poad 2.47.0 → 2.49.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 (45) hide show
  1. package/global/cli.js +14 -0
  2. package/global/cloud/action.js +37 -0
  3. package/global/cloud/create.js +42 -0
  4. package/global/cloud/index.js +19 -0
  5. package/global/cloud/info.js +37 -0
  6. package/global/cloud/pause.js +2 -0
  7. package/global/cloud/projects.js +32 -0
  8. package/global/cloud/resume.js +2 -0
  9. package/global/cloud/upgrade.js +2 -0
  10. package/global/create.js +4 -4
  11. package/global/init.js +2 -0
  12. package/global/login.js +32 -0
  13. package/global/logout.js +14 -0
  14. package/global/ls.js +2 -0
  15. package/global/projects.js +124 -0
  16. package/global/start.js +2 -0
  17. package/global/whoami.js +13 -0
  18. package/package.json +1 -1
  19. package/poad.js +5 -2
  20. package/project/cli.js +11 -0
  21. package/project/db/index.js +2 -0
  22. package/project/db/pull.js +92 -0
  23. package/project/db/url.js +33 -0
  24. package/project/deploy.js +136 -0
  25. package/project/env/create.js +19 -0
  26. package/project/env/index.js +2 -0
  27. package/project/env/ls.js +24 -0
  28. package/project/env/rm.js +21 -0
  29. package/project/link.js +38 -0
  30. package/project/unlink.js +12 -0
  31. package/project/upgrade.js +1 -0
  32. package/test/cloud.test.js +589 -0
  33. package/test/projects.test.js +167 -0
  34. package/utils/banner.js +3 -0
  35. package/utils/cloud/api.js +120 -0
  36. package/utils/cloud/branches.js +63 -0
  37. package/utils/cloud/bundle.js +226 -0
  38. package/utils/cloud/cli.js +166 -0
  39. package/utils/cloud/credentials.js +92 -0
  40. package/utils/cloud/db.js +34 -0
  41. package/utils/cloud/device.js +66 -0
  42. package/utils/cloud/system.js +45 -0
  43. package/utils/engine.js +1 -0
  44. package/utils/help-details.js +135 -0
  45. package/utils/projects.js +338 -0
