poad 2.77.0 → 2.78.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.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # poad
2
+
3
+ The command line of poad: a backend (Postgres, auth, storage, functions, flows, references) that runs on your machine, and on poad.io.
4
+
5
+ ```sh
6
+ npm i -g poad
7
+ poad doctor # is this machine ready?
8
+ poad init # a poad/ folder in the current project
9
+ poad start
10
+ ```
11
+
12
+ ## Prerequisites
13
+
14
+ | | Needed | Notes |
15
+ |---|---|---|
16
+ | **Node.js** | 20 or later | `node --version` |
17
+ | **Docker** | 20.10 or later, started | macOS: Docker Desktop. Linux: Docker Engine is enough (no Docker Desktop); your user in the `docker` group. Windows (beta): Docker Desktop with WSL2. |
18
+ | **git** | any recent version | On a new Mac, the first `git` call offers to install Apple's command line tools: `xcode-select --install`. |
19
+
20
+ **psql is not needed**: the engine brings its own Postgres tools.
21
+
22
+ Platforms: **macOS and Linux** first; **Windows in beta** (it works with Docker Desktop and WSL2; tell us what breaks).
23
+
24
+ ### `poad doctor`
25
+
26
+ Checks all of that, one line per check (✔ fine, ⚠ warning, ✕ blocking), each problem with what to do and a link:
27
+
28
+ - system, Node.js version;
29
+ - Docker: installed, **started** (the most common case: installed but not started), daemon version, architecture, free room of its storage, memory of its VM (macOS, Windows); on Linux, access to the Docker socket, systemd, `host-gateway` (Docker 20.10+), free room on the disk of `/var/lib/docker`; on Windows, WSL2;
30
+ - git;
31
+ - network: Docker Hub, the permalink (`raw.githubusercontent.com`), poad.io (short timeouts);
32
+ - in a project folder: `poad/config.toml` readable, engine image present, ports free, poad.io link and session (the token is never shown);
33
+ - the CLI version, and whether a newer one is out.
34
+
35
+ `poad doctor --json` for a script, `--offline` to skip the network. Exit code 1 when something blocks; warnings never block. `poad init`, `poad start` and `poad link` run the blocking checks first (in less than a second) and stop with the same clear message.
36
+
37
+ ## Local and poad.io
38
+
39
+ ```sh
40
+ poad login
41
+ poad link <project id>
42
+ poad deploy # code: migrations, functions, flows…
43
+ poad push --env main # the whole project: code, base, accounts, references, files (s3), --with-secrets
44
+ poad pull --env main # the other way
45
+ ```
46
+
47
+ `poad push` makes the environment the mirror of the local project, part by part, and only sends what differs: identical tables, files already there, references already loaded and code already deployed are skipped, so a push run twice in a row has nothing to do the second time, and an interrupted push resumes where it was. Every transfer longer than 2 seconds shows its progress (bytes, rows or files, rate, time left) on a terminal; plain spaced lines when the output goes to a file; JSON events with `--json`. A transfer that makes no progress for 5 minutes (`POAD_STALL_TIMEOUT`, seconds) stops with a clear message; a slow one that moves is never cut.
48
+
49
+ `poad <command> --help` gives the details of each command; `poad --help` all of them.
package/global/cli.js CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  module.exports = {
10
10
  install: 'Install poad environment: pull the latest engine image',
11
+ doctor: 'Check this machine for poad: Node.js, Docker (installed, started, disk, memory), git, network, the project and its poad.io link; what to do for each problem',
11
12
  init: 'Init a poad project in this folder: poad/ (config, secrets, migrations)',
12
13
  create: 'Create a poad project: poad/ (backend), apps/<app> (first front-end), workspace, first git commit. Inside a project: add a front-end on its own port. Templates angular, next, nuxt, vanilla from npm, integrity checked',
13
14
  start: 'Start the project: engine, migrations, services chosen with poad setup, then its state (secrets hidden)',
@@ -0,0 +1,41 @@
1
+ // poad doctor [--json] [--offline] : ce poste peut-il faire tourner poad ? (utils/doctor.js)
2
+ // Code de sortie 1 s'il y a un ✕ bloquant ; les avertissements ne bloquent pas.
3
+ // Journal : une ligne (event=doctor) dans le puits du projet s'il tourne ; des noms d'état, jamais un secret.
4
+ module.exports = async (args, raw = []) => {
5
+ const chalk = require('chalk-v2');
6
+ const doctor = require('../utils/doctor');
7
+ const words = (raw || []).map(String);
8
+ const json = words.includes('--json');
9
+ const network = !words.includes('--offline');
10
+ const unknown = words.filter((w) => w.startsWith('-') && !['--json', '--offline'].includes(w));
11
+ if (unknown.length) {
12
+ console.error(chalk.redBright(`poad doctor: unknown option ${unknown[0]}`));
13
+ process.exitCode = 2;
14
+ return;
15
+ }
16
+ const root = require('../utils/findpoad').findPoadDir(process.cwd());
17
+ const t0 = Date.now();
18
+ const r = await doctor.run(doctor.realSys(), { root, network });
19
+ const view = r.checks.map(({ id, status, label, detail, fix, link }) => ({ id, status, label, detail, ...(fix ? { fix } : {}), ...(link ? { link } : {}) }));
20
+ if (json) console.log(JSON.stringify({ ok: r.ok, platform: process.platform, checks: view, duration_ms: Date.now() - t0 }, null, 2));
21
+ else {
22
+ for (const c of r.checks) for (const l of doctor.lines(c, chalk)) console.log(` ${l}`);
23
+ const fails = r.checks.filter((c) => c.status === 'fail').length;
24
+ const warns = r.checks.filter((c) => c.status === 'warn').length;
25
+ console.log(' ');
26
+ console.log(fails ? chalk.redBright(` ${fails} problem(s) to fix before poad can run${warns ? `, ${warns} warning(s)` : ''}.`) : `${chalk.greenBright('✔')} Ready${warns ? chalk.grey(`: ${warns} warning(s), nothing blocking`) : ''}.`);
27
+ }
28
+ // Puits de logs du projet, s'il tourne (doctor n'en a pas besoin sinon)
29
+ if (r.project && r.project.running && r.project.config) {
30
+ let client;
31
+ try {
32
+ client = await require('../utils/migrations').connect(r.project.config);
33
+ const attrs = { event: 'doctor', ok: r.ok, platform: process.platform, failed: r.checks.filter((c) => c.status === 'fail').map((c) => c.id), warnings: r.checks.filter((c) => c.status === 'warn').map((c) => c.id), duration_ms: Date.now() - t0 };
34
+ await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", [r.ok ? 'info' : 'warn', `doctor: ${r.ok ? 'ready' : 'problems'} (${attrs.failed.length} blocking, ${attrs.warnings.length} warning(s))`, JSON.stringify(attrs)]);
35
+ } catch {
36
+ } finally {
37
+ if (client) await client.end().catch(() => {});
38
+ }
39
+ }
40
+ if (!r.ok) process.exitCode = 1;
41
+ };
package/global/init.js CHANGED
@@ -21,6 +21,10 @@ module.exports = async (args = {}, raw, options = {}) => {
21
21
  const { generateSecrets, writeSecrets, ensureGitignore } = require('../utils/config');
22
22
  const migrations = require('../utils/migrations');
23
23
 
24
+ // Appel direct (pas par poad create) : Node, Docker démarré, git, avant d'écrire quoi que ce soit
25
+ if (!options || !Object.keys(options).length) {
26
+ if (!(await require('../utils/doctor').guard('init'))) return { initialized: false };
27
+ }
24
28
  const dir = path.join(process.cwd(), 'poad');
25
29
  const root = path.join(dir, 'config.toml');
26
30
  if (fs.existsSync(root)) {
package/global/start.js CHANGED
@@ -10,6 +10,8 @@ const ensureDir = (dir) => {
10
10
  };
11
11
 
12
12
  module.exports = async (args = {}) => {
13
+ // Node, Docker démarré, git : un message clair plutôt qu'une erreur de connexion à Docker
14
+ if (!(await require('../utils/doctor').guard('start'))) return;
13
15
  const chalk = require('chalk-v2');
14
16
  const Docker = require('dockerode');
15
17
  const docker = new Docker();
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.77.0",
3
+ "version": "2.78.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
7
+ "engines": {
8
+ "node": ">=20.0.0"
9
+ },
7
10
  "license": "MIT",
8
11
  "bin": {
9
12
  "poad": "poad.js"
package/project/deploy.js CHANGED
@@ -154,6 +154,8 @@ module.exports = (args, raw) =>
154
154
  if (err instanceof bundle.BundleError) throw new api.CloudError(`Nothing sent: ${err.message}`, { code: 'bundle' });
155
155
  throw err;
156
156
  }
157
+ // Archive reproductible : son empreinte dit si le code a changé depuis le dernier déploiement d'ici
158
+ const archiveSha = require('crypto').createHash('sha256').update(b.tgz).digest('hex');
157
159
  const git = gitState(poadDir);
158
160
  const sha = git.repo && !git.dirty ? git.sha : null;
159
161
  const kb = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);
@@ -190,7 +192,14 @@ module.exports = (args, raw) =>
190
192
  if (sha) headers['x-poad-sha'] = sha;
191
193
  if (dryRun) headers['x-poad-dry-run'] = '1';
192
194
  if (allowLoss) headers['x-poad-allow-destructive'] = '1';
193
- let r = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
195
+ // Envoi de l'archive suivi (barre au-delà de 2 s, terminal seulement) ; délai d'inactivité pendant l'envoi
196
+ const bar = require('../utils/progress').start({ label: 'deploy', phase: 'sending the archive', total: b.tgz.length, json: out.json, part: 'code' });
197
+ let r;
198
+ try {
199
+ r = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000, onUpload: (sent, total) => bar.update(sent, sent >= total ? { phase: 'waiting for poad.io' } : {}) }));
200
+ } finally {
201
+ bar.end();
202
+ }
194
203
  // Déploiement asynchrone : suivi jusqu'à son terme
