@camposcloud/cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +57 -4
@@ -0,0 +1,98 @@
1
+ /** The applications of the personal account, or of `teamId` when given. */
2
+ export async function listApps(client, teamId) {
3
+ const team = teamId ? `&team=${encodeURIComponent(teamId)}` : "";
4
+ const data = await client.get(`/v1/apps?limit=100&view=summary${team}`);
5
+ return { apps: data.applications ?? [], totalUsedRAM: data.totalUsedRAM };
6
+ }
7
+ export async function getApp(client, id) {
8
+ const data = await client.get(`/v1/apps/${encodeURIComponent(id)}`);
9
+ return "application" in data ? data.application : data;
10
+ }
11
+ export function powerApp(client, id, action) {
12
+ return client.post(`/v1/apps/${encodeURIComponent(id)}/${action}`);
13
+ }
14
+ /**
15
+ * Which application `query` means: its id, its exact name (ignoring case), or a unique beginning of a name.
16
+ * Throws with the candidates when it is ambiguous or matches nothing.
17
+ */
18
+ export function resolveApp(apps, query) {
19
+ const wanted = query.trim().toLowerCase();
20
+ const byId = apps.find((app) => app._id === query.trim());
21
+ if (byId)
22
+ return byId;
23
+ const exact = apps.filter((app) => app.name.toLowerCase() === wanted);
24
+ if (exact.length === 1)
25
+ return exact[0];
26
+ const prefix = apps.filter((app) => app.name.toLowerCase().startsWith(wanted));
27
+ if (prefix.length === 1)
28
+ return prefix[0];
29
+ // Same names are told apart by their id, which `resolveApp` also accepts.
30
+ const matches = exact.length > 1 ? exact : prefix;
31
+ const candidates = matches.map((app) => (matches.filter((other) => other.name === app.name).length > 1 ? `${app.name} (${app._id})` : app.name));
32
+ throw new AppLookupError(query, candidates);
33
+ }
34
+ export class AppLookupError extends Error {
35
+ query;
36
+ candidates;
37
+ constructor(query, candidates) {
38
+ super(candidates.length ? `"${query}" matches more than one application: ${candidates.join(", ")}` : `No application named "${query}"`);
39
+ this.query = query;
40
+ this.candidates = candidates;
41
+ }
42
+ }
43
+ export function appState(app) {
44
+ if (app.status === "suspended")
45
+ return "suspended";
46
+ if (app.status === "creating")
47
+ return "creating";
48
+ return app.currentResourceMetrics?.online ? "online" : "offline";
49
+ }
50
+ export function runtimeLabel(app) {
51
+ const names = { nodejs: "Node.js", node: "Node.js", bun: "Bun", python: "Python", java: "Java", golang: "Go", go: "Go", php: "PHP", rust: "Rust", dotnet: ".NET", ruby: "Ruby" };
52
+ const name = app.runtimeEnvironment ? names[app.runtimeEnvironment.toLowerCase()] ?? app.runtimeEnvironment : "";
53
+ // Only a real version ("20", "3.12", "v1.1"): some records keep an image id there instead.
54
+ const version = app.runtimeVersion && /^v?\d[\w.-]{0,15}$/.test(app.runtimeVersion) ? app.runtimeVersion : "";
55
+ return [name, version].filter(Boolean).join(" ");
56
+ }
57
+ export function nodeName(app) {
58
+ return typeof app.workerNodeId === "object" && app.workerNodeId?.nodeName ? app.workerNodeId.nodeName : "";
59
+ }
60
+ export function formatBytes(bytes) {
61
+ if (!Number.isFinite(bytes) || bytes <= 0)
62
+ return "0 MB";
63
+ if (bytes < 1024)
64
+ return `${bytes} B`;
65
+ if (bytes < 1024 * 1024)
66
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
67
+ const mb = bytes / (1024 * 1024);
68
+ // "1 GB", "1.5 GB": no ".0" on round sizes.
69
+ return mb >= 1024 ? `${Number((mb / 1024).toFixed(mb >= 10240 ? 0 : 1))} GB` : `${Math.round(mb)} MB`;
70
+ }
71
+ export function formatMB(mb) {
72
+ return formatBytes((mb ?? 0) * 1024 * 1024);
73
+ }
74
+ /** "212 MB / 512 MB" while online; just the allocation otherwise. */
75
+ export function memoryLabel(app) {
76
+ const metrics = app.currentResourceMetrics;
77
+ const allocated = formatMB(app.allocatedMemoryMB);
78
+ return metrics?.online && metrics.memoryUsageBytes ? `${formatBytes(metrics.memoryUsageBytes)} / ${allocated}` : allocated;
79
+ }
80
+ /** Share of the allocated memory in use, 0 to 1, or null when offline. */
81
+ export function memoryShare(app) {
82
+ const metrics = app.currentResourceMetrics;
83
+ const allocated = (app.allocatedMemoryMB ?? 0) * 1024 * 1024;
84
+ if (!metrics?.online || !metrics.memoryUsageBytes || !allocated)
85
+ return null;
86
+ return Math.min(1, metrics.memoryUsageBytes / allocated);
87
+ }
88
+ export function cpuLabel(app) {
89
+ const metrics = app.currentResourceMetrics;
90
+ return metrics?.online ? `${Math.round(metrics.cpuUsagePercent ?? 0)}%` : "—";
91
+ }
92
+ export function appAddress(app) {
93
+ if (app.assignedCustomDomain)
94
+ return app.assignedCustomDomain;
95
+ if (app.exposedViaWeb && app.assignedSubdomain)
96
+ return `${app.assignedSubdomain.toLowerCase()}.camposcloud.app`;
97
+ return "";
98
+ }
@@ -0,0 +1,34 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { t } from "./i18n.js";
4
+ export const DEFAULT_API_URL = "https://api.camposcloud.com";
5
+ /** Where the CLI keeps its files: %APPDATA%\camposcloud on Windows, ~/.config/camposcloud elsewhere. */
6
+ export function configDir(env = process.env, platform = process.platform) {
7
+ if (env.CAMPOS_CONFIG_DIR)
8
+ return env.CAMPOS_CONFIG_DIR;
9
+ if (platform === "win32")
10
+ return path.join(env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"), "camposcloud");
11
+ return path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "camposcloud");
12
+ }
13
+ /**
14
+ * Which Campos Cloud to talk to: `--api-url`, then `CAMPOS_API_URL`, then production.
15
+ * During development: CAMPOS_API_URL=http://localhost:3002
16
+ */
17
+ export function resolveApiUrl(flag, env = process.env) {
18
+ const value = flag || env.CAMPOS_API_URL || DEFAULT_API_URL;
19
+ const url = new URL(value);
20
+ if (url.protocol !== "https:" && url.protocol !== "http:")
21
+ throw new Error(t("error.badApiUrl", { url: value }));
22
+ // A token travels in clear over http; only a local control may use it.
23
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
24
+ throw new Error(t("error.insecureApiUrl", { host: url.host }));
25
+ }
26
+ return url.origin;
27
+ }
28
+ /** What the site should show about this machine when it asks the person to approve it. */
29
+ export function machineInfo() {
30
+ const system = process.platform === "win32" || process.platform === "darwin"
31
+ ? os.version()
32
+ : `${os.type()} ${os.release()}`;
33
+ return { hostname: os.hostname(), os: system };
34
+ }
@@ -0,0 +1,43 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { configDir } from "./config.js";
4
+ const file = () => path.join(configDir(), "config.json");
5
+ function read() {
6
+ try {
7
+ const parsed = JSON.parse(fs.readFileSync(file(), "utf8"));
8
+ return parsed && typeof parsed === "object" ? parsed : {};
9
+ }
10
+ catch {
11
+ return {};
12
+ }
13
+ }
14
+ function write(data) {
15
+ fs.mkdirSync(path.dirname(file()), { recursive: true });
16
+ fs.writeFileSync(file(), `${JSON.stringify(data, null, 2)}\n`);
17
+ }
18
+ /** The team chosen with `campos team use`, or null for the personal account. */
19
+ export function storedTeam(apiUrl) {
20
+ return read().teams?.[apiUrl] ?? null;
21
+ }
22
+ export function storeTeam(apiUrl, team) {
23
+ const data = read();
24
+ const teams = { ...(data.teams ?? {}) };
25
+ if (team)
26
+ teams[apiUrl] = team;
27
+ else
28
+ delete teams[apiUrl];
29
+ write({ ...data, teams });
30
+ }
31
+ export function storeLanguage(lang) {
32
+ const data = read();
33
+ if (lang)
34
+ data.lang = lang;
35
+ else
36
+ delete data.lang;
37
+ write(data);
38
+ }
39
+ /** A one-off team for this command (`--team` or `CAMPOS_TEAM`), read by the commands that list or create. */
40
+ let override = process.env.CAMPOS_TEAM || undefined;
41
+ export const setTeamOverride = (value) => { if (value)
42
+ override = value; };
43
+ export const teamOverride = () => override;
@@ -0,0 +1,90 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { configDir } from "./config.js";
4
+ /**
5
+ * Where the token is kept: the system's keychain (Credential Manager, Keychain, libsecret) when there is one,
6
+ * otherwise a file only this user can read. One token per Campos Cloud address, so a local control and
7
+ * production never mix.
8
+ *
9
+ * `CAMPOS_TOKEN` (for CI and scripts) wins over anything stored and is never written anywhere.
10
+ */
11
+ const SERVICE = "camposcloud-cli";
12
+ async function loadKeychain() {
13
+ if (process.env.CAMPOS_NO_KEYRING)
14
+ return null;
15
+ try {
16
+ const { Entry } = await import("@napi-rs/keyring");
17
+ const keychain = {
18
+ get: (account) => new Entry(SERVICE, account).getPassword() ?? null,
19
+ set: (account, token) => new Entry(SERVICE, account).setPassword(token),
20
+ remove: (account) => new Entry(SERVICE, account).deletePassword(),
21
+ };
22
+ // A keychain that cannot even be read is treated as absent.
23
+ keychain.get("__probe__");
24
+ return keychain;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ const filePath = () => path.join(configDir(), "credentials.json");
31
+ function readFile() {
32
+ try {
33
+ const parsed = JSON.parse(fs.readFileSync(filePath(), "utf8"));
34
+ return parsed && typeof parsed === "object" ? parsed : {};
35
+ }
36
+ catch {
37
+ return {};
38
+ }
39
+ }
40
+ function writeFile(data) {
41
+ fs.mkdirSync(path.dirname(filePath()), { recursive: true, mode: 0o700 });
42
+ fs.writeFileSync(filePath(), JSON.stringify(data, null, 2), { mode: 0o600 });
43
+ // writeFileSync keeps the mode of a file that already existed.
44
+ try {
45
+ fs.chmodSync(filePath(), 0o600);
46
+ }
47
+ catch { /* Windows: the profile folder is already private */ }
48
+ }
49
+ export async function readToken(apiUrl) {
50
+ if (process.env.CAMPOS_TOKEN)
51
+ return { token: process.env.CAMPOS_TOKEN, source: "env" };
52
+ const keychain = await loadKeychain();
53
+ const fromKeychain = keychain?.get(apiUrl);
54
+ if (fromKeychain)
55
+ return { token: fromKeychain, source: "keyring" };
56
+ const fromFile = readFile()[apiUrl];
57
+ return fromFile ? { token: fromFile, source: "file" } : null;
58
+ }
59
+ /** Saves the token and says where it went. */
60
+ export async function saveToken(apiUrl, token) {
61
+ const keychain = await loadKeychain();
62
+ if (keychain) {
63
+ try {
64
+ keychain.set(apiUrl, token);
65
+ removeFromFile(apiUrl);
66
+ return "keyring";
67
+ }
68
+ catch {
69
+ // Falls back to the file below.
70
+ }
71
+ }
72
+ writeFile({ ...readFile(), [apiUrl]: token });
73
+ return "file";
74
+ }
75
+ export async function deleteToken(apiUrl) {
76
+ const keychain = await loadKeychain();
77
+ try {
78
+ keychain?.remove(apiUrl);
79
+ }
80
+ catch { /* nothing stored there */ }
81
+ removeFromFile(apiUrl);
82
+ }
83
+ function removeFromFile(apiUrl) {
84
+ const data = readFile();
85
+ if (!(apiUrl in data))
86
+ return;
87
+ delete data[apiUrl];
88
+ writeFile(data);
89
+ }
90
+ export const credentialsFile = filePath;
@@ -0,0 +1,53 @@
1
+ import { AppLookupError } from "./apps.js";
2
+ export async function listDbs(client, teamId) {
3
+ const team = teamId ? `&team=${encodeURIComponent(teamId)}` : "";
4
+ const data = await client.get(`/v1/databases?limit=100${team}`);
5
+ return data.databases ?? [];
6
+ }
7
+ export function powerDb(client, id, action) {
8
+ return client.post(`/v1/databases/${encodeURIComponent(id)}/${action}`);
9
+ }
10
+ /** By id, exact name (ignoring case) or a unique start of a name, like applications. */
11
+ export function resolveDb(dbs, query) {
12
+ const wanted = query.trim().toLowerCase();
13
+ const byId = dbs.find((db) => db._id === query.trim());
14
+ if (byId)
15
+ return byId;
16
+ const exact = dbs.filter((db) => db.name.toLowerCase() === wanted);
17
+ if (exact.length === 1)
18
+ return exact[0];
19
+ const prefix = dbs.filter((db) => db.name.toLowerCase().startsWith(wanted));
20
+ if (prefix.length === 1)
21
+ return prefix[0];
22
+ const matches = exact.length > 1 ? exact : prefix;
23
+ throw new AppLookupError(query, matches.map((db) => (matches.filter((other) => other.name === db.name).length > 1 ? `${db.name} (${db._id})` : db.name)));
24
+ }
25
+ export function dbState(db) {
26
+ if (db.status === "suspended")
27
+ return "suspended";
28
+ if (db.status === "creating")
29
+ return "creating";
30
+ return db.currentResourceMetrics?.online ? "online" : "offline";
31
+ }
32
+ const TYPE_LABEL = { mongodb: "MongoDB", postgresql: "PostgreSQL", postgres: "PostgreSQL", mysql: "MySQL", mariadb: "MariaDB", redis: "Redis" };
33
+ export const dbTypeLabel = (db) => TYPE_LABEL[db.type?.toLowerCase()] ?? db.type;
34
+ /**
35
+ * The connection string, the same as the dashboard shows, with `<password>` where the password goes: the API
36
+ * never returns it. Null while the database has no connection yet.
37
+ */
38
+ export function connectionUrl(db) {
39
+ const connection = db.connection;
40
+ if (!connection?.host || !connection.port)
41
+ return null;
42
+ const user = encodeURIComponent(connection.username || "");
43
+ const host = `${connection.host}:${connection.port}`;
44
+ switch (db.type?.toLowerCase()) {
45
+ case "mongodb": return `mongodb://${user}:<password>@${host}/?authSource=admin`;
46
+ case "redis": return `redis://default:<password>@${host}`;
47
+ case "postgresql":
48
+ case "postgres": return `postgresql://${user}:<password>@${host}/${encodeURIComponent(connection.database || "")}`;
49
+ case "mysql":
50
+ case "mariadb": return `mysql://${user}:<password>@${host}/${encodeURIComponent(connection.database || "")}`;
51
+ default: return null;
52
+ }
53
+ }
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ export const RUNTIMES = ["nodejs", "bun", "python"];
4
+ const NODE_CANDIDATES = [
5
+ "index.js", "index.ts", "index.mjs", "index.cjs", "main.js", "main.ts", "app.js", "app.ts", "server.js", "server.ts", "bot.js", "bot.ts",
6
+ "src/index.js", "src/index.ts", "src/main.js", "src/main.ts", "src/app.js", "src/app.ts", "dist/index.js",
7
+ ];
8
+ const PYTHON_CANDIDATES = ["main.py", "index.py", "app.py", "bot.py", "run.py", "server.py", "src/main.py", "src/app.py"];
9
+ export function detectProject(files, packageJsonText) {
10
+ const set = new Set(files);
11
+ const has = (name) => set.has(name);
12
+ let packageMain;
13
+ if (packageJsonText) {
14
+ try {
15
+ const pkg = JSON.parse(packageJsonText);
16
+ if (typeof pkg?.main === "string" && pkg.main.trim())
17
+ packageMain = pkg.main.trim().replace(/\\/g, "/").replace(/^\.\//, "");
18
+ }
19
+ catch {
20
+ // invalid package.json
21
+ }
22
+ }
23
+ const nodeMain = (packageMain && has(packageMain) ? packageMain : undefined) ?? NODE_CANDIDATES.find(has);
24
+ const pythonMain = PYTHON_CANDIDATES.find(has);
25
+ if (has("bun.lock") || has("bun.lockb") || has("bunfig.toml"))
26
+ return { runtime: "bun", mainFile: nodeMain ?? packageMain };
27
+ if (has("package.json"))
28
+ return { runtime: "nodejs", mainFile: nodeMain ?? packageMain };
29
+ if (has("requirements.txt") || has("pyproject.toml") || has("Pipfile"))
30
+ return { runtime: "python", mainFile: pythonMain };
31
+ if (pythonMain && !nodeMain)
32
+ return { runtime: "python", mainFile: pythonMain };
33
+ if (nodeMain)
34
+ return { runtime: "nodejs", mainFile: nodeMain };
35
+ const firstPy = files.find((file) => !file.includes("/") && file.endsWith(".py"));
36
+ if (firstPy)
37
+ return { runtime: "python", mainFile: firstPy };
38
+ const firstJs = files.find((file) => !file.includes("/") && /\.(js|ts|mjs|cjs)$/.test(file));
39
+ if (firstJs)
40
+ return { runtime: "nodejs", mainFile: firstJs };
41
+ return {};
42
+ }
43
+ /** `KEY=value` lines; `#`, `;` and `[section]` lines are skipped; keys are upper-cased. */
44
+ export function parseCamposConfig(text) {
45
+ const result = {};
46
+ for (const raw of text.split(/\r?\n/)) {
47
+ const line = raw.trim();
48
+ if (!line || line.startsWith("#") || line.startsWith(";") || line.startsWith("["))
49
+ continue;
50
+ const eq = line.indexOf("=");
51
+ if (eq <= 0)
52
+ continue;
53
+ const key = line.slice(0, eq).trim().toUpperCase();
54
+ let value = line.slice(eq + 1).trim();
55
+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0]))
56
+ value = value.slice(1, -1);
57
+ if (/^[A-Z_][A-Z0-9_]*$/.test(key))
58
+ result[key] = value;
59
+ }
60
+ return result;
61
+ }
62
+ export function readCamposConfig(root) {
63
+ for (const name of ["camposcloud.config", "squarecloud.config"]) {
64
+ try {
65
+ return parseCamposConfig(fs.readFileSync(path.join(root, name), "utf8"));
66
+ }
67
+ catch {
68
+ // not there
69
+ }
70
+ }
71
+ return {};
72
+ }
73
+ export const RUNTIME_LABEL = { nodejs: "Node.js", bun: "Bun", python: "Python" };
74
+ /** "Meu Bot!" → "meu-bot": a subdomain from a name. */
75
+ export const toSubdomain = (name) => name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63);
@@ -0,0 +1,49 @@
1
+ import { ApiError } from "./api.js";
2
+ /** `client` is the name the site shows: "<client> quer acessar sua conta". */
3
+ export function startDeviceLogin(client, machine) {
4
+ return client.post("/v1/cli/auth/device", machine);
5
+ }
6
+ const realSleep = (ms, signal) => new Promise((resolve) => {
7
+ const timer = setTimeout(resolve, ms);
8
+ signal?.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true });
9
+ });
10
+ export async function pollForToken(client, authorization, options = {}) {
11
+ const now = options.now ?? Date.now;
12
+ const sleep = options.sleep ?? ((ms) => realSleep(ms, options.signal));
13
+ const deadline = now() + authorization.expiresIn * 1000;
14
+ let intervalMs = Math.max(1, authorization.interval) * 1000;
15
+ // Network failures in a row: a short blip is retried, a lasting one gives up.
16
+ let failures = 0;
17
+ while (now() < deadline) {
18
+ await sleep(intervalMs);
19
+ if (options.signal?.aborted)
20
+ return { status: "cancelled" };
21
+ try {
22
+ const answer = await client.post("/v1/cli/auth/token", { deviceCode: authorization.deviceCode });
23
+ return { status: "approved", token: answer.token };
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof ApiError)) {
27
+ if (++failures >= 5)
28
+ throw error;
29
+ continue;
30
+ }
31
+ failures = 0;
32
+ switch (error.code) {
33
+ case "authorization_pending": continue;
34
+ // Asked too fast: RFC 8628 says to add five seconds to the interval.
35
+ case "slow_down":
36
+ intervalMs += 5000;
37
+ continue;
38
+ case "access_denied": return { status: "denied" };
39
+ case "expired_token": return { status: "expired" };
40
+ // Too many polls from this address: wait a little longer and try again.
41
+ case "too_many_requests":
42
+ intervalMs += 5000;
43
+ continue;
44
+ default: throw error;
45
+ }
46
+ }
47
+ }
48
+ return { status: "expired" };
49
+ }
@@ -0,0 +1,71 @@
1
+ import { getApp } from "./apps.js";
2
+ export const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
3
+ /** A `.env` file: `KEY=value`, `export KEY=value`, quotes, `#` comments. The last of a repeated key wins. */
4
+ export function parseDotEnv(text) {
5
+ const map = new Map();
6
+ for (const rawLine of text.split(/\r?\n/)) {
7
+ let line = rawLine.trim();
8
+ if (!line || line.startsWith("#"))
9
+ continue;
10
+ if (line.startsWith("export "))
11
+ line = line.slice(7).trim();
12
+ const eq = line.indexOf("=");
13
+ if (eq <= 0)
14
+ continue;
15
+ const key = line.slice(0, eq).trim();
16
+ if (!ENV_KEY.test(key))
17
+ continue;
18
+ let value = line.slice(eq + 1).trim();
19
+ const quote = value[0];
20
+ if ((quote === '"' || quote === "'" || quote === "`") && value.length >= 2 && value.endsWith(quote)) {
21
+ value = value.slice(1, -1);
22
+ if (quote === '"')
23
+ value = value.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
24
+ }
25
+ else {
26
+ const comment = value.search(/\s#/);
27
+ if (comment >= 0)
28
+ value = value.slice(0, comment).trim();
29
+ }
30
+ map.set(key, value);
31
+ }
32
+ return [...map].map(([key, value]) => ({ key, value }));
33
+ }
34
+ /** Back to `.env` text; values with spaces, quotes, # or line breaks go in double quotes. */
35
+ export function toDotEnv(vars) {
36
+ const quote = (value) => (/[\s"'#\\]/.test(value) || value === "" ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"` : value);
37
+ return vars.map(({ key, value }) => `${key}=${quote(value)}`).join("\n") + (vars.length ? "\n" : "");
38
+ }
39
+ /** `KEY=value` from the command line. */
40
+ export function parseAssignment(text) {
41
+ const eq = text.indexOf("=");
42
+ if (eq <= 0)
43
+ return null;
44
+ const key = text.slice(0, eq).trim();
45
+ return ENV_KEY.test(key) ? { key, value: text.slice(eq + 1) } : null;
46
+ }
47
+ /** Merges `changes` into `current`: same keys are replaced in place, new keys go at the end. */
48
+ export function mergeEnv(current, changes) {
49
+ const result = current.map((item) => ({ ...item }));
50
+ for (const change of changes) {
51
+ const existing = result.find((item) => item.key === change.key);
52
+ if (existing)
53
+ existing.value = change.value;
54
+ else
55
+ result.push({ ...change });
56
+ }
57
+ return result;
58
+ }
59
+ /** "abc•••••" — enough to recognise a value without showing it. */
60
+ export const maskValue = (value) => (value.length <= 4 ? "•".repeat(Math.max(4, value.length)) : `${value.slice(0, 3)}${"•".repeat(Math.min(12, value.length - 3))}`);
61
+ /** The variables, or null when the account may not see them (the API leaves them out). */
62
+ export async function readEnv(client, appId) {
63
+ const app = await getApp(client, appId);
64
+ if (!Array.isArray(app.environmentVariables))
65
+ return null;
66
+ return app.environmentVariables.map(({ key, value }) => ({ key, value: value ?? "" }));
67
+ }
68
+ /** Replaces all the variables. They take effect on the next restart. */
69
+ export function writeEnv(client, appId, vars) {
70
+ return client.post(`/v1/apps/${encodeURIComponent(appId)}/update`, { environmentVariables: vars.map(({ key, value }) => ({ key, value })) });
71
+ }
@@ -0,0 +1,51 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { unzipSync, zip } from "fflate";
4
+ import { t } from "./i18n.js";
5
+ /** Paths in the application are written from its root: "/", "/src", "/src/index.js". */
6
+ export function remotePath(input) {
7
+ const clean = (input ?? "").replace(/\\/g, "/").split("/").filter((part) => part && part !== ".").join("/");
8
+ if (clean.split("/").includes(".."))
9
+ throw new Error(t("error.pathAbove"));
10
+ return `/${clean}`;
11
+ }
12
+ const q = (value) => encodeURIComponent(value);
13
+ export async function listRemote(client, appId, dir) {
14
+ const data = await client.get(`/v1/apps/${q(appId)}/files?path=${q(dir)}`);
15
+ if (data?.isDirectory === false && typeof data.content === "string")
16
+ return { content: data.content };
17
+ return (data?.files ?? []).map((entry) => ({ ...entry, isDirectory: !!entry.isDirectory }));
18
+ }
19
+ export const downloadRemote = (client, appId, target) => client.getBuffer(`/v1/apps/${q(appId)}/download?path=${q(target)}`);
20
+ export function deleteRemote(client, appId, targets) {
21
+ return client.delete(`/v1/apps/${q(appId)}/files`, { files: targets.map((target) => target.replace(/^\/+/, "")) });
22
+ }
23
+ /**
24
+ * Writes the entries of a downloaded .zip under `destination`. An entry that would land outside it
25
+ * ("../x", an absolute path) is refused, so a crafted archive cannot write anywhere else.
26
+ */
27
+ export function extractZip(buffer, destination) {
28
+ const root = path.resolve(destination);
29
+ const entries = unzipSync(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength));
30
+ const written = [];
31
+ for (const [name, data] of Object.entries(entries)) {
32
+ const target = path.resolve(root, name);
33
+ if (target !== root && !target.startsWith(root + path.sep))
34
+ throw new Error(t("error.zipOutside", { name }));
35
+ if (name.endsWith("/")) {
36
+ fs.mkdirSync(target, { recursive: true });
37
+ continue;
38
+ }
39
+ fs.mkdirSync(path.dirname(target), { recursive: true });
40
+ fs.writeFileSync(target, data);
41
+ written.push(name);
42
+ }
43
+ return written;
44
+ }
45
+ /** One local file, zipped under its own name (to upload it into a folder of the application). */
46
+ export async function zipFile(file) {
47
+ const data = fs.readFileSync(file);
48
+ const files = { [path.basename(file)]: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) };
49
+ const zipped = await new Promise((resolve, reject) => zip(files, { level: 6 }, (error, out) => (error ? reject(error) : resolve(out))));
50
+ return Buffer.from(zipped.buffer, zipped.byteOffset, zipped.byteLength);
51
+ }