@@ -0,0 +1,166 @@
1
+ // Outils communs aux commandes cloud : options, sortie (texte ou --json),
2
+ // erreurs et codes de sortie, confirmation, projet lié.
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { CloudError, EXIT, usageError } = require('./api');
6
+
7
+ /**
8
+ * Options des mots tapés : « --env x », « --env=x », « env=x » pour les
9
+ * options à valeur ; « --yes », « -y », « yes » pour les drapeaux ; le reste
10
+ * est positionnel. Une option à valeur sans valeur : erreur d'usage.
11
+ * spec : { values: ['env', 'name'], flags: ['yes', 'json'], alias: { y: 'yes' } }
12
+ */
13
+ function parse(raw = [], { values = [], flags = [], alias = {} } = {}) {
14
+ const opts = {};
15
+ const positionals = [];
16
+ const words = raw.map(String);
17
+ for (let i = 0; i < words.length; i++) {
18
+ const w = words[i];
19
+ let m = /^--?([A-Za-z][A-Za-z0-9-]*)(?:=(.*))?$/s.exec(w);
20
+ if (m) {
21
+ let key = alias[m[1]] || m[1];
22
+ if (key.startsWith('no-') && flags.includes(key)) {
23
+ opts[key] = true;
24
+ continue;
25
+ }
26
+ if (values.includes(key)) {
27
+ let v = m[2];
28
+ if (v === undefined) {
29
+ if (i + 1 >= words.length || /^--?[A-Za-z]/.test(words[i + 1])) throw usageError(`--${key} needs a value`);
30
+ v = words[++i];
31
+ }
32
+ opts[key] = v;
33
+ } else if (flags.includes(key)) {
34
+ opts[key] = true;
35
+ } else {
36
+ throw usageError(`unknown option ${w.split('=')[0]}`);
37
+ }
38
+ continue;
39
+ }
40
+ m = /^([a-z][a-z-]*)=(.*)$/s.exec(w);
41
+ if (m && values.includes(m[1])) {
42
+ opts[m[1]] = m[2];
43
+ continue;
44
+ }
45
+ positionals.push(w);
46
+ }
47
+ return { opts, positionals };
48
+ }
49
+
50
+ const COMMON_FLAGS = ['json', 'yes'];
51
+
52
+ /** Sortie : log (texte, ignoré en --json), result (JSON en --json) */
53
+ function output(json) {
54
+ const chalk = require('chalk-v2');
55
+ return {
56
+ json,
57
+ chalk,
58
+ log: (...a) => (json ? null : console.log(...a)),
59
+ // En --json, ce qu'il faut tout de même dire à quelqu'un (code de connexion) part sur stderr
60
+ tell: (...a) => (json ? console.error(...a) : console.log(...a)),
61
+ result: (obj) => (json ? console.log(JSON.stringify(obj, null, 2)) : null),
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Exécute une commande cloud : toute erreur devient un message (ou
67
+ * { error: { code, message } } en --json) et un code de sortie.
68
+ */
69
+ async function run(raw, spec, fn) {
70
+ const json = (raw || []).some((w) => w === '--json');
71
+ const out = output(json);
72
+ try {
73
+ const { opts, positionals } = parse(raw, { ...spec, flags: [...COMMON_FLAGS, ...((spec && spec.flags) || [])] });
74
+ out.json = Boolean(opts.json);
75
+ const code = await fn({ opts, positionals, out });
76
+ if (typeof code === 'number' && code !== 0) process.exitCode = code;
77
+ } catch (err) {
78
+ const e = err instanceof CloudError ? err : new CloudError(err && err.message ? err.message : String(err), { code: 'error' });
79
+ process.exitCode = e.exit || EXIT.error;
80
+ if (out.json) console.log(JSON.stringify({ error: { code: e.code, message: e.message } }, null, 2));
81
+ else console.error(out.chalk.redBright(e.message));
82
+ }
83
+ }
84
+
85
+ const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
86
+
87
+ /**
88
+ * Confirmation : true si --yes, sinon la question dans un terminal. Hors
89
+ * terminal (ou en --json) sans --yes : CloudError (code de sortie 4).
90
+ */
91
+ async function confirm(message, { yes, json } = {}) {
92
+ if (yes) return true;
93
+ if (!interactive() || json) throw new CloudError(`Confirmation required: ${message} Add --yes to confirm outside a terminal.`, { code: 'confirmation_required', exit: EXIT.confirm });
94
+ const { confirm: ask } = require('@inquirer/prompts');
95
+ const ok = await ask({ message, default: false }).catch(() => false);
96
+ if (!ok) throw new CloudError('Cancelled: nothing was changed.', { code: 'cancelled', exit: EXIT.confirm });
97
+ return true;
98
+ }
99
+
100
+ // --- Projet local et liaison ([cloud] project de poad/config.toml) --------------
101
+
102
+ const ID_RE = /^[a-z0-9][a-z0-9-]{2,62}$/;
103
+ const BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$/;
104
+
105
+ const checkId = (id) => {
106
+ if (!ID_RE.test(String(id || ''))) throw usageError(`"${String(id).slice(0, 80)}" is not a poad.io project id (lowercase letters and digits, as shown by poad cloud projects)`);
107
+ return String(id);
108
+ };
109
+ const checkBranch = (name) => {
110
+ if (!BRANCH_RE.test(String(name || '')) || String(name).includes('..')) throw usageError(`"${String(name).slice(0, 80)}" is not a valid environment name (letters, digits, . _ - /)`);
111
+ return String(name);
112
+ };
113
+
114
+ /** poad/config.toml du dossier courant, ou null */
115
+ const projectRoot = () => require('../findpoad').findPoadDir(process.cwd());
116
+
117
+ /** Lecture seule de config.toml (jamais loadConfig : il crée des secrets) */
118
+ function readToml(root) {
119
+ return require('toml').parse(fs.readFileSync(root, 'utf8'));
120
+ }
121
+
122
+ /** Identifiant du projet cloud lié au projet local, ou null */
123
+ function linkedId(root) {
124
+ try {
125
+ const c = readToml(root);
126
+ const id = c.cloud && c.cloud.project;
127
+ return typeof id === 'string' && ID_RE.test(id) ? id : null;
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ function writeLink(root, id) {
134
+ const { setKeys } = require('../tomlfile');
135
+ setKeys(root, 'cloud', { project: checkId(id) });
136
+ require('../projects').record(root);
137
+ }
138
+
139
+ function removeLink(root) {
140
+ const { setKeys, removeSection } = require('../tomlfile');
141
+ const before = linkedId(root);
142
+ setKeys(root, 'cloud', { project: null });
143
+ try {
144
+ const c = readToml(root);
145
+ if (c.cloud && !Object.keys(c.cloud).length) removeSection(root, 'cloud');
146
+ } catch {}
147
+ require('../projects').record(root);
148
+ return before;
149
+ }
150
+
151
+ /**
152
+ * Projet cloud visé : --project, sinon celui lié au dossier courant.
153
+ * Renvoie { id, root } ; erreur d'usage sinon.
154
+ */
155
+ function targetProject(opts = {}) {
156
+ const root = projectRoot();
157
+ if (opts.project) return { id: checkId(opts.project), root };
158
+ if (!root) throw usageError('Not in a poad project folder: cd into one, or pass --project <id>.');
159
+ const id = linkedId(root);
160
+ if (!id) throw usageError('This project is not linked to poad.io: "poad link" (or "poad cloud create").');
161
+ return { id, root };
162
+ }
163
+
164
+ const rel = (p) => path.relative(process.cwd(), p) || '.';
165
+
166
+ module.exports = { parse, output, run, confirm, interactive, ID_RE, checkId, checkBranch, projectRoot, readToml, linkedId, writeLink, removeLink, targetProject, rel };
@@ -0,0 +1,92 @@
1
+ // Jetons de session poad.io de cette machine : ~/.poad/credentials.json.
2
+ //
3
+ // Écrit par poad login seulement, effacé par poad logout. Dossier 0700,
4
+ // fichier 0600, écrit par fichier temporaire (créé en 0600, jamais un fichier
5
+ // déjà là) puis renommage. Un jeton par API (POAD_CLOUD_API), pour que des
6
+ // essais contre une autre instance n'écrasent pas la session de poad.io.
7
+ // Le jeton n'est jamais affiché ni écrit ailleurs ; l'engine ne lit jamais ce
8
+ // fichier.
9
+ //
10
+ // { "version": 1, "sessions": { "<api>": { token, expires_at, account: { id, email }, created_at } } }
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+
15
+ const file = (home = os.homedir()) => path.join(home, '.poad', 'credentials.json');
16
+
17
+ const TOKEN_RE = /^[A-Za-z0-9_.~+/=-]{16,4096}$/;
18
+
19
+ function readAll(home) {
20
+ const f = file(home);
21
+ let text;
22
+ try {
23
+ const st = fs.statSync(f);
24
+ // Lisible par d'autres : ramené à 0600 avant toute lecture
25
+ if (process.platform !== 'win32' && (st.mode & 0o077) !== 0) fs.chmodSync(f, 0o600);
26
+ text = fs.readFileSync(f, 'utf8');
27
+ } catch {
28
+ return { version: 1, sessions: {} };
29
+ }
30
+ try {
31
+ const doc = JSON.parse(text);
32
+ const sessions = {};
33
+ for (const [api, e] of Object.entries((doc && doc.sessions) || {})) {
34
+ if (e && typeof e.token === 'string' && TOKEN_RE.test(e.token)) {
35
+ sessions[api] = {
36
+ token: e.token,
37
+ expires_at: typeof e.expires_at === 'string' ? e.expires_at : null,
38
+ account: e.account && typeof e.account === 'object' ? { id: String(e.account.id || ''), email: String(e.account.email || '') } : null,
39
+ created_at: typeof e.created_at === 'string' ? e.created_at : null,
40
+ };
41
+ }
42
+ }
43
+ return { version: 1, sessions };
44
+ } catch {
45
+ return { version: 1, sessions: {} };
46
+ }
47
+ }
48
+
49
+ function writeAll(doc, home) {
50
+ const f = file(home);
51
+ const dir = path.dirname(f);
52
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
53
+ if (process.platform !== 'win32' && (fs.statSync(dir).mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);
54
+ const tmp = path.join(dir, `.credentials.json.${process.pid}.${Date.now()}.tmp`);
55
+ const out = { version: 1, note: 'poad.io sessions of this machine, written by "poad login". Never shared, never read by the engine.', sessions: doc.sessions };
56
+ fs.writeFileSync(tmp, `${JSON.stringify(out, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
57
+ try {
58
+ fs.chmodSync(tmp, 0o600);
59
+ fs.renameSync(tmp, f);
60
+ } catch (err) {
61
+ try {
62
+ fs.unlinkSync(tmp);
63
+ } catch {}
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ /** Session enregistrée pour cette API, ou null */
69
+ const get = (api, home) => readAll(home).sessions[api] || null;
70
+
71
+ function set(api, { token, expires_at, account }, home) {
72
+ if (typeof token !== 'string' || !TOKEN_RE.test(token)) throw new Error('poad.io sent a token of an unexpected shape: nothing saved');
73
+ const doc = readAll(home);
74
+ doc.sessions[api] = {
75
+ token,
76
+ expires_at: typeof expires_at === 'string' ? expires_at : null,
77
+ account: account ? { id: String(account.id || ''), email: String(account.email || '') } : null,
78
+ created_at: new Date().toISOString(),
79
+ };
80
+ writeAll(doc, home);
81
+ }
82
+
83
+ /** Oublie la session de cette API ; renvoie true si elle existait */
84
+ function remove(api, home) {
85
+ const doc = readAll(home);
86
+ if (!doc.sessions[api]) return false;
87
+ delete doc.sessions[api];
88
+ writeAll(doc, home);
89
+ return true;
90
+ }
91
+
92
+ module.exports = { file, get, set, remove, readAll, TOKEN_RE };
@@ -0,0 +1,34 @@
1
+ // Connexion directe à la base d'un projet poad.io (passerelle db.poad.io).
2
+ // GET v1/projects/:id/db-password?purpose=copy|reveal|pull
3
+ // -> { user, password, host, session_port, transaction_port }
4
+ // Le mot de passe n'est gardé qu'en mémoire ; il ne s'affiche qu'avec
5
+ // --show-password (poad db url) et ne passe jamais en argument d'un processus.
6
+ const api = require('./api');
7
+
8
+ const HOST = 'db.poad.io';
9
+ const PORTS = { session: 5432, transaction: 6543 };
10
+ const MASK = '••••••••';
11
+
12
+ async function credentials(id, { env, purpose = 'copy' } = {}) {
13
+ if (env && !env.production) {
14
+ // Pas encore de route par environnement côté serveur : on ne devine pas
15
+ throw new api.CloudError(`The database of the environment "${env.branch}" is not reachable from the CLI yet (poad.io gives the password of the production database only). Use --env main.`, { code: 'unsupported' });
16
+ }
17
+ const d = await api.call('GET', `v1/projects/${api.enc(id)}/db-password?purpose=${encodeURIComponent(purpose)}`, { what: 'database password' });
18
+ if (typeof d.password !== 'string' || !d.password) throw new api.CloudError('poad.io sent no database password.', { code: 'bad_response' });
19
+ const port = (mode) => Number(mode === 'transaction' ? d.transaction_port : d.session_port) || PORTS[mode];
20
+ return {
21
+ user: typeof d.user === 'string' && d.user ? d.user : `postgres.${id}`,
22
+ password: d.password,
23
+ host: typeof d.host === 'string' && /^[A-Za-z0-9.-]+$/.test(d.host) ? d.host : HOST,
24
+ port,
25
+ };
26
+ }
27
+
28
+ /** postgresql://<user>:<mot de passe ou masque>@<hôte>:<port>/postgres?sslmode=require */
29
+ function url(c, mode = 'session', { show = false } = {}) {
30
+ const pw = show ? encodeURIComponent(c.password) : MASK;
31
+ return `postgresql://${encodeURIComponent(c.user)}:${pw}@${c.host}:${c.port(mode)}/postgres?sslmode=require`;
32
+ }
33
+
34
+ module.exports = { HOST, PORTS, MASK, credentials, url };
@@ -0,0 +1,66 @@
1
+ // Connexion par appareil (RFC 8628) à poad.io.
2
+ // POST v1/cli/device { client_name } -> { device_code, user_code, verification_uri,
3
+ // verification_uri_complete, interval, expires_in }
4
+ // POST v1/cli/token { device_code } -> 200 { token, expires_at, account: { id, email } }
5
+ // 428 authorization_pending : on attend
6
+ // 429 slow_down : intervalle + 5 s
7
+ // 410 expired_token : le code a expiré
8
+ // 403 access_denied : refusé sur poad.io
9
+ // device_code et token ne sont jamais affichés.
10
+ const os = require('os');
11
+ const api = require('./api');
12
+
13
+ const { CloudError, EXIT } = api;
14
+
15
+ async function start({ clientName = os.hostname() } = {}) {
16
+ const res = await api.raw('POST', 'v1/cli/device', { body: { client_name: String(clientName).slice(0, 100) } });
17
+ if (res.status < 200 || res.status >= 300) throw api.errorOf(res, 'login');
18
+ const d = res.data || {};
19
+ if (typeof d.device_code !== 'string' || typeof d.user_code !== 'string') throw new CloudError('poad.io answered the login request without a code.', { code: 'bad_response' });
20
+ const interval = Number.isFinite(Number(d.interval)) && Number(d.interval) >= 0 ? Number(d.interval) : 5;
21
+ const expiresIn = Number.isFinite(Number(d.expires_in)) && Number(d.expires_in) > 0 ? Number(d.expires_in) : 900;
22
+ return {
23
+ device_code: d.device_code,
24
+ user_code: d.user_code,
25
+ verification_uri: typeof d.verification_uri === 'string' ? d.verification_uri : null,
26
+ verification_uri_complete: typeof d.verification_uri_complete === 'string' ? d.verification_uri_complete : null,
27
+ interval,
28
+ expires_in: expiresIn,
29
+ };
30
+ }
31
+
32
+ const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
33
+
34
+ /**
35
+ * Attend la validation sur poad.io. Renvoie { token, expires_at, account }.
36
+ * sleep et now sont remplaçables (tests).
37
+ */
38
+ async function poll(deviceCode, { interval = 5, expiresIn = 900, sleep = sleepMs, now = Date.now, onWait } = {}) {
39
+ let wait = interval;
40
+ const deadline = now() + expiresIn * 1000;
41
+ for (;;) {
42
+ await sleep(wait * 1000);
43
+ const res = await api.raw('POST', 'v1/cli/token', { body: { device_code: deviceCode } });
44
+ const code = res.data && res.data.error && res.data.error.code;
45
+ if (res.status === 200) {
46
+ const d = res.data || {};
47
+ if (typeof d.token !== 'string' || !d.token) throw new CloudError('poad.io validated the login but sent no token.', { code: 'bad_response' });
48
+ return { token: d.token, expires_at: typeof d.expires_at === 'string' ? d.expires_at : null, account: d.account && typeof d.account === 'object' ? d.account : null };
49
+ }
50
+ if (res.status === 428 || code === 'authorization_pending') {
51
+ // on continue
52
+ } else if (res.status === 429 || code === 'slow_down') {
53
+ wait += 5;
54
+ } else if (res.status === 410 || code === 'expired_token') {
55
+ throw new CloudError('The login code has expired: run "poad login" again.', { status: 410, code: 'expired_token', exit: EXIT.auth });
56
+ } else if (res.status === 403 || code === 'access_denied') {
57
+ throw new CloudError('The login was refused on poad.io: nothing saved.', { status: 403, code: 'access_denied', exit: EXIT.auth });
58
+ } else {
59
+ throw api.errorOf(res, 'login');
60
+ }
61
+ if (onWait) onWait(wait);
62
+ if (now() + wait * 1000 > deadline) throw new CloudError('The login code has expired: run "poad login" again.', { status: 410, code: 'expired_token', exit: EXIT.auth });
63
+ }
64
+ }
65
+
66
+ module.exports = { start, poll };
@@ -0,0 +1,45 @@
1
+ // Navigateur et presse-papiers de la machine, sans dépendance.
2
+ // Le texte copié passe par l'entrée standard de l'outil, jamais en argument
3
+ // (il serait visible dans la liste des processus).
4
+ const { spawn, spawnSync } = require('child_process');
5
+
6
+ /** Ouvre une adresse https dans le navigateur ; false si impossible */
7
+ function openBrowser(url) {
8
+ if (!/^https?:\/\//.test(String(url))) return false;
9
+ const cmd = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
10
+ try {
11
+ const child = spawn(cmd[0], cmd[1], { stdio: 'ignore', detached: true });
12
+ child.on('error', () => {});
13
+ child.unref();
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ const has = (bin) => {
21
+ const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' });
22
+ return r.status === 0;
23
+ };
24
+
25
+ /** Copie le texte dans le presse-papiers ; renvoie le nom de l'outil, ou null */
26
+ function copy(text) {
27
+ const tools =
28
+ process.platform === 'darwin'
29
+ ? [['pbcopy', []]]
30
+ : process.platform === 'win32'
31
+ ? [['clip', []]]
32
+ : [
33
+ ['wl-copy', []],
34
+ ['xclip', ['-selection', 'clipboard']],
35
+ ['xsel', ['--clipboard', '--input']],
36
+ ];
37
+ for (const [bin, args] of tools) {
38
+ if (!has(bin)) continue;
39
+ const r = spawnSync(bin, args, { input: text, stdio: ['pipe', 'ignore', 'ignore'], timeout: 5000 });
40
+ if (r.status === 0) return bin;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ module.exports = { openBrowser, copy, has };
package/utils/engine.js CHANGED
@@ -97,6 +97,7 @@ const writeEngine = (root, version) => {
97
97
  const updated = text.replace(/^(\s*engine\s*=\s*)["'][^"']*["']/m, `$1"${version}"`);
98
98
  if (updated === text) return false;
99
99
  fs.writeFileSync(root, updated);
100
+ require('./projects').record(root);
100
101
  return true;
101
102
  };
102
103
 
@@ -8,6 +8,20 @@
8
8
  // notes paragraphes après les options
9
9
 
10
10
  const sheets = {
11
+ projects: {
12
+ usage: ['poad projects [--json | --all | --scan | --prune [--yes]]', 'poad ls'],
13
+ text: [
14
+ 'The poad projects of this machine: name, state (running, stopped, not started, folder gone), engine version, console URL when running, poad.io project it is linked to, last use and folder. The list comes from ~/.poad/projects.json, kept by poad init, create, start and upgrade; the state comes from one "docker ps -a". Nothing is started, stopped or deleted.',
15
+ ],
16
+ options: [
17
+ ['--json', 'the list as JSON, for a script'],
18
+ ['--all', 'also the projects whose folder no longer exists'],
19
+ ['--scan', 'look for existing projects in Docker (read only) and in this folder, and add them; done once on the first call'],
20
+ ['--prune', 'forget the projects whose folder no longer exists (their line only; containers and images: poad clean); asks first, --yes outside a terminal'],
21
+ ],
22
+ notes: ['~/.poad/projects.json holds no secret (no key, password or token), is readable by you only (0600), and is never read by the engine.'],
23
+ },
24
+ ls: { usage: ['poad ls [--json | --all | --scan | --prune [--yes]]'], text: ['Same as poad projects.'] },
11
25
  start: {
12
26
  usage: ['poad start [--all | --bare | --quiet]'],
13
27
  text: [
@@ -162,4 +176,125 @@ const alias = (of, name) => ({
162
176
  sheets.function = alias('functions', 'function');
163
177
  sheets.flow = alias('flows', 'flow');
164
178
 
179
+ // --- poad.io (projets hébergés) -------------------------------------------------
180
+ const EXIT_NOTE = 'Exit codes: 0 done, 1 error (poad.io, network), 2 usage (option, folder, link), 3 session (poad login), 4 confirmation missing or refused, 5 deploy failed.';
181
+ const API_NOTE = 'API: https://poad.io/_poad/cloud, or POAD_CLOUD_API. Session: POAD_ACCESS_TOKEN (CI) first, else the one saved by poad login.';
182
+ const PROJECT_OPT = ['--project <id>', 'a poad.io project other than the one linked to this folder'];
183
+ const JSON_OPT = ['--json', 'the result as JSON (errors too: { "error": { "code", "message" } })'];
184
+ Object.assign(sheets, {
185
+ login: {
186
+ usage: ['poad login [--no-browser] [--json]'],
187
+ text: [
188
+ 'Log this machine in to poad.io: a code is shown and its page opened in your browser; once you confirm it there, the session token is saved in ~/.poad/credentials.json (folder 0700, file 0600). The token is never shown nor written anywhere else.',
189
+ ],
190
+ options: [
191
+ ['--no-browser', 'show the address only (also without a terminal)'],
192
+ ['--json', 'the account as JSON (the code to confirm goes to stderr)'],
193
+ ],
194
+ notes: ['In CI, set POAD_ACCESS_TOKEN instead: it is used before the saved session.', API_NOTE, EXIT_NOTE],
195
+ },
196
+ logout: {
197
+ usage: ['poad logout [--json]'],
198
+ text: ['Forget the poad.io session of this machine (~/.poad/credentials.json). The token is not revoked by the CLI: revoke it on poad.io (account, CLI sessions) if it may have leaked.'],
199
+ options: [JSON_OPT],
200
+ },
201
+ whoami: { usage: ['poad whoami [--json]'], text: ['The poad.io account of the session, and where the session comes from (poad login or POAD_ACCESS_TOKEN).'], options: [JSON_OPT], notes: [EXIT_NOTE] },
202
+ cloud: {
203
+ usage: ['poad cloud <subcommand> [--json]'],
204
+ text: ['Projects hosted on poad.io. A local project is linked to one by [cloud] project = "<id>" in poad/config.toml (poad link, poad cloud create); then poad deploy, poad env, poad db url and poad db pull work on it.'],
205
+ notes: [API_NOTE, EXIT_NOTE],
206
+ },
207
+ 'cloud projects': { usage: ['poad cloud projects [--json]'], text: ['The poad.io projects of your account: id, name, state, engine, region; the one linked to this folder is marked.'], options: [JSON_OPT] },
208
+ 'cloud create': {
209
+ usage: ['poad cloud create [--name <name>] [--region paris] [--no-link] [--json]'],
210
+ text: ['Create a project on poad.io. In a poad project folder that is not linked yet, the folder is linked to it ([cloud] project in poad/config.toml).'],
211
+ options: [
212
+ ['--name <name>', 'its name (default: project_id of poad/config.toml, or the folder name)'],
213
+ ['--region <region>', 'its region (default: paris)'],
214
+ ['--no-link', 'do not link this folder'],
215
+ JSON_OPT,
216
+ ],
217
+ notes: [EXIT_NOTE],
218
+ },
219
+ 'cloud info': {
220
+ usage: ['poad cloud info [--project <id>] [--json]'],
221
+ text: ['The linked poad.io project: URL, anon key, state, engine version, region. The service_role key is never asked for nor shown.'],
222
+ options: [PROJECT_OPT, JSON_OPT],
223
+ },
224
+ 'cloud pause': { usage: ['poad cloud pause [--yes] [--project <id>] [--json]'], text: ['Pause the linked poad.io project: its API stops answering until poad cloud resume.'], options: [['--yes', 'no question (required outside a terminal)'], PROJECT_OPT, JSON_OPT], notes: [EXIT_NOTE] },
225
+ 'cloud resume': { usage: ['poad cloud resume [--project <id>] [--json]'], text: ['Resume the linked poad.io project.'], options: [PROJECT_OPT, JSON_OPT] },
226
+ 'cloud upgrade': {
227
+ usage: ['poad cloud upgrade [--to <version>] [--yes] [--project <id>] [--json]'],
228
+ text: ['Upgrade the engine of the linked poad.io project to the version poad.io offers (or --to). The project restarts.'],
229
+ options: [['--to <version>', 'a given version'], ['--yes', 'no question (required outside a terminal)'], PROJECT_OPT, JSON_OPT],
230
+ notes: [EXIT_NOTE],
231
+ },
232
+ link: {
233
+ usage: ['poad link [<id>] [--json]'],
234
+ text: [
235
+ 'Link this project to a poad.io project: writes [cloud] project = "<id>" in poad/config.toml. It holds no secret: commit it, so that the whole team deploys to the same project. Without <id>, choose in the list of your projects (in a terminal).',
236
+ ],
237
+ options: [JSON_OPT],
238
+ notes: ['poad projects shows the link of every project of this machine.', EXIT_NOTE],
239
+ },
240
+ unlink: { usage: ['poad unlink [--json]'], text: ['Remove [cloud] project from poad/config.toml. Nothing changes on poad.io.'], options: [JSON_OPT] },
241
+ env: {
242
+ usage: ['poad env ls', 'poad env create <name> [--kind persistent|preview]', 'poad env rm <name> [--yes]'],
243
+ text: [
244
+ 'Environments of the linked poad.io project: one branch each, with its own database and files; main is production. poad deploy, poad db url and poad db pull use the current git branch when an environment of that name exists, else main; --env <name> chooses.',
245
+ ],
246
+ options: [
247
+ ['ls', 'the environments (the default one is marked)'],
248
+ ['create <name>', 'a new environment; --kind persistent (default, kept) or preview (short-lived)'],
249
+ ['rm <name>', 'remove an environment with its database and files (asks first, --yes outside a terminal); main is never removed here'],
250
+ PROJECT_OPT,
251
+ JSON_OPT,
252
+ ],
253
+ notes: [EXIT_NOTE],
254
+ },
255
+ deploy: {
256
+ usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--json]'],
257
+ text: [
258
+ 'Send the poad/ folder to an environment of the linked poad.io project, which applies its pending migrations and loads its functions, flows, API, auth and storage settings.',
259
+ 'Sent: migrations, auth, storage, functions, flows, api, reference, variables (defaults, no secret), types, credentials/manifest.json (names and types only, never values), seed.sql, config.toml (without any secret key). Never sent: poad/secrets.toml, .env files, data/, backups/, node_modules, symbolic links. If a value of poad/secrets.toml appears in a file to send, nothing is sent.',
260
+ ],
261
+ options: [
262
+ ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
263
+ ['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
264
+ ['--yes', 'no question for production (required outside a terminal)'],
265
+ PROJECT_OPT,
266
+ JSON_OPT,
267
+ ],
268
+ notes: [
269
+ 'Production (main): a summary, then a confirmation (none for --dry-run, which changes nothing). Uncommitted changes in poad/: a warning, and no commit id is sent (the commit id is sent when poad/ is clean).',
270
+ EXIT_NOTE,
271
+ ],
272
+ },
273
+ 'db url': {
274
+ usage: ['poad db url [--env <name>] [--mode session|transaction] [--show-password] [--copy | --no-copy] [--json]'],
275
+ text: [
276
+ 'Connection string of the database of the linked poad.io project: postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
277
+ ],
278
+ options: [
279
+ ['--mode session', 'port 5432, long connections (psql, pg_dump, migrations); the default'],
280
+ ['--mode transaction', 'port 6543, pooled short connections (serverless functions)'],
281
+ ['--show-password', 'print the full string (it stays in your terminal history)'],
282
+ ['--copy, --no-copy', 'copy to the clipboard even outside a terminal, or never'],
283
+ ['--env <name>', 'the environment (production only for now)'],
284
+ PROJECT_OPT,
285
+ JSON_OPT,
286
+ ],
287
+ notes: [EXIT_NOTE],
288
+ },
289
+ 'db pull': {
290
+ usage: ['poad db pull [--env <name>] [--name <name>] [--json]'],
291
+ text: [
292
+ 'Write the schema of the poad.io database into a new local migration (poad/migrations/<timestamp>_cloud_main_schema.sql), with pg_dump --schema-only through db.poad.io. Engine schemas (auth, storage, _poad…) are left out. An existing migration is never overwritten.',
293
+ 'pg_dump: the one of this machine, else the one of the local engine (project started), else the command tells what to install.',
294
+ ],
295
+ options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (production only for now)'], PROJECT_OPT, JSON_OPT],
296
+ notes: [EXIT_NOTE],
297
+ },
298
+ });
299
+
165
300
  module.exports = sheets;