195
204
  if (r.deploy_id && r.status && !DONE.includes(r.status)) {
196
205
  const started = Date.now();
@@ -274,6 +283,8 @@ module.exports = (args, raw) =>
274
283
  if (references && references.failed) result.failed = true;
275
284
  }
276
285
 
286
+ // Dernier déploiement réussi d'ici : poad push ne redéploie pas une archive identique (utils/cloud/deploy-memo)
287
+ if (!dryRun && !lossRefused && !result.failed && result.deploy_id) require('../utils/cloud/deploy-memo').record(poadDir, id, env.branch, { deploy_id: result.deploy_id, archive_sha256: archiveSha });
277
288
  out.log(' ');
278
289
  if (lossRefused) out.log(chalk.redBright(' Deploy refused: pending migrations lose data on production.'));
279
290
  else if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
@@ -290,6 +301,7 @@ module.exports = (args, raw) =>
290
301
  dirty: git.dirty,
291
302
  files: b.files.length,
292
303
  bytes: b.tgz.length,
304
+ archive_sha256: archiveSha,
293
305
  skipped: b.skipped,
294
306
  ...result,
295
307
  dry_run: dryRun,
package/project/link.js CHANGED
@@ -8,6 +8,8 @@ module.exports = (args, raw) =>
8
8
  const cli = require('../utils/cloud/cli');
