poad 2.77.0 → 2.78.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.
@@ -0,0 +1,368 @@
1
+ // poad doctor : ce poste peut-il faire tourner poad ? Un contrôle par ligne, ✔ / ⚠ / ✕, avec quoi faire et un lien.
2
+ //
3
+ // système macOS et Linux (priorité), Windows en bêta (dit, jamais bloquant)
4
+ // Node.js au moins la version de "engines" (package.json)
5
+ // Docker installé, démarré (le cas le plus fréquent : installé mais pas lancé), version du démon,
6
+ // architecture, place libre de son stockage, mémoire de la VM (macOS, Windows) ;
7
+ // Linux : Docker Engine (sans Desktop), droits sur le socket (groupe docker), systemd,
8
+ // host-gateway (Docker 20.10+), place lue sur le disque de /var/lib/docker
9
+ // Windows : Docker Desktop avec WSL2
10
+ // git présent (Mac neuf : le premier appel propose les outils de ligne de commande d'Apple)
11
+ // réseau Docker Hub, permalink (raw.githubusercontent.com), poad.io ; délais courts
12
+ // projet poad/config.toml lisible, image de l'engine présente, ports libres, liaison poad.io (lien et
13
+ // session valides ; le jeton n'est jamais montré)
14
+ // CLI version, et la dernière publiée
15
+ //
16
+ // Bloquant (code de sortie 1) : Node trop vieux, Docker absent / arrêté / inaccessible, git absent,
17
+ // config.toml illisible. Le reste avertit. preflight() : les seuls contrôles bloquants, pour poad init,
18
+ // start et link (moins d'une seconde quand tout va bien).
19
+ //
20
+ // Tout passe par sys (exec, fetch, fs, platform…) : les tests simulent Docker absent, arrêté, Node trop vieux…
21
+ 'use strict';
22
+ const fs = require('fs');
23
+ const os = require('os');
24
+ const path = require('path');
25
+
26
+ const LINKS = {
27
+ node: 'https://nodejs.org/en/download',
28
+ docker_mac: 'https://docs.docker.com/desktop/setup/install/mac-install/',
29
+ docker_linux: 'https://docs.docker.com/engine/install/',
30
+ docker_linux_group: 'https://docs.docker.com/engine/install/linux-postinstall/',
31
+ docker_windows: 'https://docs.docker.com/desktop/setup/install/windows-install/',
32
+ docker_wsl: 'https://docs.docker.com/desktop/features/wsl/',
33
+ docker_resources: 'https://docs.docker.com/desktop/settings-and-maintenance/settings/#resources',
34
+ git: 'https://git-scm.com/downloads',
35
+ install: 'https://github.com/poadio/cli#prerequisites',
36
+ };
37
+ const GiB = 1024 ** 3;
38
+ const DISK_WARN = 10 * GiB;
39
+ const MEM_WARN = 4 * GiB;
40
+
41
+ /** Version « 20.11.1 » ≥ « 20.0.0 » ? Pure. */
42
+ function atLeast(v, min) {
43
+ const a = String(v || '').replace(/^v/, '').split(/[.+-]/).map((x) => parseInt(x, 10) || 0);
44
+ const b = String(min || '').replace(/^[^\d]*/, '').split('.').map((x) => parseInt(x, 10) || 0);
45
+ for (let i = 0; i < 3; i++) if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
46
+ return true;
47
+ }
48
+
49
+ const minNode = () => String((require('../package.json').engines || {}).node || '>=20.0.0').replace(/^>=\s*/, '');
50
+
51
+ /** Système réel : tout ce que les contrôles demandent au poste */
52
+ function realSys() {
53
+ const { spawn } = require('child_process');
54
+ return {
55
+ platform: process.platform,
56
+ arch: process.arch,
57
+ node: process.versions.node,
58
+ env: process.env,
59
+ getuid: process.getuid ? () => process.getuid() : null,
60
+ /** { code, stdout, stderr } ; code -1 : commande introuvable (ENOENT) ; -2 : délai dépassé */
61
+ exec(cmd, args, { timeout = 5000 } = {}) {
62
+ return new Promise((resolve) => {
63
+ let out = '';
64
+ let err = '';
65
+ let done = false;
66
+ let child;
67
+ try {
68
+ child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
69
+ } catch (e) {
70
+ return resolve({ code: -1, stdout: '', stderr: e.message });
71
+ }
72
+ const timer = setTimeout(() => {
73
+ if (done) return;
74
+ done = true;
75
+ child.kill('SIGKILL');
76
+ resolve({ code: -2, stdout: out, stderr: 'timeout' });
77
+ }, timeout);
78
+ child.stdout.on('data', (d) => (out += d));
79
+ child.stderr.on('data', (d) => (err += d));
80
+ child.on('error', (e) => {
81
+ if (done) return;
82
+ done = true;
83
+ clearTimeout(timer);
84
+ resolve({ code: e.code === 'ENOENT' ? -1 : -3, stdout: '', stderr: e.message });
85
+ });
86
+ child.on('close', (code) => {
87
+ if (done) return;
88
+ done = true;
89
+ clearTimeout(timer);
90
+ resolve({ code, stdout: out, stderr: err });
91
+ });
92
+ });
93
+ },
94
+ /** Joignable ? { ok, status, ms, error } (une réponse HTTP, même 401, veut dire joignable) */
95
+ async reach(url, { timeout = 4000 } = {}) {
96
+ const t0 = Date.now();
97
+ try {
98
+ const res = await fetch(url, { method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(timeout), headers: { 'user-agent': `poad-cli/${require('../package.json').version} (doctor)` } });
99
+ await res.body?.cancel().catch(() => {});
100
+ return { ok: true, status: res.status, ms: Date.now() - t0 };
101
+ } catch (e) {
102
+ return { ok: false, error: e && e.name === 'TimeoutError' ? `no answer within ${timeout / 1000} s` : (e && e.cause && e.cause.code) || (e && e.message) || String(e), ms: Date.now() - t0 };
103
+ }
104
+ },
105
+ async json(url, { timeout = 4000 } = {}) {
106
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeout), headers: { accept: 'application/json' } });
107
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
108
+ return res.json();
109
+ },
110
+ statfs(p) {
111
+ const st = fs.statfsSync(p);
112
+ return { free: st.bavail * st.bsize, size: st.blocks * st.bsize };
113
+ },
114
+ exists: (p) => fs.existsSync(p),
115
+ readFile: (p) => fs.readFileSync(p, 'utf8'),
116
+ /** Port libre sur ce poste ? */
117
+ portFree(port) {
118
+ return new Promise((resolve) => {
119
+ const srv = require('net').createServer();
120
+ srv.once('error', () => resolve(false));
121
+ srv.once('listening', () => srv.close(() => resolve(true)));
122
+ srv.listen(port, '0.0.0.0');
123
+ });
124
+ },
125
+ home: os.homedir(),
126
+ cwd: () => process.cwd(),
127
+ };
128
+ }
129
+
130
+ const ok = (id, label, detail, extra = {}) => ({ id, status: 'ok', label, detail, ...extra });
131
+ const warn = (id, label, detail, fix, link, extra = {}) => ({ id, status: 'warn', label, detail, fix, link, ...extra });
132
+ const fail = (id, label, detail, fix, link, extra = {}) => ({ id, status: 'fail', label, detail, fix, link, blocking: true, ...extra });
133
+
134
+ const size = (n) => (n >= GiB ? `${(n / GiB).toFixed(1)} GB` : `${Math.round(n / 1024 ** 2)} MB`);
135
+
136
+ // --- Contrôles -------------------------------------------------------------------------------------------
137
+
138
+ function checkSystem(sys) {
139
+ const name = { darwin: 'macOS', linux: 'Linux', win32: 'Windows' }[sys.platform] || sys.platform;
140
+ if (sys.platform === 'win32') return warn('system', 'system', `Windows (${sys.arch}): supported in beta`, 'macOS and Linux are the main platforms; on Windows, Docker Desktop with WSL2 is needed. Tell us what breaks.', LINKS.install);
141
+ if (!['darwin', 'linux'].includes(sys.platform)) return warn('system', 'system', `${name} (${sys.arch}): not supported`, 'poad runs on macOS and Linux (Windows in beta).', LINKS.install);
142
+ return ok('system', 'system', `${name} (${sys.arch})`);
143
+ }
144
+
145
+ function checkNode(sys) {
146
+ const min = minNode();
147
+ if (atLeast(sys.node, min)) return ok('node', 'Node.js', `${sys.node} (${min} or later needed)`);
148
+ return fail('node', 'Node.js', `${sys.node}: too old, ${min} or later needed`, `Install Node.js ${min.split('.')[0]} or later (nvm install ${min.split('.')[0]}, or the installer), then "npm i -g poad" again.`, LINKS.node);
149
+ }
150
+
151
+ const dockerLink = (sys) => (sys.platform === 'darwin' ? LINKS.docker_mac : sys.platform === 'win32' ? LINKS.docker_windows : LINKS.docker_linux);
152
+
153
+ /** Docker : installé, démarré, accessible ; rend { checks, info } (info : docker info, ou null) */
154
+ async function checkDocker(sys, { quick = false } = {}) {
155
+ const checks = [];
156
+ const v = await sys.exec('docker', ['--version'], { timeout: 3000 });
157
+ if (v.code === -1) {
158
+ const how = sys.platform === 'linux' ? 'Install Docker Engine (Docker Desktop is not needed): curl -fsSL https://get.docker.com | sh, then sudo usermod -aG docker $USER and log in again.' : 'Install Docker Desktop, then start it.';
159
+ checks.push(fail('docker', 'Docker', 'not installed (no "docker" command)', how, dockerLink(sys)));
160
+ return { checks, info: null };
161
+ }
162
+ const client = (/version ([\w.+-]+)/i.exec(v.stdout) || [])[1] || '?';
163
+ const r = await sys.exec('docker', ['info', '--format', '{{json .}}'], { timeout: quick ? 4000 : 8000 });
164
+ let info = null;
165
+ try {
166
+ info = r.code === 0 ? JSON.parse(r.stdout.trim()) : null;
167
+ } catch {}
168
+ // docker info rend 0 avec ServerErrors quand le démon ne répond pas (Docker récent)
169
+ const errText = `${r.stderr || ''} ${info && Array.isArray(info.ServerErrors) ? info.ServerErrors.join(' ') : ''}`;
170
+ if (!info || !info.ServerVersion) {
171
+ if (/permission denied/i.test(errText)) {
172
+ checks.push(fail('docker_running', 'Docker access', `the Docker socket refuses this user (${(sys.env.USER || 'you')})`, 'Add yourself to the docker group: sudo usermod -aG docker $USER, then log out and in again (or: newgrp docker).', LINKS.docker_linux_group));
173
+ } else if (r.code === -2) {
174
+ checks.push(fail('docker_running', 'Docker running', 'the Docker daemon does not answer (no answer within a few seconds)', sys.platform === 'linux' ? 'Restart it: sudo systemctl restart docker' : 'Restart Docker Desktop (menu bar icon → Restart).', dockerLink(sys)));
175
+ } else {
176
+ const fix = sys.platform === 'darwin' ? 'Start Docker Desktop: open -a Docker (wait for the whale icon to stop moving), then run the command again.' : sys.platform === 'win32' ? 'Start Docker Desktop from the Start menu, then run the command again.' : 'Start the daemon: sudo systemctl start docker (and sudo systemctl enable docker to start it at boot).';
177
+ checks.push(fail('docker_running', 'Docker running', `installed (${client}) but not started`, fix, dockerLink(sys)));
178
+ }
179
+ return { checks, info: null };
180
+ }
181
+ const desktop = /docker desktop/i.test(String(info.OperatingSystem || ''));
182
+ checks.push(ok('docker_running', 'Docker running', `${desktop ? 'Docker Desktop' : 'Docker Engine'} ${info.ServerVersion}, ${info.Architecture || info.OSType || '?'}${info.OperatingSystem && !desktop ? ` (${info.OperatingSystem})` : ''}`));
183
+ if (quick) return { checks, info };
184
+ // host-gateway (host.docker.internal sur Linux) : Docker 20.10 ou plus
185
+ if (!atLeast(info.ServerVersion, '20.10.0')) checks.push(fail('docker_version', 'Docker version', `${info.ServerVersion}: too old, 20.10 or later needed (host-gateway)`, sys.platform === 'linux' ? 'Upgrade Docker Engine from the Docker repository (the distribution package is often old).' : 'Update Docker Desktop.', dockerLink(sys)));
186
+ // Architecture : l'image de l'engine existe en amd64 et arm64
187
+ const arch = String(info.Architecture || '');
188
+ if (arch && !/x86_64|amd64|aarch64|arm64/i.test(arch)) checks.push(warn('docker_arch', 'Docker architecture', `${arch}: the engine image is built for amd64 and arm64 only`, null, LINKS.install));
189
+ if (sys.platform === 'win32') {
190
+ const wsl = /wsl|microsoft/i.test(`${info.KernelVersion || ''} ${info.OperatingSystem || ''}`);
191
+ checks.push(wsl ? ok('docker_wsl', 'WSL2', 'Docker Desktop runs on WSL2') : warn('docker_wsl', 'WSL2', 'Docker Desktop does not seem to use WSL2', 'Docker Desktop → Settings → General → "Use the WSL 2 based engine".', LINKS.docker_wsl));
192
+ }
193
+ if (sys.platform === 'linux' && desktop) checks.push(warn('docker_engine', 'Docker Engine', 'Docker Desktop for Linux: it works, but Docker Engine alone is lighter and what poad is tested with', null, LINKS.docker_linux));
194
+ if (sys.platform === 'linux' && !desktop) {
195
+ const sd = await sys.exec('systemctl', ['is-enabled', 'docker'], { timeout: 2000 });
196
+ if (sd.code !== -1 && sd.stdout.trim() && sd.stdout.trim() !== 'enabled') checks.push(warn('docker_boot', 'Docker at boot', `the docker service is ${sd.stdout.trim()}: it will not start by itself after a reboot`, 'sudo systemctl enable docker', LINKS.docker_linux_group));
197
+ }
198
+ // Mémoire de la VM (macOS, Windows)
199
+ const mem = Number(info.MemTotal) || 0;
200
+ if (sys.platform !== 'linux' && mem) {
201
+ if (mem < MEM_WARN) checks.push(warn('docker_memory', 'Docker memory', `${size(mem)} given to the Docker VM: 4 GB or more is advised (engine, database, functions)`, 'Docker Desktop → Settings → Resources → Memory.', LINKS.docker_resources));
202
+ else checks.push(ok('docker_memory', 'Docker memory', `${size(mem)} given to the Docker VM`));
203
+ }
204
+ checks.push(await checkDockerDisk(sys, info));
205
+ return { checks, info };
206
+ }
207
+
208
+ /** Place libre du stockage de Docker : Linux, le disque de DockerRootDir ; macOS / Windows, le disque du poste (le disque de la VM y grandit) */
209
+ async function checkDockerDisk(sys, info) {
210
+ const candidates = sys.platform === 'linux' ? [info.DockerRootDir || '/var/lib/docker', '/var/lib', '/'] : [path.join(sys.home, 'Library', 'Containers', 'com.docker.docker'), sys.home];
211
+ for (const p of candidates) {
212
+ let st;
213
+ try {
214
+ st = sys.statfs(p);
215
+ } catch {
216
+ continue;
217
+ }
218
+ const where = sys.platform === 'linux' ? `disk of ${info.DockerRootDir || '/var/lib/docker'}` : 'disk of this machine (the Docker VM disk grows on it)';
219
+ if (st.free < DISK_WARN) return warn('docker_disk', 'Docker disk', `${size(st.free)} free on the ${where}: 10 GB or more is advised`, 'Free some room: poad clean, then docker system prune (unused images and containers).', LINKS.install, { free: st.free });
220
+ return ok('docker_disk', 'Docker disk', `${size(st.free)} free on the ${where}`, { free: st.free });
221
+ }
222
+ return warn('docker_disk', 'Docker disk', 'free room unknown (not readable)', null, null);
223
+ }
224
+
225
+ async function checkGit(sys) {
226
+ // Mac neuf : /usr/bin/git existe mais n'est qu'un renvoi vers les outils de ligne de commande d'Apple
227
+ if (sys.platform === 'darwin') {
228
+ const x = await sys.exec('xcode-select', ['-p'], { timeout: 2000 });
229
+ if (x.code !== 0) return warn('git', 'git', 'the Apple command line tools are not installed: the first "git" call opens a window to install them', 'Install them now: xcode-select --install', LINKS.git);
230
+ }
231
+ const g = await sys.exec('git', ['--version'], { timeout: 3000 });
232
+ if (g.code !== 0) return fail('git', 'git', 'not installed', sys.platform === 'linux' ? 'Install it: sudo apt install git (Debian, Ubuntu), sudo dnf install git (Fedora)…' : sys.platform === 'win32' ? 'Install Git for Windows.' : 'Install it: xcode-select --install', LINKS.git);
233
+ return ok('git', 'git', g.stdout.trim().replace(/^git version /, ''));
234
+ }
235
+
236
+ async function checkNetwork(sys) {
237
+ const api = (() => {
238
+ try {
239
+ return require('./cloud/api').apiBase(sys.env);
240
+ } catch {
241
+ return 'https://poad.io/_poad/cloud';
242
+ }
243
+ })();
244
+ const targets = [
245
+ ['net_dockerhub', 'Docker Hub', 'https://registry-1.docker.io/v2/', 'engine images are pulled from there'],
246
+ ['net_permalink', 'permalink', 'https://raw.githubusercontent.com/poadio/permalink/refs/heads/main/poad.json', 'versions proposed by the CLI'],
247
+ ['net_poadio', 'poad.io', `${api}/v1/health`, 'hosted projects, poad push / pull'],
248
+ ];
249
+ const res = await Promise.all(targets.map(([, , url]) => sys.reach(url, { timeout: 4000 })));
250
+ return targets.map(([id, label, url, why], i) => {
251
+ const r = res[i];
252
+ const host = new URL(url).host;
253
+ return r.ok ? ok(id, `network: ${label}`, `${host} answers (${r.ms} ms)`) : warn(id, `network: ${label}`, `${host} not reachable (${r.error}): ${why}`, 'Check the connection, a proxy (HTTPS_PROXY) or a firewall.', null);
254
+ });
255
+ }
256
+
257
+ /** Le dossier poad du projet courant : config lisible, image présente, ports, liaison poad.io */
258
+ async function checkProject(sys, root, { info } = {}) {
259
+ const checks = [];
260
+ let config;
261
+ try {
262
+ config = require('toml').parse(sys.readFile(root));
263
+ } catch (e) {
264
+ checks.push(fail('project_config', 'poad/config.toml', `not readable: ${String(e.message).split('\n')[0]}`, 'Fix the line named above (TOML syntax), or restore it from git: git checkout poad/config.toml', LINKS.install));
265
+ return checks;
266
+ }
267
+ checks.push(ok('project_config', 'poad/config.toml', `${config.project_id || '?'}, engine ${config.engine || '?'}`));
268
+ const container = config.project_uuid;
269
+ let running = false;
270
+ if (info && container) {
271
+ const ps = await sys.exec('docker', ['ps', '--filter', `name=^${container}$`, '--format', '{{.Names}}'], { timeout: 4000 });
272
+ running = ps.code === 0 && ps.stdout.trim() === container;
273
+ }
274
+ if (info && config.engine) {
275
+ const img = `poadio/engine:${config.engine}`;
276
+ const r = await sys.exec('docker', ['image', 'inspect', '--format', '{{.Id}}', img], { timeout: 4000 });
277
+ checks.push(r.code === 0 ? ok('project_image', 'engine image', `${img} present`) : warn('project_image', 'engine image', `${img} not on this machine: poad start pulls it (about 1 GB)`, null, null));
278
+ }
279
+ // Ports : seulement quand le projet ne tourne pas (sinon ils sont à lui)
280
+ if (!running) {
281
+ const ports = [];
282
+ for (const [k, v] of Object.entries(config)) if (v && typeof v === 'object' && Number.isInteger(v.port) && v.port > 0) ports.push([k, v.port]);
283
+ const busy = [];
284
+ for (const [k, p] of ports) if (!(await sys.portFree(p))) busy.push(`${p} (${k})`);
285
+ checks.push(busy.length ? warn('project_ports', 'ports', `used by something else: ${busy.join(', ')}`, 'poad start takes a free port instead and writes it in poad/config.toml; or stop what uses them.', null) : ok('project_ports', 'ports', ports.length ? `${ports.map(([, p]) => p).join(', ')} free` : 'none configured'));
286
+ } else checks.push(ok('project_ports', 'ports', 'the project runs: its ports are its own'));
287
+ // Liaison poad.io : le lien, et une session valide (le jeton n'est jamais montré)
288
+ const id = config.cloud && config.cloud.project;
289
+ if (id) {
290
+ const api = require('./cloud/api');
291
+ let t = null;
292
+ try {
293
+ t = api.currentToken(sys.env);
294
+ } catch {}
295
+ if (!t) checks.push(warn('project_link', 'poad.io link', `linked to ${id}, but no session on this machine`, 'poad login', null));
296
+ else {
297
+ try {
298
+ await (sys.cloudCall || api.call)('GET', `v1/projects/${api.enc(id)}`, { what: 'project', timeout: 5000, env: sys.env });
299
+ checks.push(ok('project_link', 'poad.io link', `${id}, session valid${t.source === 'env' ? ' (POAD_ACCESS_TOKEN)' : ''}`));
300
+ } catch (e) {
301
+ checks.push(warn('project_link', 'poad.io link', `${id}: ${e.status === 401 ? 'session expired or revoked' : e.status === 404 ? 'project not found for this account' : e.message}`, e.status === 401 ? 'poad login' : e.status === 404 ? 'poad link <id> (poad cloud projects lists yours)' : null, null));
302
+ }
303
+ }
304
+ } else checks.push(ok('project_link', 'poad.io link', 'not linked (poad link <id> to push to poad.io)'));
305
+ return { checks, running, container, config };
306
+ }
307
+
308
+ async function checkCli(sys) {
309
+ const current = require('../package.json').version;
310
+ try {
311
+ const latest = (await (sys.npmLatest ? sys.npmLatest() : sys.json('https://registry.npmjs.org/poad/latest', { timeout: 4000 }))).version;
312
+ if (latest && atLeast(current, latest)) return ok('cli', 'poad CLI', `${current} (latest)`);
313
+ return warn('cli', 'poad CLI', `${current}, ${latest} is out`, `npm i -g poad@${latest}`, 'https://www.npmjs.com/package/poad');
314
+ } catch (e) {
315
+ return ok('cli', 'poad CLI', `${current} (latest version not checked: ${e.message})`);
316
+ }
317
+ }
318
+
319
+ /** Tous les contrôles ; root : poad/config.toml du dossier courant, ou null */
320
+ async function run(sys = realSys(), { root = null, network = true } = {}) {
321
+ const checks = [checkSystem(sys), checkNode(sys)];
322
+ const [d, git, net, cli] = await Promise.all([checkDocker(sys), checkGit(sys), network ? checkNetwork(sys) : [], network ? checkCli(sys) : null]);
323
+ checks.push(...d.checks, git, ...net);
324
+ let project = null;
325
+ if (root) {
326
+ const p = await checkProject(sys, root, { info: d.info });
327
+ project = Array.isArray(p) ? { checks: p } : p;
328
+ checks.push(...project.checks);
329
+ }
330
+ if (cli) checks.push(cli);
331
+ return { checks, ok: !checks.some((c) => c.status === 'fail'), project };
332
+ }
333
+
334
+ /** Contrôles bloquants seulement (poad init, start, link) : Node, Docker démarré, git ; rapide */
335
+ async function preflight(sys = realSys(), { docker = true, git = true } = {}) {
336
+ const checks = [checkNode(sys)];
337
+ const [d, g] = await Promise.all([docker ? checkDocker(sys, { quick: true }) : { checks: [] }, git ? checkGit(sys) : null]);
338
+ checks.push(...d.checks);
339
+ if (g) checks.push(g);
340
+ return { checks, ok: !checks.some((c) => c.status === 'fail'), failed: checks.filter((c) => c.status === 'fail') };
341
+ }
342
+
343
+ /** Lignes d'affichage d'un contrôle. Pure. */
344
+ function lines(c, chalk) {
345
+ const mark = c.status === 'ok' ? chalk.greenBright('✔') : c.status === 'warn' ? chalk.yellowBright('⚠') : chalk.redBright('✕');
346
+ const out = [`${mark} ${chalk.bold(c.label)} ${c.status === 'fail' ? chalk.redBright(c.detail) : c.detail}`];
347
+ if (c.fix) out.push(` ${chalk.grey('→')} ${c.fix}`);
348
+ if (c.link && c.status !== 'ok') out.push(` ${chalk.grey(c.link)}`);
349
+ return out;
350
+ }
351
+
352
+ /**
353
+ * Avant poad init / start / link : les contrôles bloquants ; un ✕ arrête la commande avec un message clair.
354
+ * Rend true si tout va bien. POAD_SKIP_PREFLIGHT=1 : rien (tests, CI particulière).
355
+ */
356
+ async function guard(what, { docker = true, git = true, sys } = {}) {
357
+ if (process.env.POAD_SKIP_PREFLIGHT === '1') return true;
358
+ const r = await preflight(sys || realSys(), { docker, git });
359
+ if (r.ok) return true;
360
+ const chalk = require('chalk-v2');
361
+ console.error(chalk.redBright(`poad ${what} cannot run on this machine yet:`));
362
+ for (const c of r.failed) for (const l of lines(c, chalk)) console.error(` ${l}`);
363
+ console.error(chalk.grey(' "poad doctor" checks everything (network, disk, project…).'));
364
+ process.exitCode = 1;
365
+ return false;
366
+ }
367
+
368
+ module.exports = { run, preflight, guard, lines, atLeast, minNode, realSys, checkDocker, checkGit, checkNode, checkSystem, checkNetwork, checkProject, checkCli, LINKS };
@@ -428,6 +428,23 @@ Object.assign(sheets, {
428
428
  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.'],
429
429
  options: [JSON_OPT],
430
430
  },
431
+ doctor: {
432
+ usage: ['poad doctor [--json] [--offline]'],
433
+ text: [
434
+ 'Check this machine for poad, one line per check (✔ fine, ⚠ warning, ✕ blocking), each problem with what to do and a link: the system (macOS and Linux; Windows in beta), Node.js, Docker (installed, started, daemon version, architecture, free room of its storage, memory of its VM on macOS and Windows), git, the network (Docker Hub, the permalink on raw.githubusercontent.com, poad.io) and the CLI version.',
435
+ 'Linux: Docker Engine is enough (no Docker Desktop); your user must be allowed on the Docker socket (docker group), the daemon run (systemd), Docker be 20.10 or later (host-gateway); the free room is read on the disk of /var/lib/docker. Windows: Docker Desktop with WSL2, and git.',
436
+ 'In a project folder, also: poad/config.toml readable, the engine image of the project on this machine, its ports free (when it is stopped), and its poad.io link with a valid session. The session token is never shown.',
437
+ ],
438
+ options: [
439
+ ['--json', 'the checks as JSON: { ok, platform, checks: [{ id, status: ok|warn|fail, label, detail, fix, link }] }'],
440
+ ['--offline', 'skip the network checks and the latest CLI version'],
441
+ ],
442
+ notes: [
443
+ 'poad init, poad start and poad link run the blocking checks first (Node.js, git; Docker started for init and start), in less than a second, and stop with the same message instead of an obscure error.',
444
+ 'Prerequisites of poad: Node.js, Docker and git. psql is not needed (the engine has its own).',
445
+ 'Exit codes: 0 ready (warnings allowed), 1 at least one blocking problem, 2 usage.',
446
+ ],
447
+ },
431
448
  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] },
