@animastor/installer 0.1.0 → 0.2.4

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.
@@ -145,6 +145,149 @@ function probeNodejs(io) {
145
145
  return v ? { version: v } : null;
146
146
  }
147
147
 
148
+ function nodeMajor(version) {
149
+ const m = /^v?(\d+)/.exec(String(version || ''));
150
+ return m ? Number(m[1]) : 0;
151
+ }
152
+
153
+ /**
154
+ * The Node.js binary the worker must run with: the one running this
155
+ * installer when it is >= 20 (the bootstrap verified or provisioned it),
156
+ * otherwise the first `node`/`node22`/`node20` on PATH that is >= 20.
157
+ * Written to .env as NODE_BIN so start-worker.sh, the `animastor` tool and
158
+ * the installer start the SAME binary (no silent fallback to an old system
159
+ * Node 18).
160
+ * @returns {{ bin: string, version: string } | null}
161
+ */
162
+ function pickNodeBinary(io, { execPath = process.execPath, execVersion = process.versions.node } = {}) {
163
+ if (execPath && nodeMajor(execVersion) >= 20) return { bin: execPath, version: execVersion };
164
+ for (const cand of ['node', 'node22', 'node20']) {
165
+ const r = io.exec(cand, ['-p', 'process.execPath + " " + process.versions.node']);
166
+ if (r.code !== 0) continue;
167
+ const [bin, version] = firstLine(r.stdout).split(' ');
168
+ if (bin && nodeMajor(version) >= 20) return { bin, version };
169
+ }
170
+ return null;
171
+ }
172
+
173
+ /** Version of a node binary (e.g. NODE_BIN from .env) or null. */
174
+ function nodeBinaryVersion(io, bin) {
175
+ if (!bin) return null;
176
+ const r = io.exec(bin, ['--version']);
177
+ if (r.code !== 0) return null;
178
+ return firstLine(r.stdout).replace(/^v/, '') || null;
179
+ }
180
+
181
+ /**
182
+ * A ComfyUI process of the current user (python ... main.py): pid, cwd
183
+ * (the ComfyUI root), --port and --baseurl from its command line. Used to
184
+ * find the user's existing ComfyUI when it does not live in ~/ComfyUI and to
185
+ * learn the port/prefix instead of guessing. Linux only (/proc); null
186
+ * elsewhere or when none runs.
187
+ */
188
+ function detectRunningComfyUI(io, { uid = (typeof process.getuid === 'function' ? process.getuid() : null) } = {}) {
189
+ const all = listRunningComfyUI(io, { uid });
190
+ if (all.length === 0) return null;
191
+ const { pid, root, port, baseurl } = all[0];
192
+ return { pid, root, port, baseurl };
193
+ }
194
+
195
+ /**
196
+ * Every ComfyUI process of the account: pid, cwd (the ComfyUI root) and the
197
+ * --listen / --port / --baseurl values from its own command line. Linux only
198
+ * (/proc); [] elsewhere or when none runs. Order = pgrep order (newest
199
+ * processes are not guaranteed first — callers must not rely on it).
200
+ */
201
+ function listRunningComfyUI(io, { uid = (typeof process.getuid === 'function' ? process.getuid() : null) } = {}) {
202
+ if (uid == null) return [];
203
+ let r = null;
204
+ try { r = io.exec('pgrep', ['-u', String(uid), '-f', 'main\\.py']); } catch (_) { r = null; }
205
+ if (!r || r.code !== 0) return [];
206
+ const out = [];
207
+ for (const pidStr of String(r.stdout || '').split(/\s+/).filter(Boolean)) {
208
+ const pid = Number(pidStr);
209
+ if (!Number.isFinite(pid) || pid <= 0) continue;
210
+ let cwd = null;
211
+ let argv = [];
212
+ try { cwd = io.fs.readlinkSync(`/proc/${pid}/cwd`); } catch (_) { cwd = null; }
213
+ try { argv = String(io.fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8')).split('\0').filter(Boolean); } catch (_) { argv = []; }
214
+ if (!argv.some((a) => /(^|\/)main\.py$/.test(a))) continue;
215
+ const flag = (name) => {
216
+ const i = argv.indexOf(name);
217
+ if (i !== -1 && argv[i + 1]) return argv[i + 1];
218
+ const eq = argv.find((a) => a.startsWith(`${name}=`));
219
+ return eq ? eq.slice(name.length + 1) : null;
220
+ };
221
+ const port = flag('--port');
222
+ out.push({
223
+ pid,
224
+ root: cwd && io.fs.existsSync(path.join(cwd, 'main.py')) ? cwd : null,
225
+ // ComfyUI defaults to 8188 when --port is absent
226
+ port: port ? Number(port) : 8188,
227
+ listen: flag('--listen'),
228
+ baseurl: flag('--baseurl'),
229
+ });
230
+ }
231
+ return out;
232
+ }
233
+
234
+ /**
235
+ * Resolve the ComfyUI root: an explicit --root wins; then the default
236
+ * (~/ComfyUI) when it holds a ComfyUI; then the root of the user's running
237
+ * ComfyUI process; finally the default (a managed install creates it).
238
+ * @returns {{ root: string, source: 'flag'|'default'|'running-process' }}
239
+ */
240
+ function resolveComfyRoot(io, { explicit = null, defaultRoot, running = undefined } = {}) {
241
+ if (explicit) return { root: explicit, source: 'flag' };
242
+ if (defaultRoot && io.fs.existsSync(path.join(defaultRoot, 'main.py'))) return { root: defaultRoot, source: 'default' };
243
+ const proc = running === undefined ? detectRunningComfyUI(io) : running;
244
+ if (proc && proc.root) return { root: proc.root, source: 'running-process' };
245
+ return { root: defaultRoot, source: 'default' };
246
+ }
247
+
248
+ /**
249
+ * True for a REAL ComfyUI /system_stats answer (installer 0.2.2): the payload
250
+ * carries a `system` object (ComfyUI always sends `system` + `devices`; the
251
+ * system block alone is its signature). A wrong reverse-proxy prefix answers
252
+ * 404/HTML, another service answers its own JSON — a bare 200 JSON object is
253
+ * NOT proof (a notebook proxy or a coworker's app would otherwise be
254
+ * accepted as "our" ComfyUI and wired into COMFY_URL).
255
+ */
256
+ function isSystemStats(json) {
257
+ return !!(json && typeof json === 'object' && !Array.isArray(json)
258
+ && json.system && typeof json.system === 'object' && !Array.isArray(json.system));
259
+ }
260
+
261
+ /**
262
+ * Probe the ComfyUI API base the worker must use (COMFY_URL). The plain
263
+ * http://127.0.0.1:<port> is tried FIRST; a reverse-proxy prefix (notebook
264
+ * deployments) only when the plain URL does not answer. Never guessed: the
265
+ * returned URL answered GET /system_stats with a ComfyUI payload.
266
+ * @param {object} opts { port, prefixes: string[] (e.g. NOTEBOOK_PATH, --baseurl), timeoutMs }
267
+ * @returns {Promise<{ url: string, prefixed: boolean, tried: string[] } | { url: null, tried: string[] }>}
268
+ */
269
+ async function probeComfyUrl(io, { port, prefixes = [], timeoutMs = 3000 } = {}) {
270
+ const base = `http://127.0.0.1:${port}`;
271
+ const candidates = [base];
272
+ for (const p of prefixes) {
273
+ if (!p) continue;
274
+ const norm = `/${String(p).replace(/^\/+|\/+$/g, '')}`;
275
+ if (norm === '/') continue;
276
+ const url = `${base}${norm}`;
277
+ if (!candidates.includes(url)) candidates.push(url);
278
+ }
279
+ for (const url of candidates) {
280
+ try {
281
+ const opts = typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? { signal: AbortSignal.timeout(timeoutMs) } : {};
282
+ const res = await io.http.fetchJson(`${url}/system_stats`, opts);
283
+ if (res && res.status === 200 && isSystemStats(res.json)) {
284
+ return { url, prefixed: url !== base, tried: candidates };
285
+ }
286
+ } catch (_) { /* next candidate */ }
287
+ }
288
+ return { url: null, tried: candidates };
289
+ }
290
+
148
291
  function probeCustomNodes(io, root) {
149
292
  const dir = path.join(root, 'custom_nodes');
150
293
  if (!io.fs.isDirectory(dir)) return [];
@@ -162,23 +305,118 @@ function probeCustomNodes(io, root) {
162
305
  return out;
163
306
  }
164
307
 
165
- function walkModels(io, root, relDir, out, depth = 0) {
166
- const abs = path.join(root, relDir);
167
- if (!io.fs.isDirectory(abs)) return;
168
- for (const name of io.fs.readdirSync(abs)) {
308
+ /**
309
+ * Walk one model folder. `relDir` is the CANONICAL ComfyUI-relative path the
310
+ * files are reported under (models/<folder>/...), `absDir` where they really
311
+ * live — the same for the default layout, different for a folder declared in
312
+ * extra_model_paths.yaml. `location` (absolute folder base) is attached to
313
+ * files found outside the default layout so the engine downloads missing
314
+ * pieces next to them, never into a second copy.
315
+ */
316
+ function walkModelDir(io, absDir, relDir, out, { depth = 0, location = null } = {}) {
317
+ if (!io.fs.isDirectory(absDir)) return;
318
+ let names = [];
319
+ try { names = io.fs.readdirSync(absDir); } catch (_) { return; }
320
+ for (const name of names) {
169
321
  const rel = `${relDir}/${name}`;
170
- const st = io.fs.statSync(path.join(abs, name));
322
+ let st;
323
+ try { st = io.fs.statSync(path.join(absDir, name)); } catch (_) { continue; }
171
324
  if (st.isDirectory) {
172
- if (depth < 3) walkModels(io, root, rel, out, depth + 1);
325
+ if (depth < 4) walkModelDir(io, path.join(absDir, name), rel, out, { depth: depth + 1, location });
173
326
  } else if (st.isFile) {
174
- out.push({ path: rel, size_bytes: st.size });
327
+ out.push(location ? { path: rel, size_bytes: st.size, location } : { path: rel, size_bytes: st.size });
328
+ }
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Minimal extra_model_paths.yaml reader (ComfyUI's own format):
334
+ *
335
+ * comfyui:
336
+ * base_path: /data/ComfyUI/
337
+ * checkpoints: models/checkpoints/
338
+ * TTS: models/TTS/
339
+ * loras: |
340
+ * models/loras/
341
+ * more_loras/
342
+ *
343
+ * Returns [{ folder, path }] with absolute paths (relative entries resolve
344
+ * against the section's base_path, else against the ComfyUI root). Unknown
345
+ * syntax is skipped — never guessed.
346
+ */
347
+ function parseExtraModelPaths(text, root) {
348
+ const out = [];
349
+ const sections = [];
350
+ let cur = null;
351
+ let blockKey = null;
352
+ let blockIndent = 0;
353
+ for (const raw of String(text || '').split(/\r?\n/)) {
354
+ const noComment = raw.replace(/\s+#.*$/, '');
355
+ if (!noComment.trim() || noComment.trim().startsWith('#')) continue;
356
+ const indent = noComment.length - noComment.trimStart().length;
357
+ const line = noComment.trim();
358
+ if (blockKey && indent > blockIndent) {
359
+ cur.entries.push({ folder: blockKey, value: line });
360
+ continue;
361
+ }
362
+ blockKey = null;
363
+ if (indent === 0) {
364
+ const m = /^([^:]+):\s*$/.exec(line);
365
+ cur = m ? { name: m[1].trim(), base: null, entries: [] } : null;
366
+ if (cur) sections.push(cur);
367
+ continue;
368
+ }
369
+ if (!cur) continue;
370
+ const kv = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(line);
371
+ if (!kv) continue;
372
+ const key = kv[1];
373
+ const value = kv[2].replace(/^['"]|['"]$/g, '').trim();
374
+ if (key === 'base_path') { cur.base = value; continue; }
375
+ if (key === 'is_default' || key === 'download_model_base') continue;
376
+ if (value === '|' || value === '>' || value === '|-' || value === '') {
377
+ blockKey = key;
378
+ blockIndent = indent;
379
+ continue;
380
+ }
381
+ cur.entries.push({ folder: key, value });
382
+ }
383
+ for (const sec of sections) {
384
+ const base = sec.base ? (path.isAbsolute(sec.base) ? sec.base : path.join(root, sec.base)) : root;
385
+ for (const e of sec.entries) {
386
+ const v = e.value.replace(/^['"]|['"]$/g, '');
387
+ if (!v) continue;
388
+ out.push({ folder: e.folder, path: path.normalize(path.isAbsolute(v) ? v : path.join(base, v)) });
175
389
  }
176
390
  }
391
+ return out;
392
+ }
393
+
394
+ /**
395
+ * Additional model folders: extra_model_paths.yaml next to the ComfyUI root
396
+ * (the file ComfyUI itself reads). Each entry maps a folder name (e.g. TTS,
397
+ * the folder the ComfyUI-Qwen3-TTS loader resolves via
398
+ * folder_paths.get_folder_paths("TTS")) to an absolute directory.
399
+ */
400
+ function extraModelFolders(io, root) {
401
+ const yamlPath = path.join(root, 'extra_model_paths.yaml');
402
+ if (!io.fs.existsSync(yamlPath)) return [];
403
+ try {
404
+ return parseExtraModelPaths(io.fs.readFileSync(yamlPath, 'utf8'), root);
405
+ } catch (_) {
406
+ return [];
407
+ }
177
408
  }
178
409
 
179
410
  function probeModels(io, root) {
180
411
  const out = [];
181
- for (const dir of MODEL_DIRS) walkModels(io, root, dir, out);
412
+ for (const dir of MODEL_DIRS) walkModelDir(io, path.join(root, dir), dir, out);
413
+ const seen = new Set(MODEL_DIRS.map((d) => path.normalize(path.join(root, d))));
414
+ for (const extra of extraModelFolders(io, root)) {
415
+ const abs = extra.path.replace(/[\\/]+$/, '');
416
+ if (seen.has(path.normalize(abs))) continue; // same as the default layout
417
+ seen.add(path.normalize(abs));
418
+ walkModelDir(io, abs, `models/${extra.folder}`, out, { location: abs });
419
+ }
182
420
  return out;
183
421
  }
184
422
 
@@ -265,6 +503,13 @@ function probeEnvironment(io, { root = null, workerDir = null, crypto = null, wo
265
503
  env.cuda = probeCuda(io);
266
504
  env.device = env.gpu && env.gpu.vendor === 'nvidia' ? 'cuda' : 'cpu';
267
505
  env.nodejs = probeNodejs(io);
506
+ // The worker runs with NODE_BIN (the installer's own Node >= 20), not with
507
+ // whatever `node` is first in PATH — judge the runtime by that binary and
508
+ // keep the PATH version for information only.
509
+ if (!env.nodejs || nodeMajor(env.nodejs.version) < 20) {
510
+ const pick = pickNodeBinary(io);
511
+ if (pick) env.nodejs = { version: pick.version, binary: pick.bin, path_version: env.nodejs ? env.nodejs.version : null };
512
+ }
268
513
  env.comfyui = probeComfyui(io, root);
269
514
  env.python = probePython(io, root);
270
515
  env.torch = probeTorch(io, root);
@@ -335,7 +580,19 @@ function renderDetection(env) {
335
580
  }
336
581
 
337
582
  module.exports = {
583
+ detectRunningComfyUI,
584
+ resolveComfyRoot,
338
585
  MODEL_DIRS,
586
+ parseExtraModelPaths,
587
+ probeModels,
588
+ pickNodeBinary,
589
+ nodeBinaryVersion,
590
+ nodeMajor,
591
+ detectRunningComfyUI,
592
+ resolveComfyRoot,
593
+ probeComfyUrl,
594
+ listRunningComfyUI,
595
+ isSystemStats,
339
596
  DEVICE_KINDS,
340
597
  probeEnvironment,
341
598
  probeGpu,
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Installer banner and the final result block.
5
+ *
6
+ * The final block is the ONLY thing a user has to read after a run: either
7
+ * every check is ✓ and "Done — return to the Animastor page", or every ✗ is
8
+ * one line of cause plus one exact fix command. Nothing refers to output
9
+ * "above".
10
+ */
11
+
12
+ const BANNER = [
13
+ ' _ _ _ ___ __ __ _ ____ _____ ___ ____ ',
14
+ ' / \\ | \\ | |_ _| \\/ | / \\ / ___|_ _/ _ \\| _ \\ ',
15
+ ' / _ \\ | \\| || || |\\/| | / _ \\ \\___ \\ | || | | | |_) |',
16
+ ' / ___ \\| |\\ || || | | |/ ___ \\ ___) || || |_| | _ < ',
17
+ '/_/ \\_\\_| \\_|___|_| |_/_/ \\_\\____/ |_| \\___/|_| \\_\\',
18
+ ];
19
+
20
+ /**
21
+ * @param {object} v { installer, worker, profile, profileRevision, hub, bootstrap, platform }
22
+ * @returns {string}
23
+ */
24
+ function renderBanner(v = {}) {
25
+ const val = (x) => (x ? String(x) : 'unknown');
26
+ const profile = v.profile ? `${v.profile}${v.profileRevision ? ` (${v.profileRevision})` : ''}` : '—';
27
+ return [
28
+ ...BANNER,
29
+ '',
30
+ ` GPU worker installer ${val(v.installer)}${v.platform ? ` · ${v.platform}` : ''}`,
31
+ ` worker bundle ${val(v.worker)} · profile ${profile}`,
32
+ ` hub ${val(v.hub)}${v.bootstrap ? ` · bootstrap ${v.bootstrap}` : ''}`,
33
+ '',
34
+ ].join('\n');
35
+ }
36
+
37
+ /**
38
+ * Exact fix for a failed verification check (label from
39
+ * verification-report.js). `tool` is the `animastor` command (or its
40
+ * absolute path when not in PATH).
41
+ */
42
+ function fixForCheck(check, { tool = 'animastor', mode = null } = {}) {
43
+ switch (check.label) {
44
+ case 'GPU':
45
+ return 'install the NVIDIA driver so that `nvidia-smi` works, then run: ' + `${tool} doctor`;
46
+ case 'VRAM':
47
+ return 'use a GPU with more VRAM (see the profile minimum on the Animastor setup page)';
48
+ case 'ComfyUI running':
49
+ case 'ComfyUI API':
50
+ return mode === 'managed' ? `${tool} start` : `start your ComfyUI, then run: ${tool} doctor`;
51
+ case 'Worker registration':
52
+ case 'GPU Hub registration':
53
+ return `create a new Worker Key in Animastor → Settings → Workers, then run: ${tool} doctor --new-key`;
54
+ case 'Worker process':
55
+ return `${tool} start`;
56
+ case 'Runtime':
57
+ return /incompatible|version_mismatch/.test(String(check.detail || ''))
58
+ ? `if ComfyUI already works, this can be ignored; to let the installer replace the torch/python runtime run: ${tool} doctor --accept-runtime-change`
59
+ : `${tool} doctor`;
60
+ default:
61
+ return `${tool} doctor`;
62
+ }
63
+ }
64
+
65
+ /** Verification labels already covered by the end-to-end checks. */
66
+ const COVERED_BY_E2E = new Set(['ComfyUI running', 'ComfyUI API', 'Worker process']);
67
+
68
+ /**
69
+ * Build the final block.
70
+ * @param {object} args
71
+ * @param {object|null} args.verification - buildVerificationReport() result
72
+ * @param {Array} [args.e2e] - engine endToEndChecks() result
73
+ * @param {Array} [args.extra] - additional { ok, label, detail, fix } items (blocked steps, remediation)
74
+ * @returns {{ ok: boolean, text: string, failures: Array }}
75
+ */
76
+ function renderFinalSummary({ verification = null, e2e = [], extra = [], tool = 'animastor', mode = null } = {}) {
77
+ const items = [];
78
+ for (const c of extra || []) items.push(c);
79
+ const e2eIds = new Set((e2e || []).map((c) => c.label));
80
+ for (const c of (verification && verification.checks) || []) {
81
+ if (c.verdict !== false) continue;
82
+ if (COVERED_BY_E2E.has(c.label) && e2e && e2e.length > 0) continue;
83
+ if (e2eIds.has(c.label)) continue;
84
+ items.push({ ok: false, label: c.label, detail: c.detail, fix: fixForCheck(c, { tool, mode }) });
85
+ }
86
+ for (const c of e2e || []) items.push(c);
87
+
88
+ const failures = items.filter((c) => c.ok === false);
89
+ const lines = ['', '==================== RESULT ===================='];
90
+ for (const c of items) {
91
+ const mark = c.ok === true ? '✓' : c.ok === false ? '✗' : '·';
92
+ lines.push(`${mark} ${c.label}${c.detail ? `: ${oneLine(c.detail)}` : ''}`);
93
+ if (c.ok === false && c.fix) lines.push(` fix: ${c.fix}`);
94
+ }
95
+ lines.push('');
96
+ if (failures.length === 0) {
97
+ lines.push('Done — return to the Animastor page: the worker shows ONLINE.');
98
+ } else {
99
+ lines.push(`${failures.length} problem(s) left — run the fix command(s) above; \`${tool} doctor\` re-checks and fixes what it can.`);
100
+ }
101
+ return { ok: failures.length === 0, text: lines.join('\n'), failures };
102
+ }
103
+
104
+ function oneLine(s) {
105
+ return String(s).replace(/\s+/g, ' ').trim();
106
+ }
107
+
108
+ module.exports = { renderBanner, renderFinalSummary, fixForCheck, BANNER };
@@ -0,0 +1,214 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Interactive terminal for the installer prompts.
5
+ *
6
+ * The canonical way to run the installer is `curl -fsSL "<url>" | bash`:
7
+ * there stdin is the script pipe, NOT the keyboard. Every question (including
8
+ * the hidden Worker Key input) is therefore read from the controlling
9
+ * terminal /dev/tty, never from stdin. Without any terminal the installer
10
+ * fails with a clear message instead of silently reading the script as
11
+ * answers.
12
+ *
13
+ * Prompt rules (one question = one prompt, printed once):
14
+ * - no readline: every answer is read by one small raw-mode line editor
15
+ * (readline re-renders multi-line prompts and, with several interfaces
16
+ * on one input, echoes keystrokes twice — the old "double menu");
17
+ * - the question text is written ONCE, the prompt itself is one line;
18
+ * - CR, LF and CRLF end a line; type-ahead is kept for the next question;
19
+ * - hidden input uses the same editor without echo; pasted chunks are
20
+ * processed character by character.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const tty = require('tty');
25
+
26
+ class NoTerminalError extends Error {
27
+ constructor(message) {
28
+ super(message);
29
+ this.name = 'NoTerminalError';
30
+ this.code = 'NO_TTY';
31
+ }
32
+ }
33
+
34
+ const NO_TTY_MESSAGE = [
35
+ 'No interactive terminal: the installer needs one to ask questions and the Worker Key (hidden input).',
36
+ 'Run the install command in an SSH session or a local terminal (curl -fsSL "<url>" | bash reads answers from /dev/tty),',
37
+ 'or add --yes when the Worker Key is already in the worker .env.',
38
+ ].join('\n');
39
+
40
+ /**
41
+ * Open the prompt streams: stdin/stdout when stdin is a TTY, else
42
+ * /dev/tty (piped `curl | bash`). Returns null when no terminal exists.
43
+ * Injectable for tests.
44
+ */
45
+ function openTerminal({ stdin = process.stdin, stdout = process.stdout, fsMod = fs, ttyMod = tty, devTty = '/dev/tty' } = {}) {
46
+ if (stdin && stdin.isTTY) {
47
+ return { input: stdin, output: stdout, owned: false };
48
+ }
49
+ let inFd = null;
50
+ let outFd = null;
51
+ try {
52
+ inFd = fsMod.openSync(devTty, 'r');
53
+ outFd = fsMod.openSync(devTty, 'w');
54
+ const input = new ttyMod.ReadStream(inFd);
55
+ const output = stdout && stdout.isTTY ? stdout : new ttyMod.WriteStream(outFd);
56
+ return { input, output, owned: true, fds: [inFd, outFd] };
57
+ } catch (_) {
58
+ for (const fd of [inFd, outFd]) {
59
+ if (fd !== null) { try { fsMod.closeSync(fd); } catch (__) { /* ignore */ } }
60
+ }
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Line editor state machine for raw-mode input — pure (unit-tested).
67
+ * Feeds characters into `st` until a line is complete; characters after the
68
+ * end of the line stay in `st.rest` (type-ahead for the NEXT question — never
69
+ * lost, never mistaken for this answer). CR, LF and CRLF all end a line; the
70
+ * LF of a CRLF pair is swallowed.
71
+ * Returns the text to echo (nothing for hidden input).
72
+ */
73
+ function feedLine(st, chunk, { hidden = false } = {}) {
74
+ let echo = '';
75
+ const chars = Array.from(String(chunk));
76
+ let i = 0;
77
+ for (; i < chars.length && !st.done; i++) {
78
+ const c = chars[i];
79
+ if (st.skipLf) {
80
+ st.skipLf = false;
81
+ if (c === '\n') continue;
82
+ }
83
+ if (c === '\r' || c === '\n') { st.done = true; st.endedWithCr = c === '\r'; break; }
84
+ if (c === '\u0003') { st.cancelled = true; st.done = true; break; } // Ctrl+C
85
+ if (c === '\u0004') { if (!st.value) st.eof = true; st.done = true; break; } // Ctrl+D
86
+ if (c === '\u007F' || c === '\b') {
87
+ if (st.value.length > 0) {
88
+ st.value = st.value.slice(0, -1);
89
+ if (!hidden) echo += '\b \b';
90
+ }
91
+ continue;
92
+ }
93
+ if (c === '\u001b') { st.inEscape = true; continue; } // arrow keys etc.: ignored
94
+ if (st.inEscape) { if (/[A-Za-z~]/.test(c)) st.inEscape = false; continue; }
95
+ if (c < ' ') continue; // other control chars
96
+ st.value += c;
97
+ if (!hidden) echo += c;
98
+ }
99
+ st.rest = chars.slice(i + 1).join('');
100
+ return echo;
101
+ }
102
+
103
+ /** Backwards-compatible helper for hidden input chunks (pure). */
104
+ function applySecretChunk(state, chunk) {
105
+ feedLine(state, chunk, { hidden: true });
106
+ return { value: state.value, done: state.done, cancelled: !!state.cancelled };
107
+ }
108
+
109
+ /** Parse a Yes/No answer; empty → `def` (null = ask again). */
110
+ function parseYesNo(answer, def = null) {
111
+ const a = String(answer || '').trim();
112
+ if (!a) return def;
113
+ if (/^(y|yes|д|да)$/i.test(a)) return true;
114
+ if (/^(n|no|н|нет)$/i.test(a)) return false;
115
+ return null;
116
+ }
117
+
118
+ /**
119
+ * Create the prompt API on top of a terminal (openTerminal()). With
120
+ * `term === null` every question throws NoTerminalError.
121
+ */
122
+ function createPrompt(term = openTerminal()) {
123
+ let pending = ''; // type-ahead carried over between questions
124
+ let carrySkipLf = false;
125
+ const need = () => {
126
+ if (!term) throw new NoTerminalError(NO_TTY_MESSAGE);
127
+ return term;
128
+ };
129
+ /** Read one line in raw mode (echo unless hidden). null on Ctrl+D. */
130
+ const readLine = (promptText, { hidden = false } = {}) => new Promise((resolve) => {
131
+ const t = need();
132
+ const input = t.input;
133
+ if (!input.isTTY || typeof input.setRawMode !== 'function') {
134
+ throw new NoTerminalError(NO_TTY_MESSAGE);
135
+ }
136
+ t.output.write(promptText);
137
+ const st = { value: '', done: false, skipLf: carrySkipLf, rest: '' };
138
+ const finish = () => {
139
+ input.removeListener('data', onData);
140
+ input.setRawMode(false);
141
+ input.pause();
142
+ pending = st.rest;
143
+ carrySkipLf = !!st.endedWithCr && st.rest === '';
144
+ t.output.write('\n');
145
+ if (st.cancelled) {
146
+ // Ctrl+C keeps its meaning: interrupt the installer (the
147
+ // engine's SIGINT guard saves resumable state).
148
+ process.kill(process.pid, 'SIGINT');
149
+ resolve(null);
150
+ return;
151
+ }
152
+ resolve(st.eof ? null : st.value);
153
+ };
154
+ const onData = (chunk) => {
155
+ const echo = feedLine(st, chunk, { hidden });
156
+ if (echo) t.output.write(echo);
157
+ if (st.done) finish();
158
+ };
159
+ if (pending) {
160
+ const carried = pending;
161
+ pending = '';
162
+ const echo = feedLine(st, carried, { hidden });
163
+ if (echo) t.output.write(echo);
164
+ if (st.done) { finish(); return; }
165
+ }
166
+ input.setRawMode(true);
167
+ input.on('data', onData);
168
+ input.resume();
169
+ });
170
+ return {
171
+ available: !!term,
172
+ /**
173
+ * Yes/No question. `defaultYes`: Enter alone means Yes ([Y/n]).
174
+ * Unrecognized answers re-ask (at most 3 times, then No).
175
+ */
176
+ async confirm(question, { defaultYes = false } = {}) {
177
+ const t = need();
178
+ const lines = String(question).split('\n');
179
+ const last = lines.pop();
180
+ if (lines.length > 0) t.output.write(`${lines.join('\n')}\n`);
181
+ for (let i = 0; i < 3; i++) {
182
+ const answer = await readLine(`${last} ${defaultYes ? '[Y/n]' : '[y/N]'} `);
183
+ if (answer === null) return false; // input closed (Ctrl+D)
184
+ const v = parseYesNo(answer, defaultYes);
185
+ if (v !== null) return v;
186
+ }
187
+ return false;
188
+ },
189
+ /** Numbered menu: printed once, then a single-line "> " prompt. */
190
+ async select(question, options) {
191
+ const t = need();
192
+ t.output.write(`${question}\n${options.map((o, i) => ` [${i + 1}] ${o}`).join('\n')}\n`);
193
+ const answer = await readLine('> ');
194
+ const n = parseInt(answer, 10);
195
+ return options[(n - 1)] || options[0];
196
+ },
197
+ /**
198
+ * Hidden input (raw mode, no echo). The value is never echoed, logged,
199
+ * stored in state or passed via argv.
200
+ */
201
+ async secret(question) {
202
+ const value = await readLine(`${question}: `, { hidden: true });
203
+ return value && value.trim() ? value.trim() : null;
204
+ },
205
+ close() {
206
+ if (term && term.owned) {
207
+ try { term.input.destroy(); } catch (_) { /* ignore */ }
208
+ if (term.output !== process.stdout) { try { term.output.destroy(); } catch (_) { /* ignore */ } }
209
+ }
210
+ },
211
+ };
212
+ }
213
+
214
+ module.exports = { openTerminal, createPrompt, feedLine, applySecretChunk, parseYesNo, NoTerminalError, NO_TTY_MESSAGE };