9
9
  const { view } = require('../global/cloud/index');
10
10
  const { chalk } = out;
11
+ // Node et git (lier n'a pas besoin de Docker : le projet peut être arrêté)
12
+ if (!(await require('../utils/doctor').guard('link', { docker: false }))) return 1;
11
13
  const root = cli.projectRoot();
12
14
  if (!root) throw api.usageError('Not in a poad project folder: cd into one (poad init creates one).');
13
15
  if (positionals.length > 1) throw api.usageError('Usage: poad link [<id>]');
@@ -23,21 +23,14 @@ module.exports = (args, raw) =>
23
23
  try {
24
24
  // 1. Conversion
25
25
  const t0 = Date.now();
26
- let last = 0;
27
- const conv = await S.convertFile(file, {
28
- format: opts.format,
29
- table: opts.table,
30
- fields: opts.fields,
31
- exclude: opts.exclude,
32
- dir,
33
- onProgress: (read, total) => {
34
- if (!out.json && process.stderr.isTTY && Date.now() - last > 250) {
35
- last = Date.now();
36
- process.stderr.write(`\r ${chalk.grey('reading')} ${path.basename(file)} ${Math.floor((read / total) * 100)}% `);
37
- }
38
- },
39
- });
40
- if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
26
+ const P = require('../../utils/progress');
27
+ const reading = P.start({ label: path.basename(file), phase: 'reading', total: fs.statSync(file).size, json: out.json, part: 'refs' });
28
+ let conv;
29
+ try {
30
+ conv = await S.convertFile(file, { format: opts.format, table: opts.table, fields: opts.fields, exclude: opts.exclude, dir, onProgress: (read) => reading.update(read) });
31
+ } finally {
32
+ reading.end();
33
+ }
41
34
  if (!conv.tables.length) throw new api.CloudError(`${path.basename(file)}: no data found (INSERT … VALUES, COPY … FROM stdin, CSV rows or JSON lines)`, { code: 'seed_empty' });
42
35
  out.log(`${chalk.greenBright('✔')} ${path.basename(file)} read in ${((Date.now() - t0) / 1000).toFixed(1)} s: ${conv.tables.map((t) => `${t.target} (${t.rows} rows, ≈ ${S.fmt(t.stats.db_bytes)} in the database)`).join(', ')}`);
43
36
  for (const t of conv.tables) {
@@ -50,18 +43,13 @@ module.exports = (args, raw) =>
50
43
  // 2. Envoi, table par table
51
44
  const results = [];
52
45
  for (const t of conv.tables) {
53
- let shown = 0;
54
- const r = await S.pushTable(id, t, {
55
- mode,
56
- source: path.basename(file),
57
- onProgress: (done, total) => {
58
- if (!out.json && process.stderr.isTTY && Date.now() - shown > 250) {
59
- shown = Date.now();
60
- process.stderr.write(`\r ${chalk.grey('sending')} ${t.target} ${S.fmt(done)} / ${S.fmt(total)} `);
61
- }
62
- },
63
- });
64
- if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
46
+ const sending = P.start({ label: t.target, phase: 'sending', json: out.json, part: 'refs', table: t.target });
47
+ let r;
48
+ try {
49
+ r = await S.pushTable(id, t, { mode, source: path.basename(file), onProgress: (done, total) => sending.update(done, { total }) });
50
+ } finally {
51
+ sending.end();
52
+ }
65
53
  out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent (${S.fmt(r.stored)} encrypted)` : 'unchanged content: nothing to send'}${r.replaced ? ', replaces the previous version' : ''}`);
66
54
  results.push({ target: t.target, rows: t.rows, sha256: t.sha256, uploaded: r.uploaded, stored_bytes: r.stored, db_bytes: t.stats.db_bytes, mode });
67
55
  }
@@ -104,19 +92,44 @@ async function startAndWait(id, branch, targets, opts, out) {
104
92
  if (plan.mode === 'stepwise') out.log(chalk.grey(` Loading into ${branch} table by table (${plan.order.length} tables, not enough room for all at once): ${plan.order.join(', ')}…`));
105
93
  else out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
106
94
  const done = new Set();
95
+ // poad.io ne dit pas les lignes en cours de chargement : la table en cours, son rang, le temps écoulé
96
+ const P = require('../../utils/progress');
97
+ let bar = null;
98
+ let current = null;
99
+ const follow = (st) => {
100
+ const running = (st.steps || []).find((s) => !['done', 'failed', 'skipped'].includes(s.status) && !done.has(s.target));
101
+ if (!running && bar) {
102
+ bar.end();
103
+ bar = null;
104
+ current = null;
105
+ }
106
+ if (running && running.target !== current) {
107
+ if (bar) bar.end();
108
+ current = running.target;
109
+ const i = (st.steps || []).indexOf(running);
110
+ bar = P.start({ label: running.target, phase: `loading into ${branch} (table ${i + 1} of ${st.steps.length})`, json: out.json, part: 'refs', table: running.target, total: 0 });
111
+ }
112
+ };
107
113
  const l = await S.waitLoad(id, started.load_id, {
108
114
  onStep: (st) => {
115
+ // Lignes « chargée » au-dessus de la barre : elle s'efface d'abord
116
+ if (bar && (st.steps || []).some((s) => s.target === current && ['done', 'failed', 'skipped'].includes(s.status))) {
117
+ bar.end();
118
+ bar = null;
119
+ current = null;
120
+ }
109
121
  for (const s of st.steps) {
110
122
  if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
111
123
  done.add(s.target);
112
124
  if (s.status === 'done') {
113
- out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
125
+ out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${Number(s.written || 0).toLocaleString('en-US')} rows written, ${Number(s.deleted || 0).toLocaleString('en-US')} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
114
126
  for (const w of s.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
115
127
  }
116
128
  else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
117
129
  }
130
+ follow(st);
118
131
  },
119
- });
132
+ }).finally(() => bar && bar.end());
120
133
  // Tables pas chargées (une précédente refusée ou en échec) : le prochain poad deploy les reprend
121
134
  for (const s of l.steps || []) if (s.status === 'skipped' || s.status === 'pending') out.log(`${chalk.yellow('○')} ${s.target}: pending, not loaded into ${branch}; the next "poad deploy" loads it`);
122
135
  if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
@@ -0,0 +1,159 @@
1
+ // poad doctor (CLI 2.78.0) : contrôles simulés (sys) — Docker absent, arrêté, socket refusé, Node trop vieux,
2
+ // git absent, Mac neuf sans outils de ligne de commande, Linux, Windows en bêta, réseau coupé.
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const D = require('../utils/doctor');
6
+
7
+ const INFO = { ServerVersion: '27.3.1', Architecture: 'aarch64', OperatingSystem: 'Docker Desktop', OSType: 'linux', MemTotal: 8 * 1024 ** 3, DockerRootDir: '/var/lib/docker', KernelVersion: '6.10.14-linuxkit' };
8
+
9
+ /** Faux poste : réponses des commandes par « cmd arg0 », le reste par défaut sain */
10
+ function fakeSys(o = {}) {
11
+ const cmds = {
12
+ 'docker --version': { code: 0, stdout: 'Docker version 27.3.1, build ce12230\n', stderr: '' },
13
+ 'docker info': { code: 0, stdout: JSON.stringify(o.info || INFO), stderr: '' },
14
+ 'git --version': { code: 0, stdout: 'git version 2.47.0\n', stderr: '' },
15
+ 'xcode-select -p': { code: 0, stdout: '/Library/Developer/CommandLineTools\n', stderr: '' },
16
+ 'systemctl is-enabled': { code: 0, stdout: 'enabled\n', stderr: '' },
17
+ 'docker ps': { code: 0, stdout: '', stderr: '' },
18
+ 'docker image': { code: 0, stdout: 'sha256:x', stderr: '' },
19
+ ...(o.cmds || {}),
20
+ };
21
+ return {
22
+ platform: o.platform || 'darwin',
23
+ arch: 'arm64',
24
+ node: o.node || '22.11.0',
25
+ env: { USER: 'alice', ...(o.env || {}) },
26
+ home: '/Users/alice',
27
+ exec: async (cmd, args) => cmds[`${cmd} ${args[0]}`] || cmds[cmd] || { code: -1, stdout: '', stderr: 'ENOENT' },
28
+ reach: async (url) => (o.offline ? { ok: false, error: 'ENOTFOUND', ms: 3 } : { ok: true, status: 200, ms: 12 }),
29
+ json: async () => ({ version: o.latest || require('../package.json').version }),
30
+ statfs: () => ({ free: o.free !== undefined ? o.free : 80 * 1024 ** 3, size: 500 * 1024 ** 3 }),
31
+ readFile: () => o.config || 'project_id = "demo"\nproject_uuid = "u1"\nengine = "0.79.0"\n[db]\nport = 1\n',
32
+ portFree: async () => true,
33
+ cloudCall: async () => ({}),
34
+ };
35
+ }
36
+ const by = (r, id) => r.checks.find((c) => c.id === id);
37
+
38
+ test('doctor: a healthy Mac — every check ✔, ready', async () => {
39
+ const r = await D.run(fakeSys());
40
+ assert.strictEqual(r.ok, true, JSON.stringify(r.checks.filter((c) => c.status !== 'ok')));
41
+ assert.deepStrictEqual(r.checks.filter((c) => c.status !== 'ok'), []);
42
+ assert.match(by(r, 'docker_running').detail, /Docker Desktop 27\.3\.1, aarch64/);
43
+ assert.match(by(r, 'docker_memory').detail, /8\.0 GB/);
44
+ });
45
+
46
+ test('doctor: Docker not installed — blocking, with how to install it per system', async () => {
47
+ for (const platform of ['darwin', 'linux']) {
48
+ const r = await D.run(fakeSys({ platform, cmds: { 'docker --version': { code: -1, stdout: '', stderr: 'ENOENT' } } }));
49
+ assert.strictEqual(r.ok, false);
50
+ const c = by(r, 'docker');
51
+ assert.strictEqual(c.status, 'fail');
52
+ assert.match(c.detail, /not installed/);
53
+ assert.match(c.fix, platform === 'linux' ? /Docker Engine \(Docker Desktop is not needed\)/ : /Docker Desktop/);
54
+ assert.ok(c.link.startsWith('https://docs.docker.com/'));
55
+ }
56
+ });
57
+
58
+ test('doctor: Docker installed but not started — the most common case, said as such', async () => {
59
+ const stopped = { code: 1, stdout: '', stderr: 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?' };
60
+ const mac = await D.run(fakeSys({ cmds: { 'docker info': stopped } }));
61
+ const c = by(mac, 'docker_running');
62
+ assert.strictEqual(c.status, 'fail');
63
+ assert.match(c.detail, /installed \(27\.3\.1\) but not started/);
64
+ assert.match(c.fix, /open -a Docker/);
65
+ const linux = await D.run(fakeSys({ platform: 'linux', cmds: { 'docker info': stopped } }));
66
+ assert.match(by(linux, 'docker_running').fix, /sudo systemctl start docker/);
67
+ // Docker récent : docker info rend 0 et met l'erreur dans ServerErrors
68
+ const recent = await D.run(fakeSys({ cmds: { 'docker info': { code: 0, stdout: JSON.stringify({ ServerErrors: ['Cannot connect to the Docker daemon'] }), stderr: '' } } }));
69
+ assert.match(by(recent, 'docker_running').detail, /not started/);
70
+ });
71
+
72
+ test('doctor (Linux): socket refused → the docker group command; old Docker → host-gateway; disk of /var/lib/docker', async () => {
73
+ const denied = await D.run(fakeSys({ platform: 'linux', cmds: { 'docker info': { code: 1, stdout: '', stderr: 'permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock' } } }));
74
+ const c = by(denied, 'docker_running');
75
+ assert.strictEqual(c.status, 'fail');
76
+ assert.match(c.detail, /refuses this user \(alice\)/);
77
+ assert.match(c.fix, /sudo usermod -aG docker \$USER/);
78
+ const engine = { ...INFO, OperatingSystem: 'Ubuntu 24.04.1 LTS', ServerVersion: '20.10.2', MemTotal: 2 * 1024 ** 3 };
79
+ const ok = await D.run(fakeSys({ platform: 'linux', info: engine, free: 4 * 1024 ** 3 }));
80
+ assert.match(by(ok, 'docker_running').detail, /Docker Engine 20\.10\.2/);
81
+ assert.strictEqual(by(ok, 'docker_version'), undefined, '20.10 is enough');
82
+ assert.strictEqual(by(ok, 'docker_memory'), undefined, 'no VM on Linux');
83
+ assert.match(by(ok, 'docker_disk').detail, /4\.0 GB free on the disk of \/var\/lib\/docker/);
84
+ assert.strictEqual(by(ok, 'docker_disk').status, 'warn');
85
+ const old = await D.run(fakeSys({ platform: 'linux', info: { ...engine, ServerVersion: '19.03.13' } }));
86
+ assert.strictEqual(by(old, 'docker_version').status, 'fail');
87
+ assert.match(by(old, 'docker_version').detail, /host-gateway/);
88
+ const noBoot = await D.run(fakeSys({ platform: 'linux', info: engine, cmds: { 'systemctl is-enabled': { code: 1, stdout: 'disabled\n', stderr: '' } } }));
89
+ assert.match(by(noBoot, 'docker_boot').fix, /sudo systemctl enable docker/);
90
+ });
91
+
92
+ test('doctor: Node too old → blocking; git missing → blocking; new Mac without the command line tools → warned', async () => {
93
+ const node = await D.run(fakeSys({ node: '18.19.0' }));
94
+ assert.strictEqual(node.ok, false);
95
+ assert.match(by(node, 'node').detail, /18\.19\.0: too old, 20\.0\.0 or later needed/);
96
+ const nogit = await D.run(fakeSys({ platform: 'linux', info: { ...INFO, OperatingSystem: 'Debian' }, cmds: { 'git --version': { code: -1, stdout: '', stderr: '' } } }));
97
+ assert.strictEqual(by(nogit, 'git').status, 'fail');
98
+ assert.match(by(nogit, 'git').fix, /apt install git/);
99
+ const fresh = await D.run(fakeSys({ cmds: { 'xcode-select -p': { code: 2, stdout: '', stderr: 'unable to get active developer directory' } } }));
100
+ assert.strictEqual(by(fresh, 'git').status, 'warn');
101
+ assert.match(by(fresh, 'git').detail, /opens a window to install them/);
102
+ assert.match(by(fresh, 'git').fix, /xcode-select --install/);
103
+ assert.strictEqual(fresh.ok, true, 'a warning does not block');
104
+ });
105
+
106
+ test('doctor (Windows, beta): said clearly, never blocking; WSL2 checked; little VM memory warned', async () => {
107
+ const r = await D.run(fakeSys({ platform: 'win32', info: { ...INFO, KernelVersion: '5.15.153.1-microsoft-standard-WSL2', MemTotal: 2 * 1024 ** 3 } }));
108
+ assert.strictEqual(r.ok, true);
109
+ assert.strictEqual(by(r, 'system').status, 'warn');
110
+ assert.match(by(r, 'system').detail, /Windows \(arm64\): supported in beta/);
111
+ assert.strictEqual(by(r, 'docker_wsl').status, 'ok');
112
+ assert.strictEqual(by(r, 'docker_memory').status, 'warn');
113
+ const hyperv = await D.run(fakeSys({ platform: 'win32', info: { ...INFO, KernelVersion: '5.10.16' } }));
114
+ assert.strictEqual(by(hyperv, 'docker_wsl').status, 'warn');
115
+ });
116
+
117
+ test('doctor: network cut → warnings only; newer CLI → warning with the npm command', async () => {
118
+ const r = await D.run(fakeSys({ offline: true, latest: '99.0.0' }));
119
+ assert.strictEqual(r.ok, true);
120
+ for (const id of ['net_dockerhub', 'net_permalink', 'net_poadio']) assert.strictEqual(by(r, id).status, 'warn');
121
+ assert.match(by(r, 'net_permalink').detail, /raw\.githubusercontent\.com not reachable/);
122
+ assert.match(by(r, 'cli').fix, /npm i -g poad@99\.0\.0/);
123
+ });
124
+
125
+ test('doctor in a project: unreadable config.toml blocks; link checked without ever showing the token', async () => {
126
+ const bad = await D.run(fakeSys({ config: 'engine = "0.79.0\n' }), { root: '/p/poad/config.toml' });
127
+ assert.strictEqual(by(bad, 'project_config').status, 'fail');
128
+ const token = 'poad_pat_SECRET_never_shown';
129
+ const sys = fakeSys({ env: { POAD_ACCESS_TOKEN: token }, config: 'project_id = "demo"\nproject_uuid = "u1"\nengine = "0.79.0"\n[db]\nport = 54321\n[cloud]\nproject = "abcdefghijkl"\n' });
130
+ sys.portFree = async (p) => p !== 54321;
131
+ const r = await D.run(sys, { root: '/p/poad/config.toml' });
132
+ assert.match(by(r, 'project_link').detail, /abcdefghijkl, session valid \(POAD_ACCESS_TOKEN\)/);
133
+ assert.match(by(r, 'project_ports').detail, /54321 \(db\)/);
134
+ assert.ok(!JSON.stringify(r).includes(token));
135
+ sys.cloudCall = async () => {
136
+ throw Object.assign(new Error('refused'), { status: 401 });
137
+ };
138
+ const expired = await D.run(sys, { root: '/p/poad/config.toml' });
139
+ assert.match(by(expired, 'project_link').detail, /session expired or revoked/);
140
+ assert.strictEqual(by(expired, 'project_link').fix, 'poad login');
141
+ });
142
+
143
+ test('preflight (poad init, start, link): only Node, Docker started, git; a stopped Docker stops it', async () => {
144
+ const fine = await D.preflight(fakeSys());
145
+ assert.strictEqual(fine.ok, true);
146
+ assert.deepStrictEqual(fine.checks.map((c) => c.id), ['node', 'docker_running', 'git']);
147
+ const stopped = await D.preflight(fakeSys({ cmds: { 'docker info': { code: 1, stdout: '', stderr: 'Cannot connect to the Docker daemon' } } }));
148
+ assert.deepStrictEqual(stopped.failed.map((c) => c.id), ['docker_running']);
149
+ const noDocker = await D.preflight(fakeSys({ cmds: { 'docker --version': { code: -1 } } }), { docker: false });
150
+ assert.strictEqual(noDocker.ok, true, 'poad link does not need Docker');
151
+ });
152
+
153
+ test('atLeast: versions compared number by number', () => {
154
+ assert.ok(D.atLeast('20.10.2', '20.10.0'));
155
+ assert.ok(!D.atLeast('19.03.13', '20.10.0'));
156
+ assert.ok(D.atLeast('v22.1.0', '20.0.0'));
157
+ assert.ok(!D.atLeast('2.77.0', '2.78.0'));
158
+ assert.ok(D.atLeast('27.3.1-rd', '20.10.0'));
159
+ });