432
449
  cloud: {
433
450
  usage: ['poad cloud <subcommand> [--json]'],
@@ -516,6 +533,7 @@ Object.assign(sheets, {
516
533
  'A preview always comes first, part by part and table by table: rows added (+), replaced (~), deleted (-) and identical, compared row by row with fingerprints of the primary key and of each row (never a value; above 200,000 rows a table is compared by counts only), sizes, room left on the target. An identical table is not rewritten.',
517
534
  'Base and auth go in ONE transaction, through the direct database access of poad.io (db.poad.io), run by the PostgreSQL tools of the local engine: the source is read in one consistent snapshot, the target is written with triggers and foreign keys paused during the load (nothing cascades), sequences are set as on the source; any error and nothing changes. Sessions and refresh tokens of the target are closed (accounts sign in again there), confirmation and recovery tokens are emptied. The structure must match first: a table missing or different on the target stops the base part before anything is written, and the code part (when chosen) runs first and is checked again after it.',
518
535
  'Secrets only with --with-secrets, after a confirmation of their own: the values of the variables of the engine and the credentials (fields, uses, vault values), except those of the storage, which each environment keeps. Values are never shown, written to a file or logged; keys of the engine, auth provider secrets and MCP tokens are never copied.',
536
+ 'OAuth authorizations are never copied, not even with --with-secrets: neither the authorization of the project (an OAuth connection authorized from the console) nor the accounts that end users connected (per_user connections). An authorization is given to one environment: the preview names each OAuth connection ("OAuth connection todoist: authorize again on the target"), and each user connects their account again on the target. With the auth part, accounts that leave the target take their connected OAuth accounts with them (engine 0.83+).',
519
537
  'Files: compared by name, size and checksum (MD5): what is already there is not sent again, a truncated or different object is. Above 6 MiB a file goes in resumable chunks (read from the source by ranges): an upload cut by the network, or by the end of the command, goes on from where the target is at the next run. The timeout is one of inactivity (an upload that moves is never cut); a passing error (network, timeout, 5xx, 429) is tried again after 1 s, 2 s, 4 s… and the number of transfers at once halves while errors come, then goes back up. Each file sent is read back on the target (size and checksum).',
520
538
  'Run again: poad push resumes. Code is deployed again (idempotent), identical tables and accounts are not rewritten (and production is not backed up again when the base has nothing to write), files already there are skipped. Failed files are summed up at the end (the first 5; all of them in --json and in the logs), with the command to run again; exit code 5.',
521
539
  ],
@@ -525,7 +543,7 @@ Object.assign(sheets, {
525
543
  ['--only <parts>', 'only these parts: code, base, auth, s3, refs (comma separated)'],
526
544
  ['--skip <parts>', 'all parts but these'],
527
545
  ['--tables <a,b>', 'only these tables of the base part (table or schema.table)'],
528
- ['--with-secrets', 'also the values of variables and credentials (asks separately)'],
546
+ ['--with-secrets', 'also the values of variables and credentials (asks separately); never OAuth authorizations'],
529
547
  ['--clean', 'free the room first: the tables to rewrite are emptied (TRUNCATE, in a transaction of its own) and the files to replace removed before the copy; identical ones are kept. Not all or nothing any more: a failure leaves them empty until the next run'],
530
548
  ['--allow-destructive', 'passed to poad deploy (alias --accept-data-loss): migrations that lose data are applied on production without asking'],
531
549
  ['--yes', 'no question (required outside a terminal)'],
@@ -545,7 +563,7 @@ Object.assign(sheets, {
545
563
  text: [
546
564
  'The other way of poad push: make the local project the mirror of an environment of poad.io, part by part: code (the migrations written there, by poad migration pull, then the deployed files of queries, auth, storage, functions, flows, api, reference, sources, transforms, connections, variables and seed.sql, then poad migrate), base, auth, refs (the reference tables of the store, loaded into the local engine), s3 (files of the storage).',
547
565
  'A local file is replaced or removed only when git tracks it without uncommitted change; otherwise it is kept and named (commit or stash it, then pull again). Migrations are never overwritten (a version used here under another name is a conflict, said and left alone).',
548
- 'Same preview, same single transaction for base and auth, same structure check and same --with-secrets as poad push. Before writing a local database that holds rows, a backup: poad/backups/<timestamp>-pre-pull.dump (pg_dump custom format, outside git; pg_restore brings it back).',
566
+ 'Same preview, same single transaction for base and auth, same structure check and same --with-secrets as poad push; OAuth authorizations are never copied either (authorize again locally, users connect again). Before writing a local database that holds rows, a backup: poad/backups/<timestamp>-pre-pull.dump (pg_dump custom format, outside git; pg_restore brings it back).',
549
567
  ],
550
568
  options: [
551
569
  ['--env <name>', 'the environment to read (default: the current git branch if it exists on poad.io, else main); never written'],
@@ -553,7 +571,7 @@ Object.assign(sheets, {
553
571
  ['--only <parts>', 'only these parts: code, base, auth, s3, refs'],
554
572
  ['--skip <parts>', 'all parts but these'],
555
573
  ['--tables <a,b>', 'only these tables of the base part'],
556
- ['--with-secrets', 'also the values of variables and credentials (asks separately)'],
574
+ ['--with-secrets', 'also the values of variables and credentials (asks separately); never OAuth authorizations'],
557
575
  ['--clean', 'free the room first (as for poad push)'],
558
576
  ['--yes', 'no question (required outside a terminal)'],
559
577
  PROJECT_OPT,
@@ -0,0 +1,198 @@
1
+ // Progression des transferts longs (poad push / pull, poad deploy, poad ref push) : une ligne sur stderr,
2
+ // réécrite au plus 4 fois par seconde, seulement dans un terminal et seulement quand le transfert dure plus
3
+ // de 2 s. Hors terminal (redirection vers un fichier, CI) : pas de barre, une ligne simple sans couleur toutes
4
+ // les 15 s. En --json : un événement JSON sur stderr toutes les 5 s (stdout garde le résultat seul).
5
+ //
6
+ // const p = progress.start({ label: 'public.commune', total: 525e6, unit: 'bytes', rowsTotal: 35247, json })
7
+ // p.update(bytes, { rows, file }) p.log(line) (écrit une ligne au-dessus de la barre) p.end()
8
+ //
9
+ // Une ligne : « public.commune [██████░░░░░░] 48 % 12,345 / 35,247 rows 251.2 MB sent 1.2 MB/s ETA 3 min 40 s »
10
+ // Débit : sur les 10 dernières secondes (une connexion qui ralentit se voit vite). Aucune dépendance.
11
+ 'use strict';
12
+
13
+ const SHOW_AFTER_MS = 2000;
14
+ const REDRAW_MS = 250;
15
+ const JSON_EVERY_MS = 5000;
16
+ const PLAIN_EVERY_MS = 15000;
17
+ const WINDOW_MS = 10000;
18
+
19
+ const size = (n) => {
20
+ const v = Math.max(0, Number(n) || 0);
21
+ if (v < 1024) return `${Math.round(v)} B`;
22
+ if (v < 1024 ** 2) return `${(v / 1024).toFixed(1)} KB`;
23
+ if (v < 1024 ** 3) return `${(v / 1024 ** 2).toFixed(1)} MB`;
24
+ return `${(v / 1024 ** 3).toFixed(2)} GB`;
25
+ };
26
+ const count = (n) => Math.round(Number(n) || 0).toLocaleString('en-US');
27
+
28
+ /** Durée lisible : 42 s, 3 min 40 s, 1 h 05 min. Pure. */
29
+ function duration(s) {
30
+ const v = Math.max(0, Math.round(Number(s) || 0));
31
+ if (v < 60) return `${v} s`;
32
+ if (v < 3600) return `${Math.floor(v / 60)} min ${String(v % 60).padStart(2, '0')} s`;
33
+ return `${Math.floor(v / 3600)} h ${String(Math.floor((v % 3600) / 60)).padStart(2, '0')} min`;
34
+ }
35
+
36
+ /** Barre de largeur w pour une fraction 0..1. Pure. */
37
+ function barOf(fraction, w = 20) {
38
+ const f = Math.min(1, Math.max(0, Number(fraction) || 0));
39
+ const full = Math.round(f * w);
40
+ return `${'█'.repeat(full)}${'░'.repeat(w - full)}`;
41
+ }
42
+
43
+ /** Débit sur une fenêtre glissante : add(t, done) ; rate() en unités par seconde */
44
+ function meter(windowMs = WINDOW_MS) {
45
+ const samples = [];
46
+ return {
47
+ add(t, done) {
48
+ samples.push([t, done]);
49
+ while (samples.length > 2 && t - samples[0][0] > windowMs) samples.shift();
50
+ },
51
+ rate() {
52
+ if (samples.length < 2) return 0;
53
+ const [t0, d0] = samples[0];
54
+ const [t1, d1] = samples[samples.length - 1];
55
+ return t1 > t0 ? ((d1 - d0) * 1000) / (t1 - t0) : 0;
56
+ },
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Texte d'une ligne de progression (sans couleur ; chalk facultatif). Pure.
62
+ * s : { label, done, total, unit: 'bytes'|'count', rows, rowsTotal, files, filesTotal, rate, eta, file, phase }
63
+ * Les éléments sont séparés par deux espaces, jamais collés.
64
+ */
65
+ function line(s, { chalk = null, width = 0 } = {}) {
66
+ const grey = (x) => (chalk ? chalk.grey(x) : x);
67
+ const parts = [];
68
+ if (s.label) parts.push(chalk ? chalk.bold(s.label) : s.label);
69
+ if (s.phase) parts.push(grey(s.phase));
70
+ // Fraction : les lignes quand leur total est connu (exact), sinon les octets, sinon les fichiers
71
+ const frac = s.rowsTotal > 0 && Number.isFinite(s.rows) ? s.rows / s.rowsTotal : s.total > 0 ? s.done / s.total : s.filesTotal > 0 && Number.isFinite(s.files) ? s.files / s.filesTotal : null;
72
+ if (frac !== null) parts.push(s.plain ? `${Math.min(100, Math.floor(frac * 100))} %` : `${chalk ? chalk.cyan(barOf(frac)) : barOf(frac)} ${String(Math.min(100, Math.floor(frac * 100))).padStart(3)} %`);
73
+ if (s.filesTotal > 0) parts.push(`${count(s.files)} / ${count(s.filesTotal)} files`);
74
+ if (Number.isFinite(s.rows)) parts.push(s.rowsTotal > 0 ? `${count(s.rows)} / ${count(s.rowsTotal)} rows` : `${count(s.rows)} rows`);
75
+ const unit = s.unit === 'count' ? count : size;
76
+ // Lignes comptées : leur total fait foi, celui des octets n'est qu'une estimation (taille sur disque), non montrée
77
+ const byteTotal = s.rowsTotal > 0 && Number.isFinite(s.rows) ? 0 : s.total;
78
+ if (Number.isFinite(s.done) && (byteTotal > 0 || s.done > 0)) parts.push(byteTotal > 0 ? `${unit(s.done)} / ${unit(byteTotal)}` : byteTotal === s.total ? unit(s.done) : `${unit(s.done)} sent`);
79
+ if (s.rate > 0) parts.push(s.unit === 'count' ? `${count(s.rate)}/s` : `${size(s.rate)}/s`);
80
+ if (Number.isFinite(s.eta) && s.eta > 0) parts.push(`ETA ${duration(s.eta)}`);
81
+ else if (Number.isFinite(s.elapsed)) parts.push(duration(s.elapsed));
82
+ if (s.file) parts.push(grey(s.file));
83
+ let text = ` ${parts.join(' ')}`;
84
+ // Plus large que le terminal : la ligne serait repliée et la réécriture laisserait des restes ; le nom
85
+ // du fichier en cours est raccourci d'abord
86
+ if (width > 0) {
87
+ const plain = text.replace(/\x1b\[[0-9;]*m/g, '');
88
+ if (plain.length > width - 1 && s.file) {
89
+ const keep = Math.max(8, s.file.length - (plain.length - width + 2));
90
+ return line({ ...s, file: `…${s.file.slice(-keep + 1)}` }, { chalk, width: 0 });
91
+ }
92
+ }
93
+ return text;
94
+ }
95
+
96
+ /**
97
+ * Démarre une progression. opts : { label, total, unit, rowsTotal, filesTotal, json, part, table, stream, now,
98
+ * tty, chalk }. Rend { update(done, extra), set(extra), log(text), end(), stats() }.
99
+ */
100
+ function start(opts = {}) {
101
+ const stream = opts.stream || process.stderr;
102
+ const now = opts.now || Date.now;
103
+ const tty = opts.tty !== undefined ? opts.tty : Boolean(stream.isTTY);
104
+ const chalk = opts.chalk || require('chalk-v2');
105
+ const t0 = now();
106
+ const m = meter();
107
+ const st = { label: opts.label || '', phase: opts.phase || '', done: 0, total: Number(opts.total) || 0, unit: opts.unit || 'bytes', rows: opts.rows, rowsTotal: Number(opts.rowsTotal) || 0, files: opts.filesTotal ? 0 : undefined, filesTotal: Number(opts.filesTotal) || 0, file: '' };
108
+ let shown = false;
109
+ let lastDraw = 0;
110
+ let lastJson = 0;
111
+ let lastPlain = -Infinity;
112
+ let ended = false;
113
+ let timer = null;
114
+
115
+ const snapshot = () => {
116
+ const t = now();
117
+ const rate = m.rate();
118
+ let eta = null;
119
+ // Temps restant : sur ce qui donne la fraction (lignes, fichiers, octets), au débit actuel
120
+ // Lignes connues (exactes) : reste en lignes × octets mesurés par ligne ÷ débit récent ;
121
+ // le total d'octets d'une table n'est qu'une estimation (taille sur disque, pas le texte du COPY)
122
+ if (rate > 0 && st.rowsTotal > 0 && Number.isFinite(st.rows) && st.rows > 0 && st.done > 0) eta = st.rows < st.rowsTotal ? ((st.rowsTotal - st.rows) * (st.done / st.rows)) / rate : null;
123
+ else if (rate > 0 && st.total > st.done) eta = (st.total - st.done) / rate;
124
+ else if (st.rowsTotal > 0 && Number.isFinite(st.rows) && st.rows > 0 && st.rows < st.rowsTotal) eta = ((t - t0) / 1000) * (st.rowsTotal / st.rows - 1);
125
+ return { ...st, rate, eta, elapsed: (t - t0) / 1000 };
126
+ };
127
+ const draw = (force = false) => {
128
+ if (ended) return;
129
+ const t = now();
130
+ if (t - t0 < SHOW_AFTER_MS) return;
131
+ if (opts.json) {
132
+ if (!force && t - lastJson < JSON_EVERY_MS) return;
133
+ lastJson = t;
134
+ const s = snapshot();
135
+ const ev = { event: 'progress', part: opts.part || undefined, table: opts.table || undefined, label: s.label || undefined, phase: s.phase || undefined, done: Math.round(s.done), total: s.total || undefined, unit: s.unit, rows: Number.isFinite(s.rows) ? s.rows : undefined, rows_total: s.rowsTotal || undefined, files: Number.isFinite(s.files) ? s.files : undefined, files_total: s.filesTotal || undefined, rate: Math.round(s.rate), eta_s: s.eta ? Math.round(s.eta) : undefined, elapsed_s: Math.round(s.elapsed) };
136
+ stream.write(`${JSON.stringify(ev)}\n`);
137
+ return;
138
+ }
139
+ if (!tty) {
140
+ // Lignes espacées, sans barre ni retour chariot : un fichier de journal reste lisible
141
+ if (opts.plain === false || (!force && t - lastPlain < PLAIN_EVERY_MS)) return;
142
+ lastPlain = t;
143
+ const { bar, ...rest } = snapshot();
144
+ stream.write(`${line({ ...rest, plain: true }, { chalk: null })}\n`);
145
+ return;
146
+ }
147
+ if (!force && t - lastDraw < REDRAW_MS) return;
148
+ lastDraw = t;
149
+ shown = true;
150
+ stream.write(`\r\x1b[2K${line(snapshot(), { chalk, width: stream.columns || 0 })}`);
151
+ };
152
+ // Une ligne qui ne bouge pas (attente d'une réponse) avance quand même son temps écoulé
153
+ if (opts.tick !== false) {
154
+ timer = setInterval(() => draw(), opts.json ? JSON_EVERY_MS : tty ? 1000 : PLAIN_EVERY_MS);
155
+ if (timer.unref) timer.unref();
156
+ }
157
+ const clear = () => {
158
+ if (shown && tty) stream.write('\r\x1b[2K');
159
+ };
160
+ return {
161
+ update(done, extra = {}) {
162
+ if (Number.isFinite(done)) st.done = done;
163
+ Object.assign(st, extra);
164
+ m.add(now(), st.done);
165
+ draw();
166
+ },
167
+ set(extra = {}) {
168
+ Object.assign(st, extra);
169
+ draw();
170
+ },
171
+ /** Une ligne au-dessus de la barre (la barre est redessinée ensuite) */
172
+ log(text) {
173
+ clear();
174
+ console.log(text);
175
+ if (shown) draw(true);
176
+ },
177
+ end() {
178
+ if (ended) return snapshot();
179
+ const s = snapshot();
180
+ if (timer) clearInterval(timer);
181
+ clear();
182
+ ended = true;
183
+ return s;
184
+ },
185
+ stats: snapshot,
186
+ get shown() {
187
+ return shown;
188
+ },
189
+ };
190
+ }
191
+
192
+ /** Rien à montrer (tests, sorties non suivies) : même interface */
193
+ const none = () => ({ update() {}, set() {}, log: (t) => console.log(t), end: () => ({}), stats: () => ({}), shown: false });
194
+
195
+ /** Débit moyen en octets par seconde (journaux). Pure. */
196
+ const rateOf = (bytes, ms) => (bytes > 0 && ms > 0 ? Math.round((bytes * 1000) / ms) : 0);
197
+
198
+ module.exports = { start, none, line, barOf, duration, size, meter, rateOf, SHOW_AFTER_MS, REDRAW_MS };