@trojeancedric/deployer 0.0.0-stage → 0.1.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.
@@ -0,0 +1,4767 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target2, all) => {
8
+ for (var name in all)
9
+ __defProp(target2, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/util/errors.ts
13
+ var DeployerError, CancelledError;
14
+ var init_errors = __esm({
15
+ "src/util/errors.ts"() {
16
+ "use strict";
17
+ DeployerError = class extends Error {
18
+ constructor(message, exitCode = 1) {
19
+ super(message);
20
+ this.exitCode = exitCode;
21
+ this.name = "DeployerError";
22
+ }
23
+ exitCode;
24
+ };
25
+ CancelledError = class extends DeployerError {
26
+ constructor(message = "Cancelled") {
27
+ super(message, 130);
28
+ this.name = "CancelledError";
29
+ }
30
+ };
31
+ }
32
+ });
33
+
34
+ // src/cli/args.ts
35
+ function parseArgs(argv, spec) {
36
+ const positionals = [];
37
+ const flags = {};
38
+ const aliases = new Map(Object.entries(spec).flatMap(([name, s]) => s.alias ? [[s.alias, name]] : []));
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const arg = argv[i];
41
+ if (arg === "--") {
42
+ positionals.push(...argv.slice(i + 1));
43
+ break;
44
+ }
45
+ if (arg.startsWith("--")) {
46
+ let [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
47
+ let negated = false;
48
+ if (!spec[name] && name.startsWith("no-") && spec[name.slice(3)] && !spec[name.slice(3)].value) {
49
+ name = name.slice(3);
50
+ negated = true;
51
+ }
52
+ const s = spec[name];
53
+ if (!s) throw new DeployerError(`Unknown option --${name}`);
54
+ if (s.value) {
55
+ const value = inline ?? argv[++i];
56
+ if (value === void 0 || inline === void 0 && value.startsWith("-")) throw new DeployerError(`--${name} needs a value`);
57
+ flags[name] = value;
58
+ } else {
59
+ if (inline !== void 0) throw new DeployerError(`--${name} does not take a value`);
60
+ flags[name] = !negated;
61
+ }
62
+ continue;
63
+ }
64
+ if (arg.startsWith("-") && arg.length > 1) {
65
+ for (let j = 1; j < arg.length; j++) {
66
+ const name = aliases.get(arg[j]);
67
+ if (!name) throw new DeployerError(`Unknown option -${arg[j]}`);
68
+ if (spec[name].value) {
69
+ const value = arg.slice(j + 1) || argv[++i];
70
+ if (value === void 0) throw new DeployerError(`-${arg[j]} needs a value`);
71
+ flags[name] = value;
72
+ break;
73
+ }
74
+ flags[name] = true;
75
+ }
76
+ continue;
77
+ }
78
+ positionals.push(arg);
79
+ }
80
+ return { positionals, flags };
81
+ }
82
+ function list(value) {
83
+ if (typeof value !== "string") return void 0;
84
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
85
+ }
86
+ var init_args = __esm({
87
+ "src/cli/args.ts"() {
88
+ "use strict";
89
+ init_errors();
90
+ }
91
+ });
92
+
93
+ // src/tui/ansi.ts
94
+ function detectColorDepth() {
95
+ const env = process.env;
96
+ if ("NO_COLOR" in env) return "none";
97
+ if (env.FORCE_COLOR === "0") return "none";
98
+ const colorterm = (env.COLORTERM ?? "").toLowerCase();
99
+ if (colorterm.includes("truecolor") || colorterm.includes("24bit")) return "truecolor";
100
+ const program = env.TERM_PROGRAM ?? "";
101
+ if (["iTerm.app", "WezTerm", "vscode", "ghostty", "WarpTerminal"].includes(program)) return "truecolor";
102
+ return "256";
103
+ }
104
+ function rgbTo256([r, g, b]) {
105
+ if (r === g && g === b) {
106
+ if (r < 8) return 16;
107
+ if (r > 248) return 231;
108
+ return Math.round((r - 8) / 247 * 24) + 232;
109
+ }
110
+ const q = (v) => Math.round(v / 255 * 5);
111
+ return 16 + 36 * q(r) + 6 * q(g) + q(b);
112
+ }
113
+ function fg(color, text) {
114
+ if (colorDepth === "none") return text;
115
+ const code = colorDepth === "truecolor" ? `38;2;${color[0]};${color[1]};${color[2]}` : `38;5;${rgbTo256(color)}`;
116
+ return `${ESC}${code}m${text}${ESC}39m`;
117
+ }
118
+ function bg(color, text) {
119
+ if (colorDepth === "none") return text;
120
+ const code = colorDepth === "truecolor" ? `48;2;${color[0]};${color[1]};${color[2]}` : `48;5;${rgbTo256(color)}`;
121
+ return `${ESC}${code}m${text}${ESC}49m`;
122
+ }
123
+ function lerp(a, b, t) {
124
+ const k = Math.min(1, Math.max(0, t));
125
+ return [
126
+ Math.round(a[0] + (b[0] - a[0]) * k),
127
+ Math.round(a[1] + (b[1] - a[1]) * k),
128
+ Math.round(a[2] + (b[2] - a[2]) * k)
129
+ ];
130
+ }
131
+ function gradient(text, stops, offset = 0) {
132
+ const chars = [...text];
133
+ const span = Math.max(1, chars.length - 1);
134
+ return chars.map((ch, i) => {
135
+ if (ch === " ") return ch;
136
+ let t = i / span + offset;
137
+ if (t > 1) t %= 1;
138
+ if (t < 0) t += 1;
139
+ const scaled = t * (stops.length - 1);
140
+ const idx = Math.min(stops.length - 2, Math.floor(scaled));
141
+ return fg(lerp(stops[idx], stops[idx + 1], scaled - idx), ch);
142
+ }).join("");
143
+ }
144
+ function stripAnsi(text) {
145
+ return text.replace(ANSI_PATTERN, "");
146
+ }
147
+ function isWide(cp) {
148
+ return cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 42191 && cp !== 12351 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65103 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141;
149
+ }
150
+ function charWidth(ch) {
151
+ const cp = ch.codePointAt(0) ?? 0;
152
+ if (cp < 32 || cp >= 127 && cp < 160) return 0;
153
+ if (cp >= 768 && cp <= 879) return 0;
154
+ if (cp === 8205 || cp >= 65024 && cp <= 65039) return 0;
155
+ return isWide(cp) ? 2 : 1;
156
+ }
157
+ function visibleWidth(text) {
158
+ let width = 0;
159
+ for (const ch of stripAnsi(text)) width += charWidth(ch);
160
+ return width;
161
+ }
162
+ function truncate(text, max, ellipsis = "\u2026") {
163
+ if (max <= 0) return "";
164
+ if (visibleWidth(text) <= max) return text;
165
+ const room = max - visibleWidth(ellipsis);
166
+ let out2 = "";
167
+ let width = 0;
168
+ let i = 0;
169
+ while (i < text.length) {
170
+ ANSI_PATTERN.lastIndex = i;
171
+ const match = text[i] === "\x1B" ? ANSI_PATTERN.exec(text) : null;
172
+ if (match && match.index === i) {
173
+ out2 += match[0];
174
+ i += match[0].length;
175
+ continue;
176
+ }
177
+ const ch = String.fromCodePoint(text.codePointAt(i) ?? 0);
178
+ const w = charWidth(ch);
179
+ if (width + w > room) break;
180
+ out2 += ch;
181
+ width += w;
182
+ i += ch.length;
183
+ }
184
+ return `${out2}${ESC}39;22;23;24m${ellipsis}`;
185
+ }
186
+ function fit(text, width, align = "left") {
187
+ const cut = truncate(text, width);
188
+ const gap = Math.max(0, width - visibleWidth(cut));
189
+ if (align === "right") return " ".repeat(gap) + cut;
190
+ if (align === "center") {
191
+ const left = Math.floor(gap / 2);
192
+ return " ".repeat(left) + cut + " ".repeat(gap - left);
193
+ }
194
+ return cut + " ".repeat(gap);
195
+ }
196
+ function wrap(text, width) {
197
+ const lines = [];
198
+ for (const paragraph of stripAnsi(text).split("\n")) {
199
+ let line = "";
200
+ for (const word2 of paragraph.split(/(\s+)/)) {
201
+ if (visibleWidth(line + word2) > width && line.trim() !== "") {
202
+ lines.push(line.trimEnd());
203
+ line = word2.trimStart();
204
+ } else {
205
+ line += word2;
206
+ }
207
+ while (visibleWidth(line) > width) {
208
+ lines.push(line.slice(0, width));
209
+ line = line.slice(width);
210
+ }
211
+ }
212
+ lines.push(line.trimEnd());
213
+ }
214
+ return lines;
215
+ }
216
+ var ESC, ANSI_PATTERN, colorDepth, bold, dim, inverse, cursor, screen, mouse;
217
+ var init_ansi = __esm({
218
+ "src/tui/ansi.ts"() {
219
+ "use strict";
220
+ ESC = "\x1B[";
221
+ ANSI_PATTERN = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*(?:\x07|\x1b\\)/g;
222
+ colorDepth = detectColorDepth();
223
+ bold = (text) => `${ESC}1m${text}${ESC}22m`;
224
+ dim = (text) => `${ESC}2m${text}${ESC}22m`;
225
+ inverse = (text) => `${ESC}7m${text}${ESC}27m`;
226
+ cursor = {
227
+ hide: `${ESC}?25l`,
228
+ show: `${ESC}?25h`,
229
+ home: `${ESC}H`,
230
+ to: (row, col) => `${ESC}${row};${col}H`
231
+ };
232
+ screen = {
233
+ enterAlt: `${ESC}?1049h`,
234
+ leaveAlt: `${ESC}?1049l`,
235
+ clear: `${ESC}2J`,
236
+ clearLine: `${ESC}2K`,
237
+ // Synchronized output (DEC 2026): terminals that support it paint a frame atomically.
238
+ beginSync: `${ESC}?2026h`,
239
+ endSync: `${ESC}?2026l`
240
+ };
241
+ mouse = {
242
+ enable: `${ESC}?1000h${ESC}?1003h${ESC}?1006h`,
243
+ disable: `${ESC}?1006l${ESC}?1003l${ESC}?1000l`
244
+ };
245
+ }
246
+ });
247
+
248
+ // src/util/reporter.ts
249
+ function printError(message) {
250
+ process.stderr.write(`${paint(RED, "xx")} ${message.split("\n").join("\n ")}
251
+ `);
252
+ }
253
+ function printHint(message) {
254
+ process.stderr.write(`${paint(GRAY, message)}
255
+ `);
256
+ }
257
+ var GREEN, YELLOW, RED, GRAY, useColor, paint, consoleReporter;
258
+ var init_reporter = __esm({
259
+ "src/util/reporter.ts"() {
260
+ "use strict";
261
+ init_ansi();
262
+ GREEN = [52, 211, 153];
263
+ YELLOW = [250, 204, 21];
264
+ RED = [248, 113, 113];
265
+ GRAY = [148, 163, 184];
266
+ useColor = () => process.stderr.isTTY && !("NO_COLOR" in process.env);
267
+ paint = (color, text) => useColor() ? fg(color, text) : text;
268
+ consoleReporter = {
269
+ step: (m) => process.stderr.write(`${paint(GREEN, "==>")} ${useColor() ? bold(m) : m}
270
+ `),
271
+ info: (m) => process.stderr.write(` ${m}
272
+ `),
273
+ warn: (m) => process.stderr.write(`${paint(YELLOW, "!!")} ${m}
274
+ `),
275
+ success: (m) => process.stderr.write(`${paint(GREEN, "\u2713")} ${m}
276
+ `),
277
+ output: (line) => process.stderr.write(` ${useColor() ? dim(line) : line}
278
+ `)
279
+ };
280
+ }
281
+ });
282
+
283
+ // src/version.ts
284
+ var VERSION;
285
+ var init_version = __esm({
286
+ "src/version.ts"() {
287
+ "use strict";
288
+ VERSION = true ? "0.1.0" : "0.0.0-dev";
289
+ }
290
+ });
291
+
292
+ // src/util/exec.ts
293
+ import { spawn } from "child_process";
294
+ function run(cmd, args, opts = {}) {
295
+ return new Promise((resolve2, reject) => {
296
+ let child;
297
+ try {
298
+ child = spawn(cmd, args, {
299
+ cwd: opts.cwd,
300
+ env: opts.env ?? process.env,
301
+ stdio: [opts.input === void 0 ? "ignore" : "pipe", "pipe", "pipe"],
302
+ signal: opts.signal
303
+ });
304
+ } catch (err) {
305
+ reject(err);
306
+ return;
307
+ }
308
+ let stdout = "";
309
+ let stderr = "";
310
+ child.stdout?.setEncoding("utf8").on("data", (d) => {
311
+ stdout += d;
312
+ });
313
+ child.stderr?.setEncoding("utf8").on("data", (d) => {
314
+ stderr += d;
315
+ });
316
+ if (opts.input !== void 0) child.stdin?.end(opts.input);
317
+ child.on("error", (err) => {
318
+ if (err.name === "AbortError") reject(new CancelledError());
319
+ else if (err.code === "ENOENT") resolve2({ code: 127, stdout, stderr: `${cmd}: command not found` });
320
+ else reject(err);
321
+ });
322
+ child.on("close", (code) => resolve2({ code: code ?? 1, stdout, stderr }));
323
+ });
324
+ }
325
+ async function runOk(cmd, args, opts = {}) {
326
+ const res = await run(cmd, args, opts);
327
+ if (res.code !== 0) {
328
+ const detail = (res.stderr || res.stdout).trim().split("\n").slice(-5).join("\n");
329
+ throw new DeployerError(`\`${cmd} ${args.join(" ")}\` failed (exit ${res.code})${detail ? `
330
+ ${detail}` : ""}`);
331
+ }
332
+ return res.stdout.trim();
333
+ }
334
+ function stream(cmd, args, opts) {
335
+ return new Promise((resolve2, reject) => {
336
+ if (opts.signal?.aborted) {
337
+ reject(new CancelledError());
338
+ return;
339
+ }
340
+ const child = spawn(cmd, args, {
341
+ cwd: opts.cwd,
342
+ env: opts.env ?? process.env,
343
+ stdio: [opts.input === void 0 ? "ignore" : "pipe", "pipe", "pipe"]
344
+ });
345
+ const onAbort = () => child.kill("SIGTERM");
346
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
347
+ const splitter = (name) => {
348
+ let buf = "";
349
+ return {
350
+ push(chunk) {
351
+ buf += chunk;
352
+ let nl;
353
+ while ((nl = buf.indexOf("\n")) >= 0) {
354
+ const raw = buf.slice(0, nl);
355
+ buf = buf.slice(nl + 1);
356
+ const line = raw.split("\r").filter(Boolean).pop() ?? "";
357
+ if (line.trim()) opts.onLine(line, name);
358
+ }
359
+ },
360
+ flush() {
361
+ const line = buf.split("\r").filter(Boolean).pop();
362
+ if (line?.trim()) opts.onLine(line, name);
363
+ buf = "";
364
+ }
365
+ };
366
+ };
367
+ const out2 = splitter("stdout");
368
+ const err = splitter("stderr");
369
+ child.stdout.setEncoding("utf8").on("data", (d) => out2.push(d));
370
+ child.stderr.setEncoding("utf8").on("data", (d) => err.push(d));
371
+ if (opts.input !== void 0) child.stdin?.end(opts.input);
372
+ child.on("error", (e) => {
373
+ opts.signal?.removeEventListener("abort", onAbort);
374
+ if (e.code === "ENOENT") reject(new DeployerError(`${cmd}: command not found`));
375
+ else reject(e);
376
+ });
377
+ child.on("close", (code) => {
378
+ opts.signal?.removeEventListener("abort", onAbort);
379
+ out2.flush();
380
+ err.flush();
381
+ if (opts.signal?.aborted) reject(new CancelledError());
382
+ else resolve2(code ?? 1);
383
+ });
384
+ });
385
+ }
386
+ function shellQuote(arg) {
387
+ if (/^[A-Za-z0-9_\/.,:=@%+-]+$/.test(arg)) return arg;
388
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
389
+ }
390
+ var init_exec = __esm({
391
+ "src/util/exec.ts"() {
392
+ "use strict";
393
+ init_errors();
394
+ }
395
+ });
396
+
397
+ // src/core/config.ts
398
+ import { existsSync, readFileSync } from "fs";
399
+ import { homedir } from "os";
400
+ import { dirname, isAbsolute, join, resolve } from "path";
401
+ function defaultTagVar(key2) {
402
+ return `${key2.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_VERSION`;
403
+ }
404
+ function findConfig(start = process.cwd()) {
405
+ const fromEnv = process.env.DEPLOYER_CONFIG;
406
+ if (fromEnv) return resolve(fromEnv);
407
+ let dir = resolve(start);
408
+ for (; ; ) {
409
+ const candidate = join(dir, CONFIG_FILE);
410
+ if (existsSync(candidate)) return candidate;
411
+ const parent = dirname(dir);
412
+ if (parent === dir) return void 0;
413
+ dir = parent;
414
+ }
415
+ }
416
+ function loadConfig(file) {
417
+ const path = file ? resolve(file) : findConfig();
418
+ if (!path) {
419
+ throw new DeployerError(`No ${CONFIG_FILE} found here or in any parent directory.
420
+ Run \`deployer init\` to create one.`);
421
+ }
422
+ let raw;
423
+ try {
424
+ raw = JSON.parse(readFileSync(path, "utf8"));
425
+ } catch (err) {
426
+ throw new DeployerError(`Could not read ${path}: ${err instanceof Error ? err.message : String(err)}`);
427
+ }
428
+ return parseConfig(raw, path);
429
+ }
430
+ function expandHome(p) {
431
+ if (p === "~") return homedir();
432
+ if (p.startsWith("~/")) return join(homedir(), p.slice(2));
433
+ return p;
434
+ }
435
+ function parseConfig(input, file) {
436
+ const errors = [];
437
+ const fail = (path, msg) => errors.push(`${path}: ${msg}`);
438
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
439
+ const str = (v, path, optional = true) => {
440
+ if (v === void 0 && optional) return void 0;
441
+ if (typeof v !== "string" || v.trim() === "") {
442
+ fail(path, "must be a non-empty string");
443
+ return void 0;
444
+ }
445
+ return v;
446
+ };
447
+ const bool = (v, path) => {
448
+ if (v === void 0) return void 0;
449
+ if (typeof v !== "boolean") {
450
+ fail(path, "must be true or false");
451
+ return void 0;
452
+ }
453
+ return v;
454
+ };
455
+ const strArray = (v, path) => {
456
+ if (v === void 0) return void 0;
457
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) {
458
+ fail(path, "must be an array of strings");
459
+ return void 0;
460
+ }
461
+ return v;
462
+ };
463
+ if (!isObj(input)) throw new DeployerError(`${file}: must contain a JSON object`);
464
+ const raw = input;
465
+ const root = dirname(file);
466
+ const known = /* @__PURE__ */ new Set(["$schema", "name", "repo", "imagePrefix", "ref", "version", "platforms", "pushLatest", "images", "checks", "deploy", "remote"]);
467
+ for (const k of Object.keys(input)) if (!known.has(k)) fail(k, "unknown field");
468
+ const repo = str(raw.repo, "repo");
469
+ if (repo && !/^[^/\s]+\/[^/\s]+$/.test(repo)) fail("repo", 'must look like "owner/name"');
470
+ const imagePrefix = str(raw.imagePrefix, "imagePrefix");
471
+ if (imagePrefix && imagePrefix !== imagePrefix.toLowerCase()) fail("imagePrefix", "must be lower-case (registries reject upper-case names)");
472
+ const platforms = strArray(raw.platforms, "platforms") ?? ["linux/amd64"];
473
+ if (raw.version !== void 0 && !isObj(raw.version)) fail("version", "must be an object");
474
+ const versionFile = str(raw.version?.file, "version.file");
475
+ const versionFormat = str(raw.version?.format, "version.format") ?? (versionFile ? "{version}-{sha}" : "{sha}");
476
+ const images = [];
477
+ if (!isObj(raw.images) || Object.keys(raw.images).length === 0) {
478
+ fail("images", "must be an object with at least one image");
479
+ } else {
480
+ for (const [key2, value] of Object.entries(raw.images)) {
481
+ const p = `images.${key2}`;
482
+ if (!IMAGE_KEY.test(key2)) fail(p, 'key must be lower-case letters, digits, ".", "_" or "-"');
483
+ if (!isObj(value)) {
484
+ fail(p, "must be an object");
485
+ continue;
486
+ }
487
+ const img = value;
488
+ const context = str(img.context, `${p}.context`, false) ?? ".";
489
+ const repository = str(img.repository, `${p}.repository`);
490
+ if (repository && (repository !== repository.toLowerCase() || repository.includes(":"))) {
491
+ fail(`${p}.repository`, "must be a lower-case image name without a tag");
492
+ }
493
+ if (img.buildArgs !== void 0 && (!isObj(img.buildArgs) || Object.values(img.buildArgs).some((x) => typeof x !== "string"))) {
494
+ fail(`${p}.buildArgs`, "must map names to string values");
495
+ }
496
+ if (img.service !== void 0 && img.service !== false && typeof img.service !== "string") {
497
+ fail(`${p}.service`, "must be a compose service name or false");
498
+ }
499
+ const tagVar = str(img.tagVar, `${p}.tagVar`) ?? defaultTagVar(key2);
500
+ if (!TAG_VAR.test(tagVar)) fail(`${p}.tagVar`, "must be a valid environment variable name");
501
+ const tagVarFallback = str(img.tagVarFallback, `${p}.tagVarFallback`);
502
+ if (tagVarFallback && !TAG_VAR.test(tagVarFallback)) fail(`${p}.tagVarFallback`, "must be a valid environment variable name");
503
+ const versioned = bool(img.versioned, `${p}.versioned`) ?? true;
504
+ const tags = strArray(img.tags, `${p}.tags`) ?? [];
505
+ if (!versioned && tags.length === 0) fail(p, 'an unversioned image needs at least one entry in "tags"');
506
+ images.push({
507
+ key: key2,
508
+ context,
509
+ dockerfile: str(img.dockerfile, `${p}.dockerfile`) ?? join(context, "Dockerfile"),
510
+ repository: repository ?? "",
511
+ explicitRepository: Boolean(repository),
512
+ platforms: strArray(img.platforms, `${p}.platforms`) ?? platforms,
513
+ buildArgs: img.buildArgs ?? {},
514
+ target: str(img.target, `${p}.target`),
515
+ extraArgs: strArray(img.extraArgs, `${p}.extraArgs`) ?? [],
516
+ isDefault: bool(img.default, `${p}.default`) ?? true,
517
+ versioned,
518
+ tags,
519
+ service: img.service === false ? null : typeof img.service === "string" ? img.service : key2,
520
+ tagVar,
521
+ tagVarFallback
522
+ });
523
+ }
524
+ const vars = /* @__PURE__ */ new Map();
525
+ for (const img of images.filter((i) => i.service)) {
526
+ const other = vars.get(img.tagVar);
527
+ if (other) fail(`images.${img.key}.tagVar`, `"${img.tagVar}" is already used by ${other}`);
528
+ vars.set(img.tagVar, img.key);
529
+ }
530
+ }
531
+ const checks = [];
532
+ if (raw.checks !== void 0) {
533
+ if (!Array.isArray(raw.checks)) fail("checks", "must be an array");
534
+ else raw.checks.forEach((ch, i) => {
535
+ const name = str(ch?.name, `checks[${i}].name`, false);
536
+ const run2 = str(ch?.run, `checks[${i}].run`, false);
537
+ if (name && run2) checks.push({ name, run: run2, cwd: str(ch.cwd, `checks[${i}].cwd`) });
538
+ });
539
+ }
540
+ const d = raw.deploy ?? {};
541
+ if (!isObj(raw.deploy ?? {})) fail("deploy", "must be an object");
542
+ const pull = d.pull ?? "never";
543
+ if (!["never", "missing", "always"].includes(pull)) fail("deploy.pull", 'must be "never", "missing" or "always"');
544
+ const up2 = d.up ?? "all";
545
+ if (!["all", "deployed"].includes(up2)) fail("deploy.up", 'must be "all" or "deployed"');
546
+ if (d.healthcheck !== void 0) {
547
+ if (!isObj(d.healthcheck)) fail("deploy.healthcheck", "must be an object");
548
+ else {
549
+ str(d.healthcheck.url, "deploy.healthcheck.url", false);
550
+ if (d.healthcheck.timeout !== void 0 && !(Number(d.healthcheck.timeout) > 0)) fail("deploy.healthcheck.timeout", "must be seconds > 0");
551
+ }
552
+ }
553
+ const postDeploy = [];
554
+ if (d.postDeploy !== void 0) {
555
+ if (!Array.isArray(d.postDeploy)) fail("deploy.postDeploy", "must be an array");
556
+ else d.postDeploy.forEach((h, i) => {
557
+ const name = str(h?.name, `deploy.postDeploy[${i}].name`, false);
558
+ const run2 = str(h?.run, `deploy.postDeploy[${i}].run`, false);
559
+ if (name && run2) postDeploy.push({ name, run: run2 });
560
+ });
561
+ }
562
+ const dir = d.dir ? resolve(root, expandHome(d.dir)) : root;
563
+ let remote;
564
+ if (raw.remote !== void 0) {
565
+ if (!isObj(raw.remote)) fail("remote", "must be an object");
566
+ else {
567
+ const host = str(raw.remote.host, "remote.host", false);
568
+ const rdir = str(raw.remote.dir, "remote.dir", false);
569
+ if (raw.remote.files !== void 0 && (!Array.isArray(raw.remote.files) || raw.remote.files.some((f) => !isObj(f) || typeof f.from !== "string"))) {
570
+ fail("remote.files", 'must be an array of { "from": "...", "to": "..." }');
571
+ }
572
+ if (host && rdir) remote = { ...raw.remote, host, dir: rdir, command: raw.remote.command ?? "deployer" };
573
+ }
574
+ }
575
+ if (errors.length) {
576
+ throw new DeployerError(`${file} is not valid:
577
+ ${errors.map((e) => ` \u2022 ${e}`).join("\n")}`);
578
+ }
579
+ return {
580
+ file,
581
+ root,
582
+ name: raw.name ?? (repo ? repo.split("/")[1] : root.split("/").pop() ?? "app"),
583
+ repo,
584
+ imagePrefix,
585
+ ref: raw.ref ?? "HEAD",
586
+ versionFile,
587
+ versionFormat,
588
+ pushLatest: raw.pushLatest ?? true,
589
+ images,
590
+ checks,
591
+ deploy: {
592
+ dir: isAbsolute(dir) ? dir : resolve(dir),
593
+ composeFile: d.composeFile ?? "docker-compose.yml",
594
+ envFile: d.envFile ?? ".env",
595
+ pull,
596
+ up: up2,
597
+ healthcheck: d.healthcheck,
598
+ waitForServices: d.waitForServices ?? true,
599
+ postDeploy,
600
+ autoRollback: d.autoRollback ?? true,
601
+ keepHistory: d.keepHistory ?? 30
602
+ },
603
+ remote,
604
+ raw
605
+ };
606
+ }
607
+ function resolveImages(config, prefix) {
608
+ for (const img of config.images) {
609
+ if (!img.explicitRepository) img.repository = `${prefix.replace(/\/+$/, "")}/${img.key}`;
610
+ }
611
+ return config.images;
612
+ }
613
+ function deployableImages(config) {
614
+ return config.images.filter((i) => i.service !== null && i.versioned);
615
+ }
616
+ function imagesByName(config, names) {
617
+ if (names.length === 0) return config.images.filter((i) => i.isDefault);
618
+ const unknown = names.filter((n) => !config.images.some((i) => i.key === n));
619
+ if (unknown.length) {
620
+ throw new DeployerError(`Unknown image${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")} (expected any of: ${config.images.map((i) => i.key).join(", ")})`);
621
+ }
622
+ return config.images.filter((i) => names.includes(i.key));
623
+ }
624
+ var CONFIG_FILE, TAG_VAR, IMAGE_KEY;
625
+ var init_config = __esm({
626
+ "src/core/config.ts"() {
627
+ "use strict";
628
+ init_errors();
629
+ CONFIG_FILE = "deployer.json";
630
+ TAG_VAR = /^[A-Za-z_][A-Za-z0-9_]*$/;
631
+ IMAGE_KEY = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
632
+ }
633
+ });
634
+
635
+ // src/core/docker.ts
636
+ import { readFileSync as readFileSync2 } from "fs";
637
+ import { homedir as homedir2 } from "os";
638
+ import { join as join2 } from "path";
639
+ function registryOf(repository) {
640
+ const first = repository.split("/")[0];
641
+ return first.includes(".") || first.includes(":") || first === "localhost" ? first : "docker.io";
642
+ }
643
+ async function assertDocker(opts = {}) {
644
+ const version = await run("docker", ["version", "--format", "{{.Client.Version}}"]);
645
+ if (version.code === 127) throw new DeployerError("docker is not installed (https://docs.docker.com/engine/install/)");
646
+ const info = await run("docker", ["info", "--format", "{{.ServerVersion}}"]);
647
+ if (info.code !== 0) {
648
+ const detail = info.stderr.toLowerCase();
649
+ if (detail.includes("permission denied")) {
650
+ throw new DeployerError("Docker is running but this user cannot reach it.\nAdd yourself to the docker group: sudo usermod -aG docker $USER (then log in again)");
651
+ }
652
+ throw new DeployerError("The Docker daemon is not running \u2014 start Docker (Desktop) and retry");
653
+ }
654
+ if (opts.buildx) {
655
+ const bx = await run("docker", ["buildx", "version"]);
656
+ if (bx.code !== 0) throw new DeployerError("docker buildx is required (bundled with Docker Desktop; on Linux: apt install docker-buildx-plugin)");
657
+ }
658
+ }
659
+ async function compose() {
660
+ if (composeCmd) return composeCmd;
661
+ if ((await run("docker", ["compose", "version"])).code === 0) composeCmd = ["docker", ["compose"]];
662
+ else if ((await run("docker-compose", ["version"])).code === 0) composeCmd = ["docker-compose", []];
663
+ else throw new DeployerError("docker compose is not installed (apt install docker-compose-plugin)");
664
+ return composeCmd;
665
+ }
666
+ function readDockerConfig() {
667
+ const dir = process.env.DOCKER_CONFIG ?? join2(homedir2(), ".docker");
668
+ try {
669
+ return JSON.parse(readFileSync2(join2(dir, "config.json"), "utf8"));
670
+ } catch {
671
+ return {};
672
+ }
673
+ }
674
+ async function dockerCredentials(registry) {
675
+ const cfg = readDockerConfig();
676
+ const keys = [registry, `https://${registry}`, `https://${registry}/v1/`, `https://${registry}/v2/`];
677
+ const helper = keys.map((k) => cfg.credHelpers?.[k]).find(Boolean) ?? cfg.credsStore;
678
+ if (helper) {
679
+ for (const key2 of keys) {
680
+ const res = await run(`docker-credential-${helper}`, ["get"], { input: key2 });
681
+ if (res.code === 0) {
682
+ try {
683
+ const parsed = JSON.parse(res.stdout);
684
+ if (parsed.Secret) return { username: parsed.Username ?? "", secret: parsed.Secret };
685
+ } catch {
686
+ }
687
+ }
688
+ }
689
+ }
690
+ for (const key2 of keys) {
691
+ const entry = cfg.auths?.[key2];
692
+ if (entry?.auth) {
693
+ const decoded = Buffer.from(entry.auth, "base64").toString("utf8");
694
+ const i = decoded.indexOf(":");
695
+ if (i > 0) return { username: decoded.slice(0, i), secret: decoded.slice(i + 1) };
696
+ }
697
+ }
698
+ return void 0;
699
+ }
700
+ async function isLoggedIn(registry) {
701
+ const cfg = readDockerConfig();
702
+ if (cfg.auths && Object.keys(cfg.auths).some((k) => k === registry || k.includes(`//${registry}`))) {
703
+ return true;
704
+ }
705
+ return await dockerCredentials(registry) !== void 0;
706
+ }
707
+ async function dockerLogin(registry, username, secret) {
708
+ await runOk("docker", ["login", registry, "-u", username, "--password-stdin"], { input: secret });
709
+ }
710
+ function envToken() {
711
+ return process.env.DEPLOYER_TOKEN || process.env.GHCR_TOKEN || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || void 0;
712
+ }
713
+ async function ghToken() {
714
+ const res = await run("gh", ["auth", "token"]);
715
+ return res.code === 0 && res.stdout.trim() ? res.stdout.trim() : void 0;
716
+ }
717
+ async function ensurePushLogin(registry, owner, reporter) {
718
+ if (registry !== "ghcr.io") {
719
+ if (!/^(localhost|127\.0\.0\.1)(:|$)/.test(registry) && !await isLoggedIn(registry)) reporter.warn(`Not logged in to ${registry} \u2014 run \`docker login ${registry}\` if the push is refused`);
720
+ return;
721
+ }
722
+ const token = envToken();
723
+ if (token) {
724
+ const user2 = process.env.GHCR_USER || owner || "token";
725
+ reporter.step(`Logging in to ${registry} as ${user2} (token from the environment)`);
726
+ await dockerLogin(registry, user2, token);
727
+ return;
728
+ }
729
+ if (await isLoggedIn(registry)) return;
730
+ const status = await run("gh", ["auth", "status"]);
731
+ if (status.code === 127) {
732
+ throw new DeployerError(`Not logged in to ${registry}. Either:
733
+ \u2022 export GHCR_TOKEN=<a token with write:packages>
734
+ \u2022 docker login ${registry}
735
+ \u2022 install the GitHub CLI and run gh auth login`);
736
+ }
737
+ if (status.code !== 0) throw new DeployerError("gh is not logged in: run 'gh auth login'");
738
+ if (!(status.stdout + status.stderr).includes("write:packages")) {
739
+ throw new DeployerError("Your gh token cannot push images. Run: gh auth refresh -h github.com -s write:packages");
740
+ }
741
+ const user = await runOk("gh", ["api", "user", "--jq", ".login"]);
742
+ reporter.step(`Logging in to ${registry} as ${user} (gh token)`);
743
+ await dockerLogin(registry, user, await ghToken() ?? "");
744
+ }
745
+ var composeCmd, DOCKER_TAG;
746
+ var init_docker = __esm({
747
+ "src/core/docker.ts"() {
748
+ "use strict";
749
+ init_errors();
750
+ init_exec();
751
+ DOCKER_TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;
752
+ }
753
+ });
754
+
755
+ // src/core/git.ts
756
+ import { spawn as spawn2 } from "child_process";
757
+ async function gitRoot(cwd) {
758
+ const res = await run("git", ["rev-parse", "--show-toplevel"], { cwd });
759
+ return res.code === 0 ? res.stdout.trim() : void 0;
760
+ }
761
+ async function resolveCommit(root, ref) {
762
+ const res = await run("git", ["rev-parse", "--verify", "-q", `${ref}^{commit}`], { cwd: root });
763
+ if (res.code !== 0) throw new DeployerError(`'${ref}' is not a branch or commit in ${root}`);
764
+ return res.stdout.trim();
765
+ }
766
+ async function headCommit(root) {
767
+ const res = await run("git", ["rev-parse", "HEAD"], { cwd: root });
768
+ return res.code === 0 ? res.stdout.trim() : void 0;
769
+ }
770
+ async function currentBranch(root) {
771
+ const res = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: root });
772
+ return res.code === 0 ? res.stdout.trim() : "HEAD";
773
+ }
774
+ async function isDirty(root) {
775
+ const res = await run("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: root });
776
+ return res.code === 0 && res.stdout.trim() !== "";
777
+ }
778
+ async function isPushed(root, sha) {
779
+ const fetched = await run("git", ["fetch", "-q", "origin"], { cwd: root });
780
+ if (fetched.code !== 0) return void 0;
781
+ const res = await run("git", ["branch", "-r", "--contains", sha], { cwd: root });
782
+ return res.code === 0 ? res.stdout.trim() !== "" : void 0;
783
+ }
784
+ async function originRepo(root) {
785
+ const res = await run("git", ["remote", "get-url", "origin"], { cwd: root });
786
+ if (res.code !== 0) return void 0;
787
+ return parseRepoSlug(res.stdout.trim());
788
+ }
789
+ function parseRepoSlug(url) {
790
+ const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)(?::\d+)?[:/](.+?)(?:\.git)?\/?$/i.exec(url.trim());
791
+ if (!m || !m[1].includes(".")) return void 0;
792
+ const parts = m[2].split("/").filter(Boolean);
793
+ return parts.length >= 2 ? parts.slice(-2).join("/") : void 0;
794
+ }
795
+ async function showFile(root, sha, path) {
796
+ const res = await run("git", ["show", `${sha}:${path.replace(/^\.\//, "")}`], { cwd: root });
797
+ return res.code === 0 ? res.stdout : void 0;
798
+ }
799
+ function exportTree(root, sha, dest) {
800
+ return new Promise((resolve2, reject) => {
801
+ const archive = spawn2("git", ["archive", "--format=tar", sha], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
802
+ const tar = spawn2("tar", ["-x", "-C", dest], { stdio: ["pipe", "ignore", "pipe"] });
803
+ let err = "";
804
+ archive.stderr.on("data", (d) => {
805
+ err += d;
806
+ });
807
+ tar.stderr.on("data", (d) => {
808
+ err += d;
809
+ });
810
+ archive.stdout.pipe(tar.stdin);
811
+ let pending = 2;
812
+ let failed = false;
813
+ const done = (code, what) => {
814
+ if (code !== 0 && !failed) {
815
+ failed = true;
816
+ reject(new DeployerError(`${what} failed while exporting ${sha.slice(0, 8)}: ${err.trim()}`));
817
+ }
818
+ if (--pending === 0 && !failed) resolve2();
819
+ };
820
+ archive.on("error", reject);
821
+ tar.on("error", reject);
822
+ archive.on("close", (c2) => done(c2, "git archive"));
823
+ tar.on("close", (c2) => done(c2, "tar"));
824
+ });
825
+ }
826
+ var init_git = __esm({
827
+ "src/core/git.ts"() {
828
+ "use strict";
829
+ init_errors();
830
+ init_exec();
831
+ }
832
+ });
833
+
834
+ // src/core/project.ts
835
+ import { existsSync as existsSync2 } from "fs";
836
+ import { join as join3 } from "path";
837
+ async function openProject(config) {
838
+ const root = await gitRoot(config.root);
839
+ const repo = config.repo ?? (root ? await originRepo(root) : void 0);
840
+ const imagePrefix = config.imagePrefix ?? (repo ? `ghcr.io/${repo.toLowerCase()}` : void 0);
841
+ const needsPrefix = config.images.some((i) => !i.explicitRepository);
842
+ if (!imagePrefix && needsPrefix) {
843
+ throw new DeployerError(
844
+ `Cannot tell where the images live: set "repo" (owner/name) or "imagePrefix" in ${config.file}.` + (root ? "" : "\nThis directory is not a git checkout, so the origin remote cannot be used.")
845
+ );
846
+ }
847
+ resolveImages(config, imagePrefix ?? "");
848
+ const composePath = join3(config.deploy.dir, config.deploy.composeFile);
849
+ return {
850
+ config,
851
+ gitRoot: root,
852
+ repo,
853
+ imagePrefix: imagePrefix ?? "",
854
+ canBuild: Boolean(root) && config.images.some((i) => existsSync2(join3(root, i.dockerfile))),
855
+ canDeploy: existsSync2(composePath),
856
+ composePath
857
+ };
858
+ }
859
+ function sourceRoot(project2) {
860
+ if (!project2.gitRoot) throw new DeployerError("Building needs a git checkout \u2014 this directory is not one.");
861
+ return project2.gitRoot;
862
+ }
863
+ var init_project = __esm({
864
+ "src/core/project.ts"() {
865
+ "use strict";
866
+ init_errors();
867
+ init_config();
868
+ init_git();
869
+ }
870
+ });
871
+
872
+ // src/core/build.ts
873
+ import { mkdtempSync, rmSync } from "fs";
874
+ import { tmpdir } from "os";
875
+ import { join as join4 } from "path";
876
+ function formatVersion(format, vars) {
877
+ const d = vars.date;
878
+ const pad = (n) => String(n).padStart(2, "0");
879
+ const out2 = format.replaceAll("{version}", vars.version ?? "").replaceAll("{sha}", vars.sha.slice(0, 8)).replaceAll("{branch}", vars.branch.replace(/[^A-Za-z0-9_.-]+/g, "-")).replaceAll("{date}", `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}`).replaceAll("{time}", `${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}`);
880
+ return out2;
881
+ }
882
+ function expandTag(template, image, version, sha) {
883
+ return template.replaceAll("{version}", version).replaceAll("{sha}", sha.slice(0, 8)).replace(/\{arg:([A-Za-z0-9_]+)\}/g, (_, name) => {
884
+ const value = image.buildArgs[name];
885
+ if (value === void 0) throw new DeployerError(`images.${image.key}.tags uses {arg:${name}} but buildArgs has no ${name}`);
886
+ return value;
887
+ });
888
+ }
889
+ function tagsFor(image, version, sha, pushLatest) {
890
+ const tags = [];
891
+ if (image.versioned) {
892
+ tags.push(`${image.repository}:${version}`);
893
+ if (pushLatest) tags.push(`${image.repository}:latest`);
894
+ }
895
+ for (const t of image.tags) tags.push(`${image.repository}:${expandTag(t, image, version, sha)}`);
896
+ for (const t of tags) {
897
+ const tag = t.slice(t.lastIndexOf(":") + 1);
898
+ if (!DOCKER_TAG.test(tag)) throw new DeployerError(`Invalid image tag "${tag}" for ${image.key}`);
899
+ }
900
+ return tags;
901
+ }
902
+ async function planBuild(project2, opts = {}) {
903
+ const root = sourceRoot(project2);
904
+ const { config } = project2;
905
+ const ref = opts.ref ?? config.ref;
906
+ const sha = await resolveCommit(root, ref);
907
+ const images = imagesByName(config, opts.images ?? []);
908
+ if (images.length === 0) throw new DeployerError("No images selected");
909
+ let tag = opts.tag;
910
+ if (!tag) {
911
+ let version;
912
+ if (config.versionFile) {
913
+ const text = await showFile(root, sha, config.versionFile);
914
+ if (text === void 0) throw new DeployerError(`${config.versionFile} does not exist at ${sha.slice(0, 8)}`);
915
+ try {
916
+ version = JSON.parse(text).version;
917
+ } catch {
918
+ throw new DeployerError(`${config.versionFile} is not valid JSON`);
919
+ }
920
+ if (!version) throw new DeployerError(`Could not read "version" from ${config.versionFile}`);
921
+ } else if (config.versionFormat.includes("{version}")) {
922
+ throw new DeployerError("version.format uses {version} but version.file is not set");
923
+ }
924
+ const branch = ref === "HEAD" ? await currentBranch(root) : ref;
925
+ tag = formatVersion(config.versionFormat, { version, sha, branch, date: /* @__PURE__ */ new Date() });
926
+ }
927
+ if (!DOCKER_TAG.test(tag)) throw new DeployerError(`Invalid image tag: '${tag}' (allowed: letters, digits, _ . -, max 128)`);
928
+ const pushLatest = opts.pushLatest ?? config.pushLatest;
929
+ if (opts.platforms?.length) for (const img of images) img.platforms = opts.platforms;
930
+ const tags = {};
931
+ for (const img of images) tags[img.key] = tagsFor(img, tag, sha, pushLatest);
932
+ return { sha, ref, tag, images, pushLatest, tags };
933
+ }
934
+ function buildxArgs(image, plan, src, repo, created) {
935
+ const args = ["buildx", "build", "--platform", image.platforms.join(","), "--file", join4(src, image.dockerfile)];
936
+ if (repo) args.push("--label", `org.opencontainers.image.source=https://github.com/${repo}`);
937
+ args.push(
938
+ "--label",
939
+ `org.opencontainers.image.revision=${plan.sha}`,
940
+ "--label",
941
+ `org.opencontainers.image.version=${plan.tag}`,
942
+ "--label",
943
+ `org.opencontainers.image.created=${created}`
944
+ );
945
+ for (const t of plan.tags[image.key]) args.push("-t", t);
946
+ for (const [k, v] of Object.entries(image.buildArgs)) args.push("--build-arg", `${k}=${v}`);
947
+ if (image.target) args.push("--target", image.target);
948
+ args.push(...image.extraArgs, "--progress=plain", "--push", join4(src, image.context));
949
+ return args;
950
+ }
951
+ async function build(project2, reporter, opts = {}) {
952
+ const started = Date.now();
953
+ const root = sourceRoot(project2);
954
+ const { config } = project2;
955
+ const plan = await planBuild(project2, opts);
956
+ const check = () => {
957
+ if (opts.signal?.aborted) throw new CancelledError();
958
+ };
959
+ if (!opts.dryRun) {
960
+ reporter.step("Checking docker and buildx");
961
+ await assertDocker({ buildx: true });
962
+ const registries = new Set(plan.images.map((i) => registryOf(i.repository)));
963
+ for (const registry of registries) await ensurePushLogin(registry, project2.repo?.split("/")[0], reporter);
964
+ }
965
+ if (await headCommit(root) === plan.sha && await isDirty(root)) {
966
+ reporter.warn(`You have uncommitted changes \u2014 they are NOT in these images (only commit ${plan.sha.slice(0, 8)} is)`);
967
+ }
968
+ const pushed = await isPushed(root, plan.sha);
969
+ if (pushed === false) reporter.warn(`Commit ${plan.sha.slice(0, 8)} is not pushed to the remote yet \u2014 push it so the release can be traced`);
970
+ reporter.step(`Building ${plan.ref} (${plan.sha.slice(0, 8)}) as tag '${plan.tag}'`);
971
+ reporter.info(`Images: ${plan.images.map((i) => i.key).join(" ")} \xB7 move :latest: ${plan.pushLatest ? "yes" : "no"}`);
972
+ check();
973
+ const src = mkdtempSync(join4(process.env.TMPDIR ?? tmpdir(), "deployer-build-"));
974
+ const published = [];
975
+ try {
976
+ await exportTree(root, plan.sha, src);
977
+ if (opts.runChecks && config.checks.length) {
978
+ for (const ch of config.checks) {
979
+ check();
980
+ const cwd = join4(src, ch.cwd ?? ".");
981
+ reporter.step(`Check: ${ch.name}`);
982
+ if (opts.dryRun) {
983
+ reporter.info(`(cd ${shellQuote(ch.cwd ?? ".")} && ${ch.run})`);
984
+ continue;
985
+ }
986
+ const code = await stream("sh", ["-c", ch.run], { cwd, signal: opts.signal, onLine: (l) => reporter.output(l) });
987
+ if (code !== 0) throw new DeployerError(`Check "${ch.name}" failed (exit ${code}) \u2014 no images were built`);
988
+ rmSync(join4(cwd, "node_modules"), { recursive: true, force: true });
989
+ }
990
+ }
991
+ const created = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
992
+ for (const image of plan.images) {
993
+ check();
994
+ const t0 = Date.now();
995
+ const args = buildxArgs(image, plan, src, project2.repo, created);
996
+ reporter.step(`Building ${image.key} (${image.platforms.join(", ")})`);
997
+ if (opts.dryRun) {
998
+ reporter.info(["docker", ...args].map((a) => shellQuote(a.replace(src, "<tree>"))).join(" "));
999
+ continue;
1000
+ }
1001
+ const code = await stream("docker", args, { signal: opts.signal, onLine: (l) => reporter.output(l) });
1002
+ if (code !== 0) throw new DeployerError(`Building ${image.key} failed (exit ${code})`);
1003
+ published.push(...plan.tags[image.key]);
1004
+ reporter.success(`${image.key} pushed in ${formatSeconds((Date.now() - t0) / 1e3)}`);
1005
+ }
1006
+ } finally {
1007
+ rmSync(src, { recursive: true, force: true });
1008
+ }
1009
+ const seconds = (Date.now() - started) / 1e3;
1010
+ if (!opts.dryRun) {
1011
+ reporter.step(`Published after ${formatSeconds(seconds)}:`);
1012
+ for (const p of published) reporter.info(p);
1013
+ }
1014
+ return { ...plan, pushed: published, seconds };
1015
+ }
1016
+ function formatSeconds(s) {
1017
+ if (s < 60) return `${Math.round(s)} s`;
1018
+ const m = Math.floor(s / 60);
1019
+ return m < 60 ? `${m} min ${Math.round(s % 60)} s` : `${Math.floor(m / 60)} h ${m % 60} min`;
1020
+ }
1021
+ function rolloutCommand(plan) {
1022
+ const keys = plan.images.filter((i) => i.service && i.versioned).map((i) => i.key);
1023
+ if (keys.length === 0) return void 0;
1024
+ return `deployer deploy ${plan.tag} --images ${keys.join(",")} --yes`;
1025
+ }
1026
+ var init_build = __esm({
1027
+ "src/core/build.ts"() {
1028
+ "use strict";
1029
+ init_errors();
1030
+ init_exec();
1031
+ init_config();
1032
+ init_docker();
1033
+ init_git();
1034
+ init_project();
1035
+ }
1036
+ });
1037
+
1038
+ // src/core/envfile.ts
1039
+ import { chmodSync, existsSync as existsSync3, readFileSync as readFileSync3, renameSync, statSync, writeFileSync } from "fs";
1040
+ function unquote(value) {
1041
+ const v = value.trim();
1042
+ if (v.length >= 2 && (v[0] === '"' || v[0] === "'") && v[v.length - 1] === v[0]) return v.slice(1, -1);
1043
+ return v.replace(/\s+#.*$/, "");
1044
+ }
1045
+ function parseEnv(text) {
1046
+ const vars = /* @__PURE__ */ new Map();
1047
+ for (const line of text.split(/\r?\n/)) {
1048
+ const m = LINE.exec(line);
1049
+ if (m && !vars.has(m[2])) vars.set(m[2], unquote(m[3]));
1050
+ }
1051
+ return vars;
1052
+ }
1053
+ function setEnvVar(text, key2, value) {
1054
+ const lines = text.split("\n");
1055
+ const index = lines.findIndex((line) => LINE.exec(line)?.[2] === key2);
1056
+ if (index >= 0) {
1057
+ const m = LINE.exec(lines[index]);
1058
+ lines[index] = `${m[1] ?? ""}${key2}=${value}${lines[index].endsWith("\r") ? "\r" : ""}`;
1059
+ return lines.join("\n");
1060
+ }
1061
+ const base = text === "" || text.endsWith("\n") ? text : `${text}
1062
+ `;
1063
+ return `${base}${key2}=${value}
1064
+ `;
1065
+ }
1066
+ function removeEnvVar(text, key2) {
1067
+ return text.split("\n").filter((line) => LINE.exec(line)?.[2] !== key2).join("\n");
1068
+ }
1069
+ var LINE, EnvFile;
1070
+ var init_envfile = __esm({
1071
+ "src/core/envfile.ts"() {
1072
+ "use strict";
1073
+ LINE = /^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
1074
+ EnvFile = class {
1075
+ constructor(path) {
1076
+ this.path = path;
1077
+ this.text = existsSync3(path) ? readFileSync3(path, "utf8") : "";
1078
+ }
1079
+ path;
1080
+ text;
1081
+ get vars() {
1082
+ return parseEnv(this.text);
1083
+ }
1084
+ get(key2) {
1085
+ return this.vars.get(key2);
1086
+ }
1087
+ set(key2, value) {
1088
+ this.text = setEnvVar(this.text, key2, value);
1089
+ }
1090
+ unset(key2) {
1091
+ this.text = removeEnvVar(this.text, key2);
1092
+ }
1093
+ /** Atomic write that keeps the file's mode (a .env is usually 0600). */
1094
+ save() {
1095
+ const mode = existsSync3(this.path) ? statSync(this.path).mode & 511 : 384;
1096
+ const tmp = `${this.path}.deployer-tmp`;
1097
+ writeFileSync(tmp, this.text, { mode });
1098
+ chmodSync(tmp, mode);
1099
+ renameSync(tmp, this.path);
1100
+ }
1101
+ };
1102
+ }
1103
+ });
1104
+
1105
+ // src/core/deploy.ts
1106
+ import { existsSync as existsSync4, mkdirSync, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1107
+ import { hostname, userInfo } from "os";
1108
+ import { join as join5 } from "path";
1109
+ function stateDir(config) {
1110
+ const dir = join5(config.deploy.dir, ".deployer");
1111
+ mkdirSync(dir, { recursive: true, mode: 448 });
1112
+ return dir;
1113
+ }
1114
+ function envPath(config) {
1115
+ return join5(config.deploy.dir, config.deploy.envFile);
1116
+ }
1117
+ function historyPath(config) {
1118
+ return join5(config.deploy.dir, ".deployer", "history.json");
1119
+ }
1120
+ function readHistory(config) {
1121
+ try {
1122
+ return JSON.parse(readFileSync4(historyPath(config), "utf8"));
1123
+ } catch {
1124
+ return [];
1125
+ }
1126
+ }
1127
+ function appendHistory(config, entry) {
1128
+ stateDir(config);
1129
+ const all = [entry, ...readHistory(config)].slice(0, config.deploy.keepHistory);
1130
+ writeFileSync2(historyPath(config), `${JSON.stringify(all, null, 2)}
1131
+ `, { mode: 384 });
1132
+ }
1133
+ function acquireLock(config) {
1134
+ const path = join5(stateDir(config), "lock");
1135
+ const mine = JSON.stringify({ pid: process.pid, host: hostname(), at: (/* @__PURE__ */ new Date()).toISOString() });
1136
+ for (let attempt = 0; attempt < 2; attempt++) {
1137
+ try {
1138
+ writeFileSync2(path, mine, { flag: "wx", mode: 384 });
1139
+ return () => rmSync2(path, { force: true });
1140
+ } catch (err) {
1141
+ if (err.code !== "EEXIST") throw err;
1142
+ let holder = {};
1143
+ try {
1144
+ holder = JSON.parse(readFileSync4(path, "utf8"));
1145
+ } catch {
1146
+ }
1147
+ const alive = holder.pid !== void 0 && holder.host === hostname() && pidAlive(holder.pid);
1148
+ if (alive) {
1149
+ throw new DeployerError(`Another deploy is running (pid ${holder.pid}, started ${holder.at}).
1150
+ If it is not, remove ${path}`);
1151
+ }
1152
+ rmSync2(path, { force: true });
1153
+ }
1154
+ }
1155
+ throw new DeployerError(`Could not take the deploy lock at ${path}`);
1156
+ }
1157
+ function pidAlive(pid) {
1158
+ try {
1159
+ process.kill(pid, 0);
1160
+ return true;
1161
+ } catch (err) {
1162
+ return err.code === "EPERM";
1163
+ }
1164
+ }
1165
+ function currentState(config) {
1166
+ const env = new EnvFile(envPath(config));
1167
+ return deployableImages(config).map((image) => {
1168
+ const own = env.get(image.tagVar);
1169
+ if (own) return { image, tag: own, source: "var" };
1170
+ const fb = image.tagVarFallback ? env.get(image.tagVarFallback) : void 0;
1171
+ if (fb) return { image, tag: fb, source: "fallback" };
1172
+ return { image, source: "unset" };
1173
+ });
1174
+ }
1175
+ function planVars(config, targets, env) {
1176
+ const set = [];
1177
+ const warnings = [];
1178
+ const dragged = [];
1179
+ const moving = new Set(targets.map((t) => t.image.key));
1180
+ const changed = new Set(targets.map((t) => t.image.tagVar));
1181
+ for (const img of deployableImages(config)) {
1182
+ if (moving.has(img.key) || !img.tagVarFallback || !changed.has(img.tagVarFallback)) continue;
1183
+ if (env.get(img.tagVar)) continue;
1184
+ const today = env.get(img.tagVarFallback);
1185
+ if (today) {
1186
+ set.push({ key: img.tagVar, value: today, reason: `pin ${img.key} to the tag it runs today` });
1187
+ } else {
1188
+ const tag = targets.find((t) => t.image.tagVar === img.tagVarFallback).tag;
1189
+ warnings.push(`${img.key} follows ${img.tagVarFallback}, which is not set yet \u2014 it moves to ${tag} too`);
1190
+ dragged.push({ image: img, tag });
1191
+ }
1192
+ }
1193
+ for (const t of targets) set.push({ key: t.image.tagVar, value: t.tag, reason: `${t.image.key} \u2192 ${t.tag}` });
1194
+ return { set, warnings, dragged };
1195
+ }
1196
+ async function composeArgs(config) {
1197
+ const [cmd, base] = await compose();
1198
+ const args = [...base, "-f", config.deploy.composeFile];
1199
+ if (config.deploy.envFile !== ".env") args.push("--env-file", config.deploy.envFile);
1200
+ return [cmd, args];
1201
+ }
1202
+ async function ensurePullLogin(registry, reporter) {
1203
+ if (/^(localhost|127\.0\.0\.1)(:|$)/.test(registry)) return;
1204
+ if (await isLoggedIn(registry)) return;
1205
+ const token = envToken();
1206
+ if (token && registry === "ghcr.io") {
1207
+ reporter.step(`Logging in to ${registry} (token from the environment)`);
1208
+ await dockerLogin(registry, process.env.GHCR_USER || "token", token);
1209
+ return;
1210
+ }
1211
+ reporter.warn(`Not logged in to ${registry}; private images will be refused. Run: docker login ${registry}`);
1212
+ }
1213
+ async function composePs(config) {
1214
+ const [cmd, args] = await composeArgs(config);
1215
+ const res = await run(cmd, [...args, "ps", "--all", "--format", "json"], { cwd: config.deploy.dir });
1216
+ if (res.code !== 0) return [];
1217
+ const text = res.stdout.trim();
1218
+ if (!text) return [];
1219
+ try {
1220
+ const parsed = JSON.parse(text);
1221
+ return Array.isArray(parsed) ? parsed : [parsed];
1222
+ } catch {
1223
+ return text.split("\n").flatMap((line) => {
1224
+ try {
1225
+ return [JSON.parse(line)];
1226
+ } catch {
1227
+ return [];
1228
+ }
1229
+ });
1230
+ }
1231
+ }
1232
+ async function waitForServices(config, services, reporter, timeoutMs = 9e4) {
1233
+ const deadline = Date.now() + timeoutMs;
1234
+ reporter.step(`Waiting for ${services.join(", ")} to be up`);
1235
+ let last = "";
1236
+ for (; ; ) {
1237
+ const ps = await composePs(config);
1238
+ const states = services.map((svc) => {
1239
+ const entries = ps.filter((e) => e.Service === svc);
1240
+ if (entries.length === 0) return { svc, ok: false, bad: false, text: "not created" };
1241
+ const bad = entries.some((e) => e.State === "exited" || e.State === "dead" || e.State === "restarting");
1242
+ const ok = entries.every((e) => e.State === "running" && (!e.Health || e.Health === "healthy"));
1243
+ return { svc, ok, bad, text: entries.map((e) => e.Health ? `${e.State} (${e.Health})` : e.State).join(", ") };
1244
+ });
1245
+ const summary = states.map((s) => `${s.svc}: ${s.text}`).join(" \xB7 ");
1246
+ if (summary !== last) reporter.info(summary);
1247
+ last = summary;
1248
+ if (states.every((s) => s.ok)) return;
1249
+ if (Date.now() > deadline) {
1250
+ const failing = states.filter((s) => !s.ok).map((s) => `${s.svc} is ${s.text}`);
1251
+ throw new DeployerError(`Services did not come up within ${Math.round(timeoutMs / 1e3)} s: ${failing.join(", ")}`);
1252
+ }
1253
+ if (states.some((s) => s.bad) && Date.now() > deadline - timeoutMs + 2e4) {
1254
+ const failing = states.filter((s) => s.bad).map((s) => `${s.svc} is ${s.text}`);
1255
+ throw new DeployerError(`Service failed after deploy: ${failing.join(", ")}
1256
+ See: docker compose logs ${states.filter((s) => s.bad).map((s) => s.svc).join(" ")}`);
1257
+ }
1258
+ await sleep(2e3);
1259
+ }
1260
+ }
1261
+ async function healthcheck(config, reporter) {
1262
+ const hc = config.deploy.healthcheck;
1263
+ if (!hc) return;
1264
+ const timeout = (hc.timeout ?? 90) * 1e3;
1265
+ const deadline = Date.now() + timeout;
1266
+ reporter.step(`Health check ${hc.url}`);
1267
+ let lastError = "";
1268
+ while (Date.now() < deadline) {
1269
+ try {
1270
+ const res = await fetch(hc.url, { redirect: "manual", signal: AbortSignal.timeout(5e3) });
1271
+ const ok = hc.expectStatus ? res.status === hc.expectStatus : res.status < 400;
1272
+ if (ok) {
1273
+ reporter.success(`Health check passed (HTTP ${res.status})`);
1274
+ return;
1275
+ }
1276
+ lastError = `HTTP ${res.status}`;
1277
+ } catch (err) {
1278
+ lastError = err instanceof Error ? err.cause instanceof Error ? err.cause.message : err.message : String(err);
1279
+ }
1280
+ await sleep(2e3);
1281
+ }
1282
+ throw new DeployerError(`Health check ${hc.url} failed after ${Math.round(timeout / 1e3)} s (${lastError})`);
1283
+ }
1284
+ async function deploy(project2, targets, reporter, opts = {}) {
1285
+ const { config } = project2;
1286
+ if (targets.length === 0) throw new DeployerError("Nothing to deploy: no images selected");
1287
+ if (!project2.canDeploy) throw new DeployerError(`No compose file at ${project2.composePath}`);
1288
+ const started = Date.now();
1289
+ await assertDocker();
1290
+ const release = acquireLock(config);
1291
+ const env = new EnvFile(envPath(config));
1292
+ const before = env.vars;
1293
+ const { set, warnings, dragged } = planVars(config, targets, before);
1294
+ const vars = {};
1295
+ for (const s of set) vars[s.key] = { from: before.get(s.key) ?? null, to: s.value };
1296
+ const entry = {
1297
+ id: (/* @__PURE__ */ new Date()).toISOString().replace(/[-:.TZ]/g, ""),
1298
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1299
+ user: safeUser(),
1300
+ host: hostname(),
1301
+ images: Object.fromEntries(targets.map((t) => [t.image.key, t.tag])),
1302
+ vars,
1303
+ status: "failed",
1304
+ seconds: 0,
1305
+ ...opts.rollbackOf ? { rollbackOf: opts.rollbackOf } : {}
1306
+ };
1307
+ let envWritten = false;
1308
+ try {
1309
+ for (const w of warnings) reporter.warn(w);
1310
+ for (const registry of new Set(targets.map((t) => registryOf(t.image.repository)))) {
1311
+ await ensurePullLogin(registry, reporter);
1312
+ }
1313
+ for (const t of [...targets, ...dragged]) {
1314
+ const ref = `${t.image.repository}:${t.tag}`;
1315
+ reporter.step(`Pulling ${ref}`);
1316
+ const code = await stream("docker", ["pull", ref], { signal: opts.signal, onLine: (l) => reporter.output(l) });
1317
+ if (code !== 0) {
1318
+ if (dragged.includes(t)) {
1319
+ throw new DeployerError(
1320
+ `${t.image.key} has no ${t.image.tagVar} of its own, so it would follow ${t.image.tagVarFallback} to ${t.tag} \u2014 but ${ref} does not exist.
1321
+ Deploy ${t.image.key} at a tag it has, or set ${t.image.tagVar} in ${config.deploy.envFile}. Nothing was changed.`
1322
+ );
1323
+ }
1324
+ throw new DeployerError(`Could not pull ${ref} \u2014 does the tag exist, and is this server logged in? Nothing was changed.`);
1325
+ }
1326
+ }
1327
+ reporter.step(`Updating ${config.deploy.envFile}`);
1328
+ for (const s of set) {
1329
+ reporter.info(`${s.key}=${s.value} ${s.reason}`);
1330
+ env.set(s.key, s.value);
1331
+ }
1332
+ env.save();
1333
+ envWritten = true;
1334
+ await up(config, targets, reporter);
1335
+ const services = [...new Set(targets.map((t) => t.image.service).filter(Boolean))];
1336
+ if (config.deploy.waitForServices) await waitForServices(config, services, reporter);
1337
+ await healthcheck(config, reporter);
1338
+ if (!opts.skipHooks) await runHooks(config, reporter);
1339
+ entry.status = "success";
1340
+ reporter.success(`Deployed ${targets.map((t) => `${t.image.key}:${t.tag}`).join(", ")}`);
1341
+ return { entry };
1342
+ } catch (err) {
1343
+ entry.error = err instanceof Error ? err.message : String(err);
1344
+ const restorable = Object.values(vars).some((v) => v.from !== null && v.from !== v.to);
1345
+ if (envWritten && config.deploy.autoRollback && !restorable) {
1346
+ reporter.fail?.(entry.error);
1347
+ reporter.warn("Nothing to roll back to (no previous tags in .env) \u2014 the new containers were left as they are");
1348
+ }
1349
+ if (envWritten && config.deploy.autoRollback && restorable) {
1350
+ reporter.fail?.(entry.error);
1351
+ reporter.warn(`Deploy failed: ${entry.error.split("\n")[0]}`);
1352
+ reporter.step("Rolling back to the previous tags");
1353
+ try {
1354
+ const restore = new EnvFile(envPath(config));
1355
+ for (const [key2, v] of Object.entries(vars)) {
1356
+ if (v.from === null) restore.unset(key2);
1357
+ else restore.set(key2, v.from);
1358
+ reporter.info(v.from === null ? `unset ${key2}` : `${key2}=${v.from}`);
1359
+ }
1360
+ restore.save();
1361
+ await up(config, targets, reporter);
1362
+ entry.status = "rolled-back";
1363
+ reporter.warn("Rolled back \u2014 the previous version is running again");
1364
+ } catch (rollbackErr) {
1365
+ reporter.warn(`Rollback failed too: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
1366
+ }
1367
+ }
1368
+ throw err;
1369
+ } finally {
1370
+ entry.seconds = Math.round((Date.now() - started) / 1e3);
1371
+ if (!opts.noHistory && (envWritten || entry.status === "success")) appendHistory(config, entry);
1372
+ release();
1373
+ }
1374
+ }
1375
+ async function up(config, targets, reporter) {
1376
+ const [cmd, args] = await composeArgs(config);
1377
+ const upArgs = [...args, "up", "-d", "--pull", config.deploy.pull];
1378
+ if (config.deploy.up === "deployed") upArgs.push(...new Set(targets.map((t) => t.image.service)));
1379
+ reporter.step(`${cmd} ${upArgs.join(" ")}`);
1380
+ const tail = [];
1381
+ const code = await stream(cmd, upArgs, {
1382
+ cwd: config.deploy.dir,
1383
+ onLine: (l) => {
1384
+ reporter.output(l);
1385
+ tail.push(l.trim());
1386
+ if (tail.length > 4) tail.shift();
1387
+ }
1388
+ });
1389
+ if (code !== 0) throw new DeployerError(`docker compose up failed (exit ${code})
1390
+ ${tail.join("\n")}`);
1391
+ }
1392
+ async function runHooks(config, reporter) {
1393
+ for (const hook of config.deploy.postDeploy) {
1394
+ reporter.step(`Hook: ${hook.name}`);
1395
+ const code = await stream("sh", ["-c", hook.run], { cwd: config.deploy.dir, onLine: (l) => reporter.output(l) });
1396
+ if (code !== 0) throw new DeployerError(`Hook "${hook.name}" failed (exit ${code})`);
1397
+ }
1398
+ }
1399
+ function safeUser() {
1400
+ try {
1401
+ return userInfo().username;
1402
+ } catch {
1403
+ return process.env.USER ?? "unknown";
1404
+ }
1405
+ }
1406
+ function rollbackTargets(project2, history = readHistory(project2.config)) {
1407
+ const undone = new Set(history.filter((h) => h.status === "success" && h.rollbackOf).map((h) => h.rollbackOf));
1408
+ const last = history.find((h) => h.status === "success" && !h.rollbackOf && !undone.has(h.id));
1409
+ if (!last) return void 0;
1410
+ const targets = [];
1411
+ for (const img of deployableImages(project2.config)) {
1412
+ const v = last.vars[img.tagVar];
1413
+ if (v?.from && last.images[img.key]) targets.push({ image: img, tag: v.from });
1414
+ }
1415
+ return targets.length ? { targets, entry: last } : void 0;
1416
+ }
1417
+ function targetsFor(project2, tag, available, only) {
1418
+ const images = deployableImages(project2.config);
1419
+ if (only?.length) {
1420
+ const unknown = only.filter((k) => !images.some((i) => i.key === k));
1421
+ if (unknown.length) throw new DeployerError(`Not a deployable image: ${unknown.join(", ")} (have: ${images.map((i) => i.key).join(", ")})`);
1422
+ }
1423
+ return images.filter((img) => only?.length ? only.includes(img.key) : available ? available.includes(img.key) : true).map((image) => ({ image, tag }));
1424
+ }
1425
+ var sleep;
1426
+ var init_deploy = __esm({
1427
+ "src/core/deploy.ts"() {
1428
+ "use strict";
1429
+ init_errors();
1430
+ init_exec();
1431
+ init_config();
1432
+ init_docker();
1433
+ init_envfile();
1434
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1435
+ }
1436
+ });
1437
+
1438
+ // src/core/init.ts
1439
+ import { existsSync as existsSync5, readdirSync, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
1440
+ import { join as join6, relative } from "path";
1441
+ function findDockerfiles(root, dir = root, depth = 0, out2 = []) {
1442
+ if (depth > 3) return out2;
1443
+ let entries;
1444
+ try {
1445
+ entries = readdirSync(dir);
1446
+ } catch {
1447
+ return out2;
1448
+ }
1449
+ for (const name of entries) {
1450
+ const full = join6(dir, name);
1451
+ let st;
1452
+ try {
1453
+ st = statSync2(full);
1454
+ } catch {
1455
+ continue;
1456
+ }
1457
+ if (st.isDirectory()) {
1458
+ if (!SKIP.has(name) && !name.startsWith(".")) findDockerfiles(root, full, depth + 1, out2);
1459
+ } else if (name === "Dockerfile") {
1460
+ out2.push(relative(root, full));
1461
+ }
1462
+ }
1463
+ return out2;
1464
+ }
1465
+ function keyFor(context, repoName) {
1466
+ const base = context === "." ? repoName : context.split("/").pop();
1467
+ return base.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+|[-._]+$/g, "") || "app";
1468
+ }
1469
+ async function initConfig(cwd, opts = {}) {
1470
+ const root = await gitRoot(cwd) ?? cwd;
1471
+ const path = join6(root, CONFIG_FILE);
1472
+ if (existsSync5(path) && !opts.force) throw new DeployerError(`${path} already exists (use --force to overwrite)`);
1473
+ const repo = await originRepo(root);
1474
+ const repoName = repo?.split("/")[1] ?? root.split("/").pop() ?? "app";
1475
+ const images = {};
1476
+ for (const file of findDockerfiles(root)) {
1477
+ const context = file.includes("/") ? file.slice(0, file.lastIndexOf("/")) : ".";
1478
+ let key2 = keyFor(context, repoName);
1479
+ while (images[key2]) key2 = `${key2}-2`;
1480
+ images[key2] = { context, dockerfile: file };
1481
+ }
1482
+ if (Object.keys(images).length === 0) images.app = { context: ".", dockerfile: "Dockerfile" };
1483
+ const firstContext = Object.values(images)[0].context;
1484
+ const versionFile = [join6(firstContext, "package.json"), "package.json"].find((f) => existsSync5(join6(root, f)));
1485
+ const composeFile = ["docker-compose.prod.yml", "docker-compose.yml", "compose.yml", "compose.yaml", "deploy/docker-compose.yml"].find((f) => existsSync5(join6(root, f)));
1486
+ const config = {
1487
+ name: repoName,
1488
+ ...repo ? { repo } : {},
1489
+ ...versionFile ? { version: { file: versionFile.replace(/^\.\//, "") } } : {},
1490
+ platforms: ["linux/amd64"],
1491
+ pushLatest: true,
1492
+ images,
1493
+ deploy: {
1494
+ composeFile: "docker-compose.yml",
1495
+ envFile: ".env",
1496
+ pull: "never"
1497
+ },
1498
+ remote: {
1499
+ host: "your.server.example",
1500
+ user: "deploy",
1501
+ dir: `~/${repoName}`,
1502
+ ...composeFile ? { files: [{ from: composeFile, to: "docker-compose.yml" }] } : {}
1503
+ }
1504
+ };
1505
+ writeFileSync3(path, `${JSON.stringify(config, null, 2)}
1506
+ `);
1507
+ return { path, config };
1508
+ }
1509
+ var SKIP;
1510
+ var init_init = __esm({
1511
+ "src/core/init.ts"() {
1512
+ "use strict";
1513
+ init_errors();
1514
+ init_config();
1515
+ init_git();
1516
+ SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", ".next", "vendor", "target", ".venv", "__pycache__", ".claude"]);
1517
+ }
1518
+ });
1519
+
1520
+ // src/core/registry.ts
1521
+ async function githubToken() {
1522
+ return envToken() ?? (await dockerCredentials("ghcr.io"))?.secret ?? await ghToken();
1523
+ }
1524
+ async function listFromGitHub(repository, token, maxPages = 5) {
1525
+ const [, owner, ...rest] = repository.split("/");
1526
+ const pkg = encodeURIComponent(rest.join("/"));
1527
+ const headers = {
1528
+ Accept: "application/vnd.github+json",
1529
+ Authorization: `Bearer ${token}`,
1530
+ "X-GitHub-Api-Version": "2022-11-28",
1531
+ "User-Agent": UA
1532
+ };
1533
+ let lastStatus = 0;
1534
+ let lastBody = "";
1535
+ for (const scope of ["users", "orgs"]) {
1536
+ const out2 = [];
1537
+ let ok = true;
1538
+ for (let page = 1; page <= maxPages; page++) {
1539
+ const url = `https://api.github.com/${scope}/${owner}/packages/container/${pkg}/versions?per_page=100&page=${page}`;
1540
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(2e4) });
1541
+ if (!res.ok) {
1542
+ lastStatus = res.status;
1543
+ lastBody = await res.text().catch(() => "");
1544
+ ok = false;
1545
+ break;
1546
+ }
1547
+ const items = await res.json();
1548
+ for (const item of items) {
1549
+ const tags = item.metadata?.container?.tags ?? [];
1550
+ if (tags.length === 0) continue;
1551
+ const primary = tags.find((t) => t !== "latest") ?? tags[0];
1552
+ out2.push({
1553
+ tag: primary,
1554
+ aliases: tags.filter((t) => t !== primary),
1555
+ created: item.created_at ?? item.updated_at,
1556
+ digest: item.name
1557
+ });
1558
+ for (const extra of tags.filter((t) => t !== primary && t !== "latest")) {
1559
+ out2.push({ tag: extra, aliases: tags.filter((t) => t !== extra), created: item.created_at, digest: item.name });
1560
+ }
1561
+ }
1562
+ if (items.length < 100) break;
1563
+ }
1564
+ if (ok) return out2;
1565
+ if (lastStatus !== 404) break;
1566
+ }
1567
+ let message = "";
1568
+ try {
1569
+ message = JSON.parse(lastBody).message ?? "";
1570
+ } catch {
1571
+ }
1572
+ throw new GitHubApiError(lastStatus, message);
1573
+ }
1574
+ function registryHost(registry) {
1575
+ return registry === "docker.io" ? "registry-1.docker.io" : registry;
1576
+ }
1577
+ function registryBase(registry) {
1578
+ const host = registryHost(registry);
1579
+ const local = /^(localhost|127\.0\.0\.1)(:|$)/.test(host);
1580
+ return `${local ? "http" : "https"}://${host}`;
1581
+ }
1582
+ function repoPath(repository) {
1583
+ const registry = registryOf(repository);
1584
+ const path = repository.startsWith(`${registry}/`) ? repository.slice(registry.length + 1) : repository;
1585
+ return registry === "docker.io" && !path.includes("/") ? `library/${path}` : path;
1586
+ }
1587
+ async function bearerFor(repository, creds) {
1588
+ const registry = registryOf(repository);
1589
+ const probe = await fetch(`${registryBase(registry)}/v2/`, { signal: AbortSignal.timeout(15e3) });
1590
+ if (probe.status !== 401) return void 0;
1591
+ const header = probe.headers.get("www-authenticate") ?? "";
1592
+ if (!/^bearer/i.test(header)) return void 0;
1593
+ const params = Object.fromEntries([...header.matchAll(/(\w+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
1594
+ if (!params.realm) return void 0;
1595
+ const url = new URL(params.realm);
1596
+ if (params.service) url.searchParams.set("service", params.service);
1597
+ url.searchParams.set("scope", `repository:${repoPath(repository)}:pull`);
1598
+ const headers = { "User-Agent": UA };
1599
+ if (creds) headers.Authorization = `Basic ${Buffer.from(`${creds.username || "token"}:${creds.secret}`).toString("base64")}`;
1600
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(15e3) });
1601
+ if (!res.ok) throw new DeployerError(`${registry} refused a pull token (${res.status}) \u2014 check \`docker login ${registry}\``);
1602
+ const body = await res.json();
1603
+ return body.token ?? body.access_token;
1604
+ }
1605
+ async function listFromRegistry(repository) {
1606
+ const registry = registryOf(repository);
1607
+ let creds = await dockerCredentials(registry);
1608
+ const token = envToken();
1609
+ if (!creds && token && registry === "ghcr.io") creds = { username: "token", secret: token };
1610
+ const bearer = await bearerFor(repository, creds);
1611
+ const headers = { "User-Agent": UA };
1612
+ if (bearer) headers.Authorization = `Bearer ${bearer}`;
1613
+ else if (creds) headers.Authorization = `Basic ${Buffer.from(`${creds.username}:${creds.secret}`).toString("base64")}`;
1614
+ const tags = [];
1615
+ let next = `${registryBase(registry)}/v2/${repoPath(repository)}/tags/list?n=1000`;
1616
+ for (let guard = 0; next && guard < 20; guard++) {
1617
+ const res = await fetch(next, { headers, signal: AbortSignal.timeout(2e4) });
1618
+ if (res.status === 404) throw new DeployerError(`${repository} does not exist (or this login cannot see it)`);
1619
+ if (res.status === 401 || res.status === 403) throw new DeployerError(`Not allowed to list ${repository} (${res.status}) \u2014 run \`docker login ${registry}\``);
1620
+ if (!res.ok) throw new DeployerError(`${registry} returned ${res.status} listing ${repository}`);
1621
+ const body = await res.json();
1622
+ tags.push(...body.tags ?? []);
1623
+ const link = res.headers.get("link");
1624
+ const m = link ? /<([^>]+)>;\s*rel="next"/.exec(link) : null;
1625
+ next = m ? new URL(m[1], registryBase(registry)).toString() : void 0;
1626
+ }
1627
+ const base = `${registryBase(registry)}/v2/${repoPath(repository)}`;
1628
+ const wanted = [...tags].filter((t) => t !== "latest").sort(compareTagsDesc).slice(0, DATED_TAGS);
1629
+ const dates = /* @__PURE__ */ new Map();
1630
+ const digests = /* @__PURE__ */ new Map();
1631
+ await mapLimit(wanted.concat(tags.includes("latest") ? ["latest"] : []), 6, async (tag) => {
1632
+ const info = await imageInfo(base, tag, headers).catch(() => void 0);
1633
+ if (info?.created) dates.set(tag, info.created);
1634
+ if (info?.digest) digests.set(tag, info.digest);
1635
+ });
1636
+ const latestDigest = digests.get("latest");
1637
+ return tags.map((tag) => ({
1638
+ tag,
1639
+ aliases: latestDigest && digests.get(tag) === latestDigest && tag !== "latest" ? ["latest"] : [],
1640
+ created: dates.get(tag),
1641
+ digest: digests.get(tag)
1642
+ }));
1643
+ }
1644
+ async function imageInfo(base, tag, headers) {
1645
+ const get = (url, accept) => fetch(url, { headers: accept ? { ...headers, Accept: accept } : headers, signal: AbortSignal.timeout(15e3) });
1646
+ const res = await get(`${base}/manifests/${encodeURIComponent(tag)}`, MANIFEST_TYPES);
1647
+ if (!res.ok) return {};
1648
+ const digest = res.headers.get("docker-content-digest") ?? void 0;
1649
+ let manifest = await res.json();
1650
+ if (manifest.manifests?.length) {
1651
+ const child = manifest.manifests.find((m) => m.platform?.os !== "unknown") ?? manifest.manifests[0];
1652
+ const sub = await get(`${base}/manifests/${child.digest}`, MANIFEST_TYPES);
1653
+ if (!sub.ok) return { digest };
1654
+ manifest = await sub.json();
1655
+ }
1656
+ if (!manifest.config?.digest) return { digest };
1657
+ const blob = await get(`${base}/blobs/${manifest.config.digest}`);
1658
+ if (!blob.ok) return { digest };
1659
+ const cfg = await blob.json();
1660
+ return { digest, created: cfg.config?.Labels?.["org.opencontainers.image.created"] ?? cfg.created };
1661
+ }
1662
+ async function mapLimit(items, limit, fn) {
1663
+ let next = 0;
1664
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
1665
+ while (next < items.length) await fn(items[next++]);
1666
+ });
1667
+ await Promise.all(workers);
1668
+ }
1669
+ async function listImageVersions(repository) {
1670
+ if (registryOf(repository) === "ghcr.io") {
1671
+ const token = await githubToken();
1672
+ if (token) {
1673
+ try {
1674
+ return { versions: await listFromGitHub(repository, token), source: "github" };
1675
+ } catch (err) {
1676
+ if (!(err instanceof GitHubApiError)) throw err;
1677
+ try {
1678
+ return { versions: await listFromRegistry(repository), source: "registry" };
1679
+ } catch {
1680
+ const hint = err.status === 403 || err.status === 401 ? "\nThe token needs the read:packages scope (classic PAT, or `gh auth refresh -s read:packages`)." : err.status === 404 ? `
1681
+ No package ${repository} is visible to this token.` : "";
1682
+ throw new DeployerError(`${err.message}${hint}`);
1683
+ }
1684
+ }
1685
+ }
1686
+ }
1687
+ return { versions: await listFromRegistry(repository), source: "registry" };
1688
+ }
1689
+ function compareTagsDesc(a, b) {
1690
+ return b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" });
1691
+ }
1692
+ function sortReleases(releases) {
1693
+ return releases.sort((a, b) => {
1694
+ if (a.created && b.created && a.created !== b.created) return b.created.localeCompare(a.created);
1695
+ if (a.created && !b.created) return -1;
1696
+ if (!a.created && b.created) return 1;
1697
+ return compareTagsDesc(a.tag, b.tag);
1698
+ });
1699
+ }
1700
+ async function listReleases(images) {
1701
+ const results = await Promise.allSettled(images.map((img) => listImageVersions(img.repository)));
1702
+ const byTag = /* @__PURE__ */ new Map();
1703
+ const errors = [];
1704
+ const sources = /* @__PURE__ */ new Set();
1705
+ results.forEach((result, i) => {
1706
+ const img = images[i];
1707
+ if (result.status === "rejected") {
1708
+ errors.push({ image: img.key, message: result.reason instanceof Error ? result.reason.message : String(result.reason) });
1709
+ return;
1710
+ }
1711
+ sources.add(result.value.source);
1712
+ for (const v of result.value.versions) {
1713
+ if (v.tag === "latest") continue;
1714
+ const rel = byTag.get(v.tag) ?? { tag: v.tag, images: [], latest: false };
1715
+ if (!rel.images.includes(img.key)) rel.images.push(img.key);
1716
+ if (v.created && (!rel.created || v.created > rel.created)) rel.created = v.created;
1717
+ if (v.aliases.includes("latest")) rel.latest = true;
1718
+ byTag.set(v.tag, rel);
1719
+ }
1720
+ });
1721
+ if (errors.length === images.length && images.length > 0) {
1722
+ throw new DeployerError(errors.map((e) => `${e.image}: ${e.message}`).join("\n"));
1723
+ }
1724
+ const releases = sortReleases([...byTag.values()]);
1725
+ const newest = releases.find((r) => r.latest);
1726
+ for (const r of releases) r.latest = r === newest;
1727
+ return {
1728
+ releases,
1729
+ errors,
1730
+ source: sources.size > 1 ? "mixed" : sources.values().next().value ?? "registry"
1731
+ };
1732
+ }
1733
+ function latestRelease(list2) {
1734
+ return list2.releases.find((r) => r.latest) ?? list2.releases[0];
1735
+ }
1736
+ var UA, GitHubApiError, DATED_TAGS, MANIFEST_TYPES;
1737
+ var init_registry = __esm({
1738
+ "src/core/registry.ts"() {
1739
+ "use strict";
1740
+ init_errors();
1741
+ init_docker();
1742
+ UA = "deployer-cli";
1743
+ GitHubApiError = class extends Error {
1744
+ constructor(status, detail) {
1745
+ super(`GitHub Packages API returned ${status}${detail ? `: ${detail}` : ""}`);
1746
+ this.status = status;
1747
+ }
1748
+ status;
1749
+ };
1750
+ DATED_TAGS = 40;
1751
+ MANIFEST_TYPES = [
1752
+ "application/vnd.oci.image.index.v1+json",
1753
+ "application/vnd.docker.distribution.manifest.list.v2+json",
1754
+ "application/vnd.oci.image.manifest.v1+json",
1755
+ "application/vnd.docker.distribution.manifest.v2+json"
1756
+ ].join(", ");
1757
+ }
1758
+ });
1759
+
1760
+ // src/core/remote.ts
1761
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
1762
+ import { tmpdir as tmpdir2 } from "os";
1763
+ import { basename, join as join7, posix } from "path";
1764
+ function target(remote) {
1765
+ return remote.user ? `${remote.user}@${remote.host}` : remote.host;
1766
+ }
1767
+ function commonOpts(remote) {
1768
+ const opts = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15"];
1769
+ if (remote.identityFile) opts.push("-i", remote.identityFile, "-o", "IdentitiesOnly=yes");
1770
+ return [...opts, ...remote.sshArgs ?? []];
1771
+ }
1772
+ function sshArgs(remote, command) {
1773
+ const args = commonOpts(remote);
1774
+ if (remote.port) args.push("-p", String(remote.port));
1775
+ return [...args, target(remote), command];
1776
+ }
1777
+ function remoteCommand(remote, deployerArgs) {
1778
+ return `cd ${remoteDirExpr(remote.dir)} && ${remote.command} ${deployerArgs.map(shellQuote).join(" ")}`;
1779
+ }
1780
+ function sshCommandLine(remote, deployerArgs) {
1781
+ return ["ssh", ...sshArgs(remote, remoteCommand(remote, deployerArgs))].map(shellQuote).join(" ");
1782
+ }
1783
+ function needRemote(config) {
1784
+ if (!config.remote) throw new DeployerError(`No "remote" section in ${config.file} \u2014 add host and dir to drive the server from here`);
1785
+ return config.remote;
1786
+ }
1787
+ async function remoteRun(config, deployerArgs, reporter, signal) {
1788
+ const remote = needRemote(config);
1789
+ const command = remoteCommand(remote, deployerArgs);
1790
+ reporter.step(`ssh ${target(remote)}: ${remote.command} ${deployerArgs.join(" ")}`);
1791
+ const code = await stream("ssh", sshArgs(remote, command), { signal, onLine: (l) => reporter.output(l) });
1792
+ if (code === 255) throw new DeployerError(`ssh to ${target(remote)} failed \u2014 check host, user and identityFile (BatchMode: no password prompts)`);
1793
+ if (code === 127) throw new DeployerError(`"${remote.command}" is not installed on ${remote.host}: npm install -g @trojeancedric/deployer`);
1794
+ if (code !== 0) throw new DeployerError(`Remote deploy failed (exit ${code})`);
1795
+ }
1796
+ async function syncToRemote(project2, reporter, signal) {
1797
+ const { config } = project2;
1798
+ const remote = needRemote(config);
1799
+ const tmp = mkdtempSync2(join7(process.env.TMPDIR ?? tmpdir2(), "deployer-sync-"));
1800
+ try {
1801
+ const raw = { ...config.raw };
1802
+ if (!raw.imagePrefix && !raw.repo && project2.repo) raw.repo = project2.repo;
1803
+ if (!raw.imagePrefix) raw.imagePrefix = project2.imagePrefix || void 0;
1804
+ delete raw.deploy?.dir;
1805
+ const cfgCopy = join7(tmp, CONFIG_FILE);
1806
+ writeFileSync4(cfgCopy, `${JSON.stringify(raw, null, 2)}
1807
+ `);
1808
+ const files = [{ local: cfgCopy, remote: CONFIG_FILE }];
1809
+ const root = project2.gitRoot ?? config.root;
1810
+ for (const f of remote.files ?? []) {
1811
+ files.push({ local: join7(root, f.from), remote: f.to ?? basename(f.from) });
1812
+ }
1813
+ reporter.step(`Creating ${remote.dir} on ${remote.host}`);
1814
+ const mk = await stream("ssh", sshArgs(remote, `mkdir -p ${remoteDirExpr(remote.dir)}`), { signal, onLine: (l) => reporter.output(l) });
1815
+ if (mk !== 0) throw new DeployerError(`ssh to ${target(remote)} failed (exit ${mk})`);
1816
+ for (const f of files) {
1817
+ const dest = posix.join(remote.dir, f.remote);
1818
+ reporter.step(`Copying ${f.local === cfgCopy ? CONFIG_FILE : f.local} \u2192 ${remote.host}:${dest}`);
1819
+ const args = commonOpts(remote);
1820
+ if (remote.port) args.push("-P", String(remote.port));
1821
+ args.push(f.local, `${target(remote)}:${dest}`);
1822
+ const code = await stream("scp", args, { signal, onLine: (l) => reporter.output(l) });
1823
+ if (code !== 0) throw new DeployerError(`scp of ${f.local} failed (exit ${code})`);
1824
+ }
1825
+ reporter.success(`Synced ${files.length} file${files.length > 1 ? "s" : ""} to ${remote.host}:${remote.dir}`);
1826
+ } finally {
1827
+ rmSync3(tmp, { recursive: true, force: true });
1828
+ }
1829
+ }
1830
+ function remoteDirExpr(dir) {
1831
+ return dir.startsWith("~/") ? `"$HOME"/${shellQuote(dir.slice(2))}` : shellQuote(dir);
1832
+ }
1833
+ async function remoteJson(config, deployerArgs) {
1834
+ const remote = needRemote(config);
1835
+ const res = await run("ssh", sshArgs(remote, remoteCommand(remote, deployerArgs)));
1836
+ if (res.code === 255) throw new DeployerError(`ssh to ${target(remote)} failed
1837
+ ${res.stderr.trim().split("\n").pop() ?? ""}`);
1838
+ if (res.code === 127) throw new DeployerError(`"${remote.command}" is not installed on ${remote.host}
1839
+ npm install -g @trojeancedric/deployer`);
1840
+ if (res.code !== 0) throw new DeployerError(`${remote.command} ${deployerArgs.join(" ")} failed on ${remote.host}
1841
+ ${res.stderr.trim().split("\n").slice(-3).join(" ")}`);
1842
+ try {
1843
+ return JSON.parse(res.stdout);
1844
+ } catch {
1845
+ throw new DeployerError(`Unexpected output from ${remote.host}: ${res.stdout.slice(0, 200)}`);
1846
+ }
1847
+ }
1848
+ function remoteLabel(config) {
1849
+ const remote = needRemote(config);
1850
+ return `${target(remote)}:${remote.dir}`;
1851
+ }
1852
+ var init_remote = __esm({
1853
+ "src/core/remote.ts"() {
1854
+ "use strict";
1855
+ init_errors();
1856
+ init_exec();
1857
+ init_config();
1858
+ }
1859
+ });
1860
+
1861
+ // src/tui/theme.ts
1862
+ function spinnerFrame(tick) {
1863
+ return SPINNER_FRAMES[tick % SPINNER_FRAMES.length];
1864
+ }
1865
+ function statusTone(status) {
1866
+ return STATUS_TONES[String(status ?? "").toLowerCase()] ?? "muted";
1867
+ }
1868
+ function toneColor(tone) {
1869
+ switch (tone) {
1870
+ case "success":
1871
+ return palette.success;
1872
+ case "danger":
1873
+ return palette.danger;
1874
+ case "warning":
1875
+ return palette.warning;
1876
+ case "info":
1877
+ return palette.info;
1878
+ default:
1879
+ return palette.muted;
1880
+ }
1881
+ }
1882
+ function statusBadge(status, tick = 0) {
1883
+ const label = String(status ?? "").trim() || "unknown";
1884
+ const lower = label.toLowerCase();
1885
+ const color = toneColor(statusTone(lower));
1886
+ const glyph = ACTIVE_STATUSES.has(lower) ? spinnerFrame(tick) : statusTone(lower) === "muted" ? "\u25CB" : "\u25CF";
1887
+ return fg(color, `${glyph} ${lower}`);
1888
+ }
1889
+ function relativeTime(value) {
1890
+ if (!value) return "\u2014";
1891
+ const date = new Date(String(value));
1892
+ const ms = date.getTime();
1893
+ if (Number.isNaN(ms)) return "\u2014";
1894
+ const diff = Date.now() - ms;
1895
+ const future = diff < 0;
1896
+ const s = Math.abs(diff) / 1e3;
1897
+ const fmt = (n, unit) => {
1898
+ const v = Math.floor(n);
1899
+ return future ? `in ${v}${unit}` : `${v}${unit} ago`;
1900
+ };
1901
+ if (s < 45) return future ? "in a moment" : "just now";
1902
+ if (s < 3600) return fmt(s / 60, "m");
1903
+ if (s < 86400) return fmt(s / 3600, "h");
1904
+ if (s < 86400 * 30) return fmt(s / 86400, "d");
1905
+ return date.toISOString().slice(0, 10);
1906
+ }
1907
+ function formatClock(ms) {
1908
+ const total = Math.max(0, Math.floor(ms / 1e3));
1909
+ const m = Math.floor(total / 60);
1910
+ const s = total % 60;
1911
+ return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
1912
+ }
1913
+ var palette, brandGradient, c, SPINNER_FRAMES, STATUS_TONES, ACTIVE_STATUSES;
1914
+ var init_theme = __esm({
1915
+ "src/tui/theme.ts"() {
1916
+ "use strict";
1917
+ init_ansi();
1918
+ palette = {
1919
+ brand: [16, 185, 129],
1920
+ brandSoft: [110, 231, 183],
1921
+ accent: [56, 189, 248],
1922
+ text: [229, 231, 235],
1923
+ muted: [148, 163, 184],
1924
+ faint: [100, 116, 139],
1925
+ border: [71, 85, 105],
1926
+ selection: [6, 78, 59],
1927
+ hover: [30, 41, 59],
1928
+ success: [74, 222, 128],
1929
+ warning: [250, 204, 21],
1930
+ danger: [248, 113, 113],
1931
+ info: [96, 165, 250]
1932
+ };
1933
+ brandGradient = [
1934
+ [163, 230, 53],
1935
+ [52, 211, 153],
1936
+ [16, 185, 129],
1937
+ [34, 211, 238],
1938
+ [59, 130, 246]
1939
+ ];
1940
+ c = {
1941
+ brand: (t) => fg(palette.brand, t),
1942
+ brandSoft: (t) => fg(palette.brandSoft, t),
1943
+ accent: (t) => fg(palette.accent, t),
1944
+ text: (t) => fg(palette.text, t),
1945
+ muted: (t) => fg(palette.muted, t),
1946
+ faint: (t) => fg(palette.faint, t),
1947
+ border: (t) => fg(palette.border, t),
1948
+ success: (t) => fg(palette.success, t),
1949
+ warning: (t) => fg(palette.warning, t),
1950
+ danger: (t) => fg(palette.danger, t),
1951
+ info: (t) => fg(palette.info, t),
1952
+ bold,
1953
+ dim
1954
+ };
1955
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1956
+ STATUS_TONES = {
1957
+ passed: "success",
1958
+ success: "success",
1959
+ ok: "success",
1960
+ up: "success",
1961
+ healthy: "success",
1962
+ active: "success",
1963
+ enabled: "success",
1964
+ completed: "success",
1965
+ failed: "danger",
1966
+ error: "danger",
1967
+ down: "danger",
1968
+ unhealthy: "danger",
1969
+ blocked: "danger",
1970
+ timeout: "danger",
1971
+ running: "info",
1972
+ queued: "info",
1973
+ pending: "info",
1974
+ in_progress: "info",
1975
+ paused: "warning",
1976
+ degraded: "warning",
1977
+ cancelled: "warning",
1978
+ canceled: "warning",
1979
+ disabled: "muted",
1980
+ inactive: "muted",
1981
+ idle: "muted"
1982
+ };
1983
+ ACTIVE_STATUSES = /* @__PURE__ */ new Set(["running", "queued", "pending", "in_progress"]);
1984
+ }
1985
+ });
1986
+
1987
+ // src/cli/commands.ts
1988
+ var commands_exports = {};
1989
+ __export(commands_exports, {
1990
+ cmdBuild: () => cmdBuild,
1991
+ cmdDeploy: () => cmdDeploy,
1992
+ cmdHistory: () => cmdHistory,
1993
+ cmdInit: () => cmdInit,
1994
+ cmdRollback: () => cmdRollback,
1995
+ cmdStatus: () => cmdStatus,
1996
+ cmdSync: () => cmdSync,
1997
+ cmdVersions: () => cmdVersions
1998
+ });
1999
+ import { createInterface } from "readline";
2000
+ async function project(flags) {
2001
+ return openProject(loadConfig(typeof flags.config === "string" ? flags.config : void 0));
2002
+ }
2003
+ function out(data) {
2004
+ process.stdout.write(`${typeof data === "string" ? data : JSON.stringify(data, null, 2)}
2005
+ `);
2006
+ }
2007
+ async function confirm(question, yes) {
2008
+ if (yes) return;
2009
+ if (!process.stdin.isTTY) throw new DeployerError("Refusing to deploy without confirmation: pass --yes");
2010
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
2011
+ const answer = await new Promise((res) => rl.question(`${question} [y/N] `, res));
2012
+ rl.close();
2013
+ if (!/^y(es)?$/i.test(answer.trim())) throw new DeployerError("Cancelled", 130);
2014
+ }
2015
+ function withSignal(fn) {
2016
+ const ctl = new AbortController();
2017
+ let interrupts = 0;
2018
+ const onInt = () => {
2019
+ interrupts++;
2020
+ if (interrupts > 1) process.exit(130);
2021
+ process.stderr.write("\nStopping\u2026 (ctrl+c again to force)\n");
2022
+ ctl.abort();
2023
+ };
2024
+ process.on("SIGINT", onInt);
2025
+ return fn(ctl.signal).finally(() => process.off("SIGINT", onInt));
2026
+ }
2027
+ function describeTargets(targets, p) {
2028
+ const state = new Map(currentState(p.config).map((s) => [s.image.key, s.tag]));
2029
+ return targets.map((t) => ` ${t.image.key.padEnd(16)} ${state.get(t.image.key) ?? "(unset)"} \u2192 ${t.tag}`).join("\n");
2030
+ }
2031
+ async function cmdBuild({ positionals, flags }) {
2032
+ const p = await project(flags);
2033
+ const opts = {
2034
+ images: positionals,
2035
+ tag: typeof flags.tag === "string" ? flags.tag : void 0,
2036
+ ref: typeof flags.ref === "string" ? flags.ref : void 0,
2037
+ platforms: list(flags.platforms),
2038
+ pushLatest: typeof flags.latest === "boolean" ? flags.latest : void 0,
2039
+ runChecks: flags.checks === true,
2040
+ dryRun: flags["dry-run"] === true
2041
+ };
2042
+ if (flags.plan) {
2043
+ const plan = await planBuild(p, opts);
2044
+ out({ tag: plan.tag, sha: plan.sha, ref: plan.ref, images: plan.tags });
2045
+ return;
2046
+ }
2047
+ const result = await withSignal((signal) => build(p, consoleReporter, { ...opts, signal }));
2048
+ if (opts.dryRun) return;
2049
+ out(result.tag);
2050
+ const keys = result.images.filter((i) => i.service && i.versioned).map((i) => i.key);
2051
+ if (keys.length === 0) return;
2052
+ const deployArgs = ["deploy", result.tag, "--images", keys.join(","), "--yes"];
2053
+ if (flags.deploy) {
2054
+ await withSignal((signal) => remoteRun(p.config, deployArgs, consoleReporter, signal));
2055
+ return;
2056
+ }
2057
+ printHint("\nRoll it out on the server:");
2058
+ printHint(p.config.remote ? ` ${sshCommandLine(p.config.remote, deployArgs)}` : ` ${rolloutCommand(result)}`);
2059
+ if (p.config.remote) printHint(" (or next time: deployer build --deploy)");
2060
+ }
2061
+ async function cmdVersions({ flags }) {
2062
+ const p = await project(flags);
2063
+ const images = deployableImages(p.config);
2064
+ const listing = await listReleases(images);
2065
+ for (const e of listing.errors) consoleReporter.warn(`${e.image}: ${e.message}`);
2066
+ const limit = typeof flags.limit === "string" ? Number(flags.limit) : 20;
2067
+ const releases = listing.releases.slice(0, limit);
2068
+ if (flags.json) {
2069
+ out(releases);
2070
+ return;
2071
+ }
2072
+ const running = new Set(p.canDeploy ? currentState(p.config).map((s) => s.tag) : []);
2073
+ const latest = latestRelease(listing)?.tag;
2074
+ if (releases.length === 0) {
2075
+ consoleReporter.info("No published versions yet. Build one with `deployer build`.");
2076
+ return;
2077
+ }
2078
+ const width = Math.max(...releases.map((x) => x.tag.length), 3);
2079
+ for (const rel of releases) {
2080
+ const marks = [rel.tag === latest ? "latest" : "", running.has(rel.tag) ? "running" : ""].filter(Boolean).join(", ");
2081
+ const imgs = rel.images.length === images.length ? "all images" : rel.images.join(" ");
2082
+ out(`${rel.tag.padEnd(width)} ${(rel.created ? relativeTime(rel.created) : "").padEnd(10)} ${imgs}${marks ? ` (${marks})` : ""}`);
2083
+ }
2084
+ }
2085
+ async function cmdDeploy({ positionals, flags }) {
2086
+ const p = await project(flags);
2087
+ const only = list(flags.images);
2088
+ let tag = positionals[0] ?? "latest";
2089
+ let available;
2090
+ if (tag === "latest" || !only) {
2091
+ const listing = await listReleases(deployableImages(p.config)).catch((err) => {
2092
+ if (tag === "latest") throw err;
2093
+ consoleReporter.warn(`Could not list published versions (${err instanceof Error ? err.message.split("\n")[0] : err}); deploying every image at ${tag}`);
2094
+ return void 0;
2095
+ });
2096
+ if (listing) {
2097
+ const rel = tag === "latest" ? latestRelease(listing) : listing.releases.find((x) => x.tag === tag);
2098
+ if (!rel) throw new DeployerError(tag === "latest" ? "No published versions found" : `No image is published under tag ${tag}`);
2099
+ tag = rel.tag;
2100
+ available = rel.images;
2101
+ }
2102
+ }
2103
+ const targets = targetsFor(p, tag, available, only);
2104
+ if (targets.length === 0) throw new DeployerError(`None of the selected images exist at ${tag}`);
2105
+ consoleReporter.step(`Deploy ${tag} to ${p.config.deploy.dir}`);
2106
+ process.stderr.write(`${describeTargets(targets, p)}
2107
+ `);
2108
+ await confirm("Proceed?", flags.yes === true);
2109
+ await withSignal((signal) => deploy(p, targets, consoleReporter, { signal }));
2110
+ }
2111
+ async function cmdRollback({ flags }) {
2112
+ const p = await project(flags);
2113
+ const rb = rollbackTargets(p);
2114
+ if (!rb) throw new DeployerError("Nothing to roll back to: no successful deploy with a previous version in the history");
2115
+ consoleReporter.step(`Roll back the deploy of ${rb.entry.at} (${Object.entries(rb.entry.images).map(([k, v]) => `${k}:${v}`).join(", ")})`);
2116
+ process.stderr.write(`${describeTargets(rb.targets, p)}
2117
+ `);
2118
+ await confirm("Roll back?", flags.yes === true);
2119
+ await withSignal((signal) => deploy(p, rb.targets, consoleReporter, { signal, rollbackOf: rb.entry.id }));
2120
+ }
2121
+ async function cmdStatus({ flags }) {
2122
+ const p = await project(flags);
2123
+ if (!p.canDeploy) throw new DeployerError(`No compose file at ${p.composePath} \u2014 status is for the server's deploy directory`);
2124
+ const state = currentState(p.config);
2125
+ const last = readHistory(p.config)[0];
2126
+ if (flags.json) {
2127
+ out({ images: state.map((s) => ({ image: s.image.key, service: s.image.service, tag: s.tag ?? null, source: s.source })), last: last ?? null });
2128
+ return;
2129
+ }
2130
+ for (const s of state) {
2131
+ out(`${s.image.key.padEnd(16)} ${(s.tag ?? "(unset)").padEnd(28)} ${s.source === "fallback" ? `via ${s.image.tagVarFallback}` : ""}`);
2132
+ }
2133
+ if (last) printHint(`
2134
+ Last deploy: ${last.status} ${relativeTime(last.at)} by ${last.user} (${Object.entries(last.images).map(([k, v]) => `${k}:${v}`).join(", ")})`);
2135
+ }
2136
+ async function cmdHistory({ flags }) {
2137
+ const p = await project(flags);
2138
+ const history = readHistory(p.config);
2139
+ if (flags.json) return out(history);
2140
+ if (history.length === 0) return consoleReporter.info("No deploys recorded yet.");
2141
+ for (const h of history) {
2142
+ out(`${h.at.slice(0, 19).replace("T", " ")} ${h.status.padEnd(11)} ${Object.entries(h.images).map(([k, v]) => `${k}:${v}`).join(", ")} ${h.user}`);
2143
+ }
2144
+ }
2145
+ async function cmdSync({ flags }) {
2146
+ const p = await project(flags);
2147
+ await withSignal((signal) => syncToRemote(p, consoleReporter, signal));
2148
+ }
2149
+ async function cmdInit({ flags }) {
2150
+ const { path, config } = await initConfig(process.cwd(), { force: flags.force === true });
2151
+ consoleReporter.success(`Wrote ${path}`);
2152
+ consoleReporter.info(`Images: ${Object.entries(config.images).map(([k, v]) => `${k} (${v.dockerfile})`).join(", ")}`);
2153
+ printHint('Edit "remote" (your server) and check the image list, then run: deployer');
2154
+ }
2155
+ var init_commands = __esm({
2156
+ "src/cli/commands.ts"() {
2157
+ "use strict";
2158
+ init_build();
2159
+ init_config();
2160
+ init_deploy();
2161
+ init_init();
2162
+ init_project();
2163
+ init_registry();
2164
+ init_remote();
2165
+ init_theme();
2166
+ init_errors();
2167
+ init_reporter();
2168
+ init_args();
2169
+ }
2170
+ });
2171
+
2172
+ // src/tui/input.ts
2173
+ function parseInput(data) {
2174
+ const events = [];
2175
+ let i = 0;
2176
+ while (i < data.length) {
2177
+ const rest = data.slice(i);
2178
+ if (rest.startsWith(PASTE_START)) {
2179
+ const end = rest.indexOf(PASTE_END);
2180
+ const text = end === -1 ? rest.slice(PASTE_START.length) : rest.slice(PASTE_START.length, end);
2181
+ events.push({ type: "paste", text });
2182
+ i += end === -1 ? rest.length : end + PASTE_END.length;
2183
+ continue;
2184
+ }
2185
+ const mouse2 = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])/.exec(rest);
2186
+ if (mouse2) {
2187
+ const button = Number(mouse2[1]);
2188
+ const x = Number(mouse2[2]) - 1;
2189
+ const y = Number(mouse2[3]) - 1;
2190
+ let action;
2191
+ if (button & 64) action = button & 1 ? "wheeldown" : "wheelup";
2192
+ else if (button & 32) action = "move";
2193
+ else action = mouse2[4] === "M" ? "press" : "release";
2194
+ if (action !== "press" || (button & 3) === 0) events.push({ type: "mouse", action, x, y });
2195
+ i += mouse2[0].length;
2196
+ continue;
2197
+ }
2198
+ const csi = /^\x1b\[(\d*)(?:;(\d+))?([A-Za-z~])/.exec(rest);
2199
+ if (csi) {
2200
+ const [, param, mod, final] = csi;
2201
+ const modifier = mod ? Number(mod) - 1 : 0;
2202
+ const flags = { shift: (modifier & 1) !== 0, ctrl: (modifier & 4) !== 0 };
2203
+ if (final === "~" && TILDE_KEYS[param]) events.push(key(TILDE_KEYS[param], flags));
2204
+ else if (final === "Z") events.push(key("tab", { shift: true }));
2205
+ else if (CSI_KEYS[final]) events.push(key(CSI_KEYS[final], flags));
2206
+ i += csi[0].length;
2207
+ continue;
2208
+ }
2209
+ const ss3 = /^\x1bO([A-DHF])/.exec(rest);
2210
+ if (ss3) {
2211
+ events.push(key(CSI_KEYS[ss3[1]]));
2212
+ i += 3;
2213
+ continue;
2214
+ }
2215
+ const ch = String.fromCodePoint(rest.codePointAt(0) ?? 0);
2216
+ i += ch.length;
2217
+ switch (ch) {
2218
+ case "\x1B":
2219
+ events.push(key("escape"));
2220
+ break;
2221
+ case "\r":
2222
+ case "\n":
2223
+ events.push(key("enter"));
2224
+ break;
2225
+ case " ":
2226
+ events.push(key("tab"));
2227
+ break;
2228
+ case "\x7F":
2229
+ case "\b":
2230
+ events.push(key("backspace"));
2231
+ break;
2232
+ case " ":
2233
+ events.push(key("space", { char: " " }));
2234
+ break;
2235
+ default: {
2236
+ const code = ch.codePointAt(0) ?? 0;
2237
+ if (code < 32) {
2238
+ events.push(key("char", { ctrl: true, char: String.fromCharCode(code + 96) }));
2239
+ } else {
2240
+ events.push(key("char", { char: ch }));
2241
+ }
2242
+ }
2243
+ }
2244
+ }
2245
+ return events;
2246
+ }
2247
+ var key, CSI_KEYS, TILDE_KEYS, PASTE_START, PASTE_END;
2248
+ var init_input = __esm({
2249
+ "src/tui/input.ts"() {
2250
+ "use strict";
2251
+ key = (name, extra = {}) => ({
2252
+ type: "key",
2253
+ name,
2254
+ ctrl: false,
2255
+ shift: false,
2256
+ ...extra
2257
+ });
2258
+ CSI_KEYS = {
2259
+ A: "up",
2260
+ B: "down",
2261
+ C: "right",
2262
+ D: "left",
2263
+ H: "home",
2264
+ F: "end"
2265
+ };
2266
+ TILDE_KEYS = {
2267
+ "1": "home",
2268
+ "7": "home",
2269
+ "4": "end",
2270
+ "8": "end",
2271
+ "3": "delete",
2272
+ "5": "pageup",
2273
+ "6": "pagedown"
2274
+ };
2275
+ PASTE_START = "\x1B[200~";
2276
+ PASTE_END = "\x1B[201~";
2277
+ }
2278
+ });
2279
+
2280
+ // src/tui/app.ts
2281
+ var Frame, App;
2282
+ var init_app = __esm({
2283
+ "src/tui/app.ts"() {
2284
+ "use strict";
2285
+ init_ansi();
2286
+ init_input();
2287
+ init_theme();
2288
+ Frame = class {
2289
+ constructor(width, height, offset = 0, sharedHits) {
2290
+ this.width = width;
2291
+ this.height = height;
2292
+ this.offset = offset;
2293
+ this.sharedHits = sharedHits;
2294
+ }
2295
+ width;
2296
+ height;
2297
+ offset;
2298
+ sharedHits;
2299
+ lines = [];
2300
+ hits = [];
2301
+ /** Row index the next `line()` will write to. */
2302
+ get y() {
2303
+ return this.lines.length;
2304
+ }
2305
+ get remaining() {
2306
+ return Math.max(0, this.height - this.lines.length);
2307
+ }
2308
+ line(text = "", hit) {
2309
+ if (this.lines.length >= this.height) return this;
2310
+ if (hit) this.hit(this.lines.length, 0, this.width, hit);
2311
+ this.lines.push(fit(text, this.width));
2312
+ return this;
2313
+ }
2314
+ blank(count = 1) {
2315
+ for (let i = 0; i < count; i++) this.line();
2316
+ return this;
2317
+ }
2318
+ /** Register a clickable span on row `y` (frame-relative), columns [x0, x1). */
2319
+ hit(y, x0, x1, handlers) {
2320
+ const entry = { y: y + this.offset, x0, x1, ...handlers };
2321
+ (this.sharedHits ?? this.hits).push(entry);
2322
+ }
2323
+ /**
2324
+ * Write a row made of segments, each optionally clickable. Returns the column
2325
+ * where every segment started, for callers that need it.
2326
+ */
2327
+ segments(parts) {
2328
+ if (this.lines.length >= this.height) return this;
2329
+ let x = 0;
2330
+ let out2 = "";
2331
+ for (const part of parts) {
2332
+ const w = visibleWidth(part.text);
2333
+ if (part.onClick || part.onHover) this.hit(this.lines.length, x, x + w, part);
2334
+ out2 += part.text;
2335
+ x += w;
2336
+ }
2337
+ this.lines.push(fit(out2, this.width));
2338
+ return this;
2339
+ }
2340
+ fill() {
2341
+ while (this.lines.length < this.height) this.lines.push(" ".repeat(this.width));
2342
+ return this;
2343
+ }
2344
+ };
2345
+ App = class {
2346
+ constructor(ctx) {
2347
+ this.ctx = ctx;
2348
+ }
2349
+ ctx;
2350
+ tick = 0;
2351
+ stack = [];
2352
+ prevLines = [];
2353
+ hits = [];
2354
+ hovered = null;
2355
+ toastState = null;
2356
+ renderQueued = false;
2357
+ timer = null;
2358
+ running = false;
2359
+ resolveExit = null;
2360
+ out = process.stdout;
2361
+ inp = process.stdin;
2362
+ get width() {
2363
+ return this.out.columns || 80;
2364
+ }
2365
+ get height() {
2366
+ return this.out.rows || 24;
2367
+ }
2368
+ get current() {
2369
+ return this.stack[this.stack.length - 1];
2370
+ }
2371
+ get depth() {
2372
+ return this.stack.length;
2373
+ }
2374
+ // ── navigation ────────────────────────────────────────────────────────────
2375
+ push(next) {
2376
+ this.stack.push(next);
2377
+ next.mount?.();
2378
+ this.invalidate();
2379
+ }
2380
+ pop() {
2381
+ this.popTo(this.stack.length - 1);
2382
+ }
2383
+ /** Leave the current screen unless it is busy with something that must finish. */
2384
+ requestPop() {
2385
+ const blocked = this.current?.blocksExit?.();
2386
+ if (blocked) {
2387
+ this.toast(blocked, "warning");
2388
+ return;
2389
+ }
2390
+ this.pop();
2391
+ }
2392
+ /** Quit unless any screen on the stack is busy. */
2393
+ requestExit() {
2394
+ for (const s of this.stack) {
2395
+ const blocked = s.blocksExit?.();
2396
+ if (blocked) {
2397
+ this.toast(blocked, "warning");
2398
+ return;
2399
+ }
2400
+ }
2401
+ this.exit();
2402
+ }
2403
+ /** Pop until `depth` screens remain. */
2404
+ popTo(depth) {
2405
+ if (this.stack.length <= Math.max(1, depth)) return;
2406
+ while (this.stack.length > Math.max(1, depth)) this.stack.pop()?.unmount?.();
2407
+ this.current?.resume?.();
2408
+ this.invalidate();
2409
+ }
2410
+ replace(next) {
2411
+ this.stack.pop()?.unmount?.();
2412
+ this.push(next);
2413
+ }
2414
+ toast(message, tone = "info", ms = 3500) {
2415
+ this.toastState = { message, tone, until: Date.now() + ms };
2416
+ this.invalidate();
2417
+ }
2418
+ invalidate() {
2419
+ if (this.renderQueued || !this.running) return;
2420
+ this.renderQueued = true;
2421
+ setImmediate(() => {
2422
+ this.renderQueued = false;
2423
+ this.render();
2424
+ });
2425
+ }
2426
+ // ── lifecycle ─────────────────────────────────────────────────────────────
2427
+ run(root) {
2428
+ this.running = true;
2429
+ this.inp.setRawMode?.(true);
2430
+ this.inp.setEncoding("utf8");
2431
+ this.inp.resume();
2432
+ this.inp.on("data", this.onData);
2433
+ this.out.on("resize", this.onResize);
2434
+ process.on("exit", this.restoreTerminal);
2435
+ this.out.write(
2436
+ screen.enterAlt + cursor.hide + screen.clear + mouse.enable + "\x1B[?2004h\x1B[?7l"
2437
+ // no autowrap: a full-width last row must never scroll the screen
2438
+ );
2439
+ this.timer = setInterval(() => {
2440
+ this.tick++;
2441
+ const toastExpired = this.toastState && Date.now() > this.toastState.until;
2442
+ if (toastExpired) this.toastState = null;
2443
+ if (toastExpired || this.current?.animated?.()) this.render();
2444
+ }, 80);
2445
+ this.push(root);
2446
+ this.render();
2447
+ return new Promise((resolve2) => {
2448
+ this.resolveExit = resolve2;
2449
+ });
2450
+ }
2451
+ exit() {
2452
+ if (!this.running) return;
2453
+ this.running = false;
2454
+ while (this.stack.length) this.stack.pop()?.unmount?.();
2455
+ if (this.timer) clearInterval(this.timer);
2456
+ this.inp.off("data", this.onData);
2457
+ this.out.off("resize", this.onResize);
2458
+ this.restoreTerminal();
2459
+ process.off("exit", this.restoreTerminal);
2460
+ this.inp.setRawMode?.(false);
2461
+ this.inp.pause();
2462
+ this.resolveExit?.();
2463
+ }
2464
+ restoreTerminal = () => {
2465
+ this.out.write(mouse.disable + "\x1B[?2004l\x1B[?7h" + cursor.show + screen.leaveAlt);
2466
+ };
2467
+ onResize = () => {
2468
+ this.prevLines = [];
2469
+ this.out.write(screen.clear);
2470
+ this.render();
2471
+ };
2472
+ // ── input ─────────────────────────────────────────────────────────────────
2473
+ onData = (data) => {
2474
+ for (const event of parseInput(data)) {
2475
+ if (!this.running) return;
2476
+ try {
2477
+ this.dispatch(event);
2478
+ } catch (err) {
2479
+ this.toast(err instanceof Error ? err.message : String(err), "danger", 6e3);
2480
+ }
2481
+ }
2482
+ };
2483
+ dispatch(event) {
2484
+ const screen2 = this.current;
2485
+ if (!screen2) return;
2486
+ if (event.type === "paste") {
2487
+ screen2.onPaste?.(event.text);
2488
+ this.invalidate();
2489
+ return;
2490
+ }
2491
+ if (event.type === "mouse") {
2492
+ this.onMouse(event.action, event.x, event.y);
2493
+ return;
2494
+ }
2495
+ if (event.ctrl && event.char === "c") {
2496
+ if (screen2.onInterrupt?.()) {
2497
+ this.invalidate();
2498
+ return;
2499
+ }
2500
+ this.requestExit();
2501
+ return;
2502
+ }
2503
+ if (screen2.onKey?.(event)) {
2504
+ this.invalidate();
2505
+ return;
2506
+ }
2507
+ const typing = screen2.capturesText?.() ?? false;
2508
+ if (event.name === "escape" || event.name === "backspace" && !typing) {
2509
+ this.requestPop();
2510
+ return;
2511
+ }
2512
+ if (!typing && event.name === "char" && event.char === "q") {
2513
+ this.requestExit();
2514
+ }
2515
+ }
2516
+ onMouse(action, x, y) {
2517
+ if (action === "wheelup" || action === "wheeldown") {
2518
+ this.current?.onWheel?.(action === "wheelup" ? -1 : 1);
2519
+ this.invalidate();
2520
+ return;
2521
+ }
2522
+ const hit = this.hits.find((h) => h.y === y && x >= h.x0 && x < h.x1) ?? null;
2523
+ if (action === "move") {
2524
+ if (hit !== this.hovered) {
2525
+ this.hovered = hit;
2526
+ hit?.onHover?.();
2527
+ this.invalidate();
2528
+ }
2529
+ return;
2530
+ }
2531
+ if (action === "press" && hit?.onClick) {
2532
+ hit.onClick();
2533
+ this.invalidate();
2534
+ }
2535
+ }
2536
+ // ── rendering ─────────────────────────────────────────────────────────────
2537
+ render() {
2538
+ if (!this.running) return;
2539
+ const screen2 = this.current;
2540
+ if (!screen2) return;
2541
+ const { width, height } = this;
2542
+ const hits = [];
2543
+ const lines = [];
2544
+ if (!screen2.fullBleed) lines.push(...this.renderHeader(width, hits));
2545
+ const footerHeight = 2;
2546
+ const body = new Frame(width, Math.max(1, height - lines.length - footerHeight), lines.length, hits);
2547
+ screen2.render(body);
2548
+ body.fill();
2549
+ lines.push(...body.lines);
2550
+ lines.push(...this.renderFooter(screen2, width, height - 1, hits));
2551
+ this.hits = hits;
2552
+ if (this.hovered) {
2553
+ const prev = this.hovered;
2554
+ this.hovered = hits.find((h) => h.y === prev.y && h.x0 === prev.x0 && h.x1 === prev.x1) ?? null;
2555
+ }
2556
+ let changes = "";
2557
+ for (let i = 0; i < height; i++) {
2558
+ const line = lines[i] ?? "";
2559
+ if (this.prevLines[i] === line) continue;
2560
+ changes += cursor.to(i + 1, 1) + line + "\x1B[0m\x1B[K";
2561
+ }
2562
+ this.prevLines = lines.slice(0, height);
2563
+ if (changes) this.out.write(screen.beginSync + changes + screen.endSync);
2564
+ }
2565
+ renderHeader(width, hits) {
2566
+ const parts = [
2567
+ { text: " " + gradient("\u25B2 DEPLOYER", brandGradient), depth: 1 }
2568
+ ];
2569
+ this.stack.slice(1).forEach((s, i) => {
2570
+ parts.push({ text: c.faint(" \u203A ") });
2571
+ const isLast = i === this.stack.length - 2;
2572
+ parts.push({ text: isLast ? c.bold(c.text(s.title)) : c.muted(s.title), depth: i + 2 });
2573
+ });
2574
+ let x = 0;
2575
+ let left = "";
2576
+ for (const part of parts) {
2577
+ const w = visibleWidth(part.text);
2578
+ if (part.depth !== void 0 && part.depth < this.stack.length) {
2579
+ const depth = part.depth;
2580
+ hits.push({ y: 0, x0: x, x1: x + w, onClick: () => this.popTo(depth) });
2581
+ }
2582
+ left += part.text;
2583
+ x += w;
2584
+ }
2585
+ const right = c.faint(this.ctx.location()) + " ";
2586
+ const gap = width - visibleWidth(left) - visibleWidth(right);
2587
+ const header = gap > 2 ? left + " ".repeat(gap) + right : left;
2588
+ return [fit(header, width), c.border("\u2500".repeat(width))];
2589
+ }
2590
+ renderFooter(screen2, width, y, hits) {
2591
+ const hints = [...screen2.hints?.() ?? []];
2592
+ if (this.stack.length > 1) hints.push({ key: "esc", label: "back", action: () => this.requestPop() });
2593
+ hints.push({ key: "q", label: "quit", action: () => this.requestExit() });
2594
+ let right = c.faint(`v${this.ctx.version} `);
2595
+ if (this.toastState) {
2596
+ right = fg(toneColor(this.toastState.tone), `\u25CF ${this.toastState.message}`) + " ";
2597
+ }
2598
+ const hintWidth = (h) => visibleWidth(`${h.key} ${h.label}`) + 3;
2599
+ if (this.toastState) {
2600
+ const room = width - visibleWidth(right) - 2;
2601
+ while (hints.length > 2 && hints.reduce((sum, h) => sum + hintWidth(h), 1) > room) {
2602
+ hints.splice(hints.length - 3, 1);
2603
+ }
2604
+ }
2605
+ let x = 1;
2606
+ let left = " ";
2607
+ for (const hint of hints) {
2608
+ const text = `${c.accent(hint.key)} ${c.muted(hint.label)}`;
2609
+ const w = visibleWidth(text);
2610
+ if (hint.action) hits.push({ y, x0: x, x1: x + w, onClick: hint.action });
2611
+ left += text + " ";
2612
+ x += w + 3;
2613
+ }
2614
+ const gap = width - visibleWidth(left) - visibleWidth(right);
2615
+ const footer = gap >= 1 ? left + " ".repeat(gap) + right : left;
2616
+ return [fg(palette.border, "\u2500".repeat(width)), fit(footer, width)];
2617
+ }
2618
+ };
2619
+ }
2620
+ });
2621
+
2622
+ // src/tui/logo.ts
2623
+ function word(text) {
2624
+ const rows = ["", "", "", "", "", ""];
2625
+ for (const letter of text) {
2626
+ const glyph = GLYPHS[letter];
2627
+ for (let r = 0; r < 6; r++) rows[r] += glyph[r];
2628
+ }
2629
+ return rows;
2630
+ }
2631
+ function revealRow(row, progress, rowIndex) {
2632
+ if (progress >= 1) return gradient(row, brandGradient);
2633
+ const chars = [...row];
2634
+ const span = Math.max(1, chars.length - 1);
2635
+ const edge = progress * (chars.length + 12) - rowIndex * 2;
2636
+ return chars.map((ch, i) => {
2637
+ if (ch === " " || i > edge) return " ";
2638
+ const scaled = i / span * (brandGradient.length - 1);
2639
+ const idx = Math.min(brandGradient.length - 2, Math.floor(scaled));
2640
+ const base = lerp(brandGradient[idx], brandGradient[idx + 1], scaled - idx);
2641
+ const glow = Math.max(0, 1 - (edge - i) / 6);
2642
+ return fg(lerp(base, WHITE, glow * 0.85), ch);
2643
+ }).join("");
2644
+ }
2645
+ function renderLogo(width, progress = 1) {
2646
+ if (width >= LOGO_WIDTH) return DEPLOYER.map((row, i) => revealRow(row, progress, i));
2647
+ return [revealRow("\u25B2 D E P L O Y E R", progress, 0)];
2648
+ }
2649
+ var GLYPHS, DEPLOYER, LOGO_WIDTH, WHITE;
2650
+ var init_logo = __esm({
2651
+ "src/tui/logo.ts"() {
2652
+ "use strict";
2653
+ init_ansi();
2654
+ init_theme();
2655
+ GLYPHS = {
2656
+ D: ["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "\u2588\u2588\u2551 \u2588\u2588\u2551", "\u2588\u2588\u2551 \u2588\u2588\u2551", "\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", "\u255A\u2550\u2550\u2550\u2550\u2550\u255D "],
2657
+ E: ["\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557", "\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D", "\u2588\u2588\u2588\u2588\u2588\u2557 ", "\u2588\u2588\u2554\u2550\u2550\u255D ", "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557", "\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],
2658
+ P: ["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", "\u2588\u2588\u2554\u2550\u2550\u2550\u255D ", "\u2588\u2588\u2551 ", "\u255A\u2550\u255D "],
2659
+ L: ["\u2588\u2588\u2557 ", "\u2588\u2588\u2551 ", "\u2588\u2588\u2551 ", "\u2588\u2588\u2551 ", "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557", "\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],
2660
+ O: [" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557", "\u2588\u2588\u2551 \u2588\u2588\u2551", "\u2588\u2588\u2551 \u2588\u2588\u2551", "\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", " \u255A\u2550\u2550\u2550\u2550\u2550\u255D "],
2661
+ Y: ["\u2588\u2588\u2557 \u2588\u2588\u2557", "\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D", " \u255A\u2588\u2588\u2588\u2588\u2554\u255D ", " \u255A\u2588\u2588\u2554\u255D ", " \u2588\u2588\u2551 ", " \u255A\u2550\u255D "],
2662
+ R: ["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", "\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "\u2588\u2588\u2551 \u2588\u2588\u2551", "\u255A\u2550\u255D \u255A\u2550\u255D"]
2663
+ };
2664
+ DEPLOYER = word("DEPLOYER");
2665
+ LOGO_WIDTH = visibleWidth(DEPLOYER[0]);
2666
+ WHITE = [255, 255, 255];
2667
+ }
2668
+ });
2669
+
2670
+ // src/tui/widgets.ts
2671
+ function describeError(err) {
2672
+ if (err instanceof Error) {
2673
+ const [first, ...rest] = err.message.split("\n");
2674
+ return { title: first || "Something went wrong", detail: rest.join(" ").trim(), auth: false };
2675
+ }
2676
+ return { title: "Something went wrong", detail: String(err), auth: false };
2677
+ }
2678
+ function recoveryKey(event, resource, actions) {
2679
+ if (resource.state !== "error" || event.name !== "char" || event.ctrl) return false;
2680
+ if (event.char === "r") {
2681
+ actions.retry();
2682
+ return true;
2683
+ }
2684
+ if (event.char === "s" && actions.signIn && describeError(resource.error).auth) {
2685
+ actions.signIn();
2686
+ return true;
2687
+ }
2688
+ return false;
2689
+ }
2690
+ function recoveryHints(resource, actions) {
2691
+ if (resource.state !== "error") return null;
2692
+ const hints = [{ key: "r", label: "retry", action: actions.retry }];
2693
+ if (actions.signIn && describeError(resource.error).auth) hints.unshift({ key: "s", label: "sign in", action: actions.signIn });
2694
+ return hints;
2695
+ }
2696
+ function renderResource(frame, resource, app, label, actions) {
2697
+ if (resource.state === "ready") return true;
2698
+ if (resource.state === "loading") {
2699
+ frame.blank();
2700
+ frame.line(`${INDENT}${c.brandSoft(spinnerFrame(app.tick))} ${c.muted(label)}`);
2701
+ return false;
2702
+ }
2703
+ const info = describeError(resource.error);
2704
+ frame.blank();
2705
+ frame.line(`${INDENT}${c.danger("\u2717")} ${bold(c.danger(info.title))}`);
2706
+ for (const line of wrap(info.detail, Math.max(20, frame.width - 6))) {
2707
+ if (line) frame.line(`${INDENT} ${c.muted(line)}`);
2708
+ }
2709
+ frame.blank();
2710
+ const buttons = new ButtonBar([
2711
+ ...info.auth && actions.signIn ? [{ label: "Sign in", action: actions.signIn }] : [],
2712
+ { label: "Retry", action: actions.retry },
2713
+ { label: "Back", action: () => app.pop() }
2714
+ ]);
2715
+ buttons.render(frame, INDENT, false);
2716
+ return false;
2717
+ }
2718
+ function box(lines, width, title, color = palette.border) {
2719
+ const inner = Math.max(4, width - 4);
2720
+ const border = (s) => fg(color, s);
2721
+ let top = "\u256D" + "\u2500".repeat(width - 2) + "\u256E";
2722
+ if (title) {
2723
+ const label = ` ${truncate(title, width - 6)} `;
2724
+ top = border("\u256D\u2500") + label + border("\u2500".repeat(Math.max(0, width - 3 - visibleWidth(label))) + "\u256E");
2725
+ } else {
2726
+ top = border(top);
2727
+ }
2728
+ return [
2729
+ top,
2730
+ ...lines.map((line) => `${border("\u2502")} ${fit(line, inner)} ${border("\u2502")}`),
2731
+ border("\u2570" + "\u2500".repeat(width - 2) + "\u256F")
2732
+ ];
2733
+ }
2734
+ function keyValues(pairs, keyWidth = 12) {
2735
+ return pairs.map(([k, v]) => `${c.muted(fit(k, keyWidth))} ${v}`);
2736
+ }
2737
+ function sectionTitle(text, width) {
2738
+ const label = ` ${text} `;
2739
+ return `${INDENT}${c.bold(c.text(text))} ${c.border("\u2500".repeat(Math.max(0, width - visibleWidth(label) - INDENT.length - 1)))}`;
2740
+ }
2741
+ var INDENT, Resource, ListView, Menu, ButtonBar, TextInput;
2742
+ var init_widgets = __esm({
2743
+ "src/tui/widgets.ts"() {
2744
+ "use strict";
2745
+ init_ansi();
2746
+ init_theme();
2747
+ INDENT = " ";
2748
+ Resource = class {
2749
+ constructor(app, loader) {
2750
+ this.app = app;
2751
+ this.loader = loader;
2752
+ }
2753
+ app;
2754
+ loader;
2755
+ state = "loading";
2756
+ data;
2757
+ error;
2758
+ /** True while a background refresh runs over already-shown data. */
2759
+ refreshing = false;
2760
+ seq = 0;
2761
+ async load(options = {}) {
2762
+ const seq = ++this.seq;
2763
+ if (options.silent && this.state === "ready") this.refreshing = true;
2764
+ else this.state = "loading";
2765
+ this.app.invalidate();
2766
+ try {
2767
+ const data = await this.loader();
2768
+ if (seq !== this.seq) return;
2769
+ this.data = data;
2770
+ this.state = "ready";
2771
+ } catch (err) {
2772
+ if (seq !== this.seq) return;
2773
+ this.error = err;
2774
+ this.state = "error";
2775
+ } finally {
2776
+ if (seq === this.seq) this.refreshing = false;
2777
+ this.app.invalidate();
2778
+ }
2779
+ }
2780
+ /** Discard any in-flight load so its result is ignored. */
2781
+ cancel() {
2782
+ this.seq++;
2783
+ }
2784
+ };
2785
+ ListView = class {
2786
+ constructor(opts) {
2787
+ this.opts = opts;
2788
+ }
2789
+ opts;
2790
+ items = [];
2791
+ selected = 0;
2792
+ offset = 0;
2793
+ filter = "";
2794
+ filtering = false;
2795
+ lastViewport = 10;
2796
+ setItems(items) {
2797
+ const current = this.current;
2798
+ this.items = items;
2799
+ const index = current ? this.visible.indexOf(current) : -1;
2800
+ this.selected = index >= 0 ? index : Math.min(this.selected, Math.max(0, this.visible.length - 1));
2801
+ }
2802
+ get visible() {
2803
+ if (!this.filter) return this.items;
2804
+ const needle = this.filter.toLowerCase();
2805
+ return this.items.filter((item) => this.opts.searchText(item).toLowerCase().includes(needle));
2806
+ }
2807
+ get current() {
2808
+ return this.visible[this.selected];
2809
+ }
2810
+ move(delta) {
2811
+ const count = this.visible.length;
2812
+ if (count === 0) return;
2813
+ this.selected = Math.min(count - 1, Math.max(0, this.selected + delta));
2814
+ if (this.selected === count - 1) this.opts.onReachEnd?.();
2815
+ }
2816
+ onWheel(direction) {
2817
+ this.move(direction * 3);
2818
+ }
2819
+ onKey(event) {
2820
+ if (this.filtering) {
2821
+ if (event.name === "escape") {
2822
+ this.filtering = false;
2823
+ this.filter = "";
2824
+ this.selected = 0;
2825
+ return true;
2826
+ }
2827
+ if (event.name === "enter") {
2828
+ this.filtering = false;
2829
+ return true;
2830
+ }
2831
+ if (event.name === "backspace") {
2832
+ this.filter = this.filter.slice(0, -1);
2833
+ this.selected = 0;
2834
+ return true;
2835
+ }
2836
+ if ((event.name === "char" || event.name === "space") && event.char && !event.ctrl) {
2837
+ this.filter += event.char;
2838
+ this.selected = 0;
2839
+ return true;
2840
+ }
2841
+ }
2842
+ switch (event.name) {
2843
+ case "up":
2844
+ this.move(-1);
2845
+ return true;
2846
+ case "down":
2847
+ this.move(1);
2848
+ return true;
2849
+ case "pageup":
2850
+ this.move(-this.lastViewport);
2851
+ return true;
2852
+ case "pagedown":
2853
+ this.move(this.lastViewport);
2854
+ return true;
2855
+ case "home":
2856
+ this.move(-Infinity);
2857
+ return true;
2858
+ case "end":
2859
+ this.move(Infinity);
2860
+ return true;
2861
+ case "enter": {
2862
+ const item = this.current;
2863
+ if (item !== void 0) this.opts.onSelect(item);
2864
+ return true;
2865
+ }
2866
+ case "escape":
2867
+ if (this.filter) {
2868
+ this.filter = "";
2869
+ this.selected = 0;
2870
+ return true;
2871
+ }
2872
+ return false;
2873
+ case "char":
2874
+ if (event.ctrl && event.char === "p") {
2875
+ this.move(-1);
2876
+ return true;
2877
+ }
2878
+ if (event.ctrl && event.char === "n") {
2879
+ this.move(1);
2880
+ return true;
2881
+ }
2882
+ if (event.char === "k") {
2883
+ this.move(-1);
2884
+ return true;
2885
+ }
2886
+ if (event.char === "j") {
2887
+ this.move(1);
2888
+ return true;
2889
+ }
2890
+ if (event.char === "/") {
2891
+ this.filtering = true;
2892
+ return true;
2893
+ }
2894
+ return false;
2895
+ default:
2896
+ return false;
2897
+ }
2898
+ }
2899
+ render(frame, height = frame.remaining, tick = 0) {
2900
+ const { columns } = this.opts;
2901
+ const visible = this.visible;
2902
+ const width = frame.width - INDENT.length - 2;
2903
+ const fixed = columns.reduce((sum, col) => sum + (col.width === "flex" ? 0 : col.width), 0);
2904
+ const gaps = (columns.length - 1) * 2;
2905
+ const flex = Math.max(8, width - fixed - gaps);
2906
+ const widths = columns.map((col) => col.width === "flex" ? flex : col.width);
2907
+ const row = (cells) => cells.map((cell, i) => fit(cell, widths[i], columns[i].align ?? "left")).join(" ");
2908
+ const showFilter = this.filtering || this.filter !== "";
2909
+ if (showFilter) {
2910
+ const caret = this.filtering ? inverse(" ") : "";
2911
+ frame.line(`${INDENT}${c.accent("/")} ${c.text(this.filter)}${caret} ${c.faint(`${visible.length} of ${this.items.length}`)}`);
2912
+ }
2913
+ frame.line(`${INDENT} ${c.faint(bold(row(columns.map((col) => col.header))))}`);
2914
+ const viewport = Math.max(1, height - (showFilter ? 1 : 0) - 2);
2915
+ this.lastViewport = viewport;
2916
+ if (visible.length === 0) {
2917
+ frame.line(`${INDENT} ${c.muted(this.filter ? `No matches for \u201C${this.filter}\u201D` : this.opts.emptyText ?? "Nothing here yet.")}`);
2918
+ return;
2919
+ }
2920
+ this.selected = Math.min(this.selected, visible.length - 1);
2921
+ if (this.selected < this.offset) this.offset = this.selected;
2922
+ if (this.selected >= this.offset + viewport) this.offset = this.selected - viewport + 1;
2923
+ this.offset = Math.max(0, Math.min(this.offset, Math.max(0, visible.length - viewport)));
2924
+ const slice = visible.slice(this.offset, this.offset + viewport);
2925
+ slice.forEach((item, i) => {
2926
+ const index = this.offset + i;
2927
+ const isSelected = index === this.selected;
2928
+ const text = row(columns.map((col) => col.render(item, tick)));
2929
+ const pointer = isSelected ? c.brand("\u276F ") : " ";
2930
+ const line = isSelected ? `${INDENT}${pointer}${bg(palette.selection, fit(text, frame.width - INDENT.length - 2))}` : `${INDENT}${pointer}${text}`;
2931
+ frame.line(line, {
2932
+ onHover: () => {
2933
+ this.selected = index;
2934
+ },
2935
+ onClick: () => {
2936
+ this.selected = index;
2937
+ this.opts.onSelect(item);
2938
+ }
2939
+ });
2940
+ });
2941
+ const above = this.offset;
2942
+ const below = visible.length - this.offset - slice.length;
2943
+ if (above > 0 || below > 0) {
2944
+ const parts = [above > 0 ? `\u2191 ${above} more` : "", below > 0 ? `\u2193 ${below} more` : ""].filter(Boolean);
2945
+ frame.line(`${INDENT} ${c.faint(parts.join(" "))}`);
2946
+ }
2947
+ }
2948
+ };
2949
+ Menu = class {
2950
+ constructor(items) {
2951
+ this.items = items;
2952
+ }
2953
+ items;
2954
+ selected = 0;
2955
+ /** Called when the pointer hovers an item, so a parent can move focus here. */
2956
+ onFocus;
2957
+ move(delta) {
2958
+ const n = this.items.length;
2959
+ if (n === 0) return;
2960
+ let next = this.selected;
2961
+ for (let step = 0; step < n; step++) {
2962
+ next = (next + Math.sign(delta) + n) % n;
2963
+ if (!this.items[next].disabled && !this.items[next].heading) break;
2964
+ }
2965
+ this.selected = next;
2966
+ }
2967
+ onKey(event) {
2968
+ if (event.name === "up" || event.name === "tab" && event.shift || event.name === "char" && event.char === "k") {
2969
+ this.move(-1);
2970
+ return true;
2971
+ }
2972
+ if (event.name === "down" || event.name === "tab" || event.name === "char" && event.char === "j") {
2973
+ this.move(1);
2974
+ return true;
2975
+ }
2976
+ if (event.name === "enter" || event.name === "space") {
2977
+ const item = this.items[this.selected];
2978
+ if (item && !item.disabled && !item.heading) item.action();
2979
+ return true;
2980
+ }
2981
+ if (event.name === "char" && event.char && !event.ctrl) {
2982
+ const index = this.items.findIndex((item) => item.shortcut === event.char && !item.disabled && !item.heading);
2983
+ if (index >= 0) {
2984
+ this.selected = index;
2985
+ this.items[index].action();
2986
+ return true;
2987
+ }
2988
+ }
2989
+ return false;
2990
+ }
2991
+ render(frame, indent = INDENT, labelWidth = 18, active = true) {
2992
+ const here = this.items[this.selected];
2993
+ if (here && (here.heading || here.disabled)) this.move(1);
2994
+ this.items.forEach((item, index) => {
2995
+ if (item.heading) {
2996
+ if (index > 0) frame.blank();
2997
+ frame.line(sectionTitle(item.heading, frame.width));
2998
+ frame.blank();
2999
+ return;
3000
+ }
3001
+ const isSelected = active && index === this.selected;
3002
+ const shortcut = item.shortcut ? c.faint(`${item.shortcut} `) : " ";
3003
+ const icon = item.icon ? `${item.icon} ` : "";
3004
+ const labelText = fit(`${icon}${item.label}`, labelWidth);
3005
+ const label = item.disabled ? c.faint(labelText) : isSelected ? bold(c.text(labelText)) : c.text(labelText);
3006
+ const description = item.description ? isSelected ? c.muted(item.description) : c.faint(item.description) : "";
3007
+ const content = `${shortcut}${label} ${description}`;
3008
+ const pointer = isSelected ? c.brand("\u276F ") : " ";
3009
+ const body = isSelected ? bg(palette.selection, fit(` ${content}`, frame.width - visibleWidth(indent) - 4)) : ` ${content}`;
3010
+ frame.line(`${indent}${pointer}${body}`, {
3011
+ onHover: () => {
3012
+ if (item.disabled) return;
3013
+ this.selected = index;
3014
+ this.onFocus?.();
3015
+ },
3016
+ onClick: () => {
3017
+ if (item.disabled) return;
3018
+ this.selected = index;
3019
+ item.action();
3020
+ }
3021
+ });
3022
+ });
3023
+ }
3024
+ };
3025
+ ButtonBar = class {
3026
+ constructor(buttons) {
3027
+ this.buttons = buttons;
3028
+ }
3029
+ buttons;
3030
+ focused = 0;
3031
+ onKey(event) {
3032
+ const n = this.buttons.length;
3033
+ if (n === 0) return false;
3034
+ if (event.name === "left" || event.name === "tab" && event.shift || event.name === "char" && event.char === "h") {
3035
+ this.focused = (this.focused - 1 + n) % n;
3036
+ return true;
3037
+ }
3038
+ if (event.name === "right" || event.name === "tab" || event.name === "char" && event.char === "l") {
3039
+ this.focused = (this.focused + 1) % n;
3040
+ return true;
3041
+ }
3042
+ if (event.name === "enter" || event.name === "space") {
3043
+ this.buttons[this.focused]?.action();
3044
+ return true;
3045
+ }
3046
+ return false;
3047
+ }
3048
+ render(frame, indent = INDENT, active = true) {
3049
+ const parts = [{ text: indent }];
3050
+ this.buttons.forEach((button, index) => {
3051
+ const focused = active && index === this.focused;
3052
+ const color = button.tone === "danger" ? palette.danger : button.tone === "primary" ? palette.brand : palette.border;
3053
+ const label = ` ${button.label} `;
3054
+ const text = focused ? bg(color, bold(fg([255, 255, 255], label))) : fg(button.tone === "danger" ? palette.danger : button.tone === "primary" ? palette.brandSoft : palette.muted, `[${button.label}]`);
3055
+ parts.push({
3056
+ text,
3057
+ onHover: () => {
3058
+ this.focused = index;
3059
+ },
3060
+ onClick: () => {
3061
+ this.focused = index;
3062
+ button.action();
3063
+ }
3064
+ });
3065
+ parts.push({ text: " " });
3066
+ });
3067
+ frame.segments(parts);
3068
+ }
3069
+ };
3070
+ TextInput = class {
3071
+ constructor(initial = "", options = {}) {
3072
+ this.options = options;
3073
+ this.value = initial;
3074
+ this.cursorPos = initial.length;
3075
+ }
3076
+ options;
3077
+ value;
3078
+ cursorPos;
3079
+ insert(text) {
3080
+ const clean = text.replace(/[\r\n\t]/g, "");
3081
+ this.value = this.value.slice(0, this.cursorPos) + clean + this.value.slice(this.cursorPos);
3082
+ this.cursorPos += clean.length;
3083
+ }
3084
+ onKey(event) {
3085
+ switch (event.name) {
3086
+ case "left":
3087
+ this.cursorPos = Math.max(0, this.cursorPos - 1);
3088
+ return true;
3089
+ case "right":
3090
+ this.cursorPos = Math.min(this.value.length, this.cursorPos + 1);
3091
+ return true;
3092
+ case "home":
3093
+ this.cursorPos = 0;
3094
+ return true;
3095
+ case "end":
3096
+ this.cursorPos = this.value.length;
3097
+ return true;
3098
+ case "backspace":
3099
+ if (this.cursorPos > 0) {
3100
+ this.value = this.value.slice(0, this.cursorPos - 1) + this.value.slice(this.cursorPos);
3101
+ this.cursorPos--;
3102
+ }
3103
+ return true;
3104
+ case "delete":
3105
+ this.value = this.value.slice(0, this.cursorPos) + this.value.slice(this.cursorPos + 1);
3106
+ return true;
3107
+ case "space":
3108
+ this.insert(" ");
3109
+ return true;
3110
+ case "char":
3111
+ if (event.ctrl) {
3112
+ if (event.char === "u") {
3113
+ this.value = "";
3114
+ this.cursorPos = 0;
3115
+ return true;
3116
+ }
3117
+ if (event.char === "a") {
3118
+ this.cursorPos = 0;
3119
+ return true;
3120
+ }
3121
+ if (event.char === "e") {
3122
+ this.cursorPos = this.value.length;
3123
+ return true;
3124
+ }
3125
+ return false;
3126
+ }
3127
+ if (event.char) this.insert(event.char);
3128
+ return true;
3129
+ default:
3130
+ return false;
3131
+ }
3132
+ }
3133
+ render(width, focused = true) {
3134
+ const shown = this.options.mask ? "\u2022".repeat(this.value.length) : this.value;
3135
+ if (!shown && this.options.placeholder) {
3136
+ return (focused ? inverse(" ") : "") + c.faint(this.options.placeholder);
3137
+ }
3138
+ const start = Math.max(0, this.cursorPos - width + 2);
3139
+ const view = shown.slice(start, start + width - 1);
3140
+ const at = this.cursorPos - start;
3141
+ if (!focused) return c.text(view);
3142
+ const before = view.slice(0, at);
3143
+ const under = view[at] ?? " ";
3144
+ const after = view.slice(at + 1);
3145
+ return c.text(before) + inverse(under) + c.text(after);
3146
+ }
3147
+ };
3148
+ }
3149
+ });
3150
+
3151
+ // src/tui/backend.ts
3152
+ function backendFor(project2) {
3153
+ if (project2.canDeploy) return localBackend(project2);
3154
+ if (project2.config.remote) return remoteBackend(project2);
3155
+ return void 0;
3156
+ }
3157
+ function localBackend(project2) {
3158
+ const { config } = project2;
3159
+ return {
3160
+ kind: "local",
3161
+ label: config.deploy.dir,
3162
+ async state() {
3163
+ return new Map(currentState(config).map((s) => [s.image.key, s.tag]));
3164
+ },
3165
+ async history() {
3166
+ return readHistory(config);
3167
+ },
3168
+ async vars() {
3169
+ return new EnvFile(envPath(config)).vars;
3170
+ },
3171
+ async services() {
3172
+ const ps = await composePs(config);
3173
+ return ps.map((e) => ({ service: e.Service ?? "?", state: e.State ?? "", health: e.Health ?? "", status: e.Status ?? "" }));
3174
+ },
3175
+ async deploy(targets, reporter, signal) {
3176
+ await deploy(project2, targets, reporter, { signal });
3177
+ },
3178
+ async rollback(reporter, signal) {
3179
+ const rb = rollbackTargets(project2);
3180
+ if (!rb) throw new Error("Nothing to roll back to");
3181
+ await deploy(project2, rb.targets, reporter, { signal, rollbackOf: rb.entry.id });
3182
+ },
3183
+ async rollbackPreview() {
3184
+ return rollbackTargets(project2);
3185
+ }
3186
+ };
3187
+ }
3188
+ function remoteBackend(project2) {
3189
+ const { config } = project2;
3190
+ return {
3191
+ kind: "remote",
3192
+ label: remoteLabel(config),
3193
+ async state() {
3194
+ const status = await remoteJson(config, ["status", "--json"]);
3195
+ const known = new Set(deployableImages(config).map((i) => i.key));
3196
+ return new Map(status.images.filter((s) => known.has(s.image)).map((s) => [s.image, s.tag ?? void 0]));
3197
+ },
3198
+ async history() {
3199
+ return remoteJson(config, ["history", "--json"]);
3200
+ },
3201
+ async vars() {
3202
+ return void 0;
3203
+ },
3204
+ async services() {
3205
+ return void 0;
3206
+ },
3207
+ async deploy(targets, reporter, signal) {
3208
+ const tags = new Set(targets.map((t) => t.tag));
3209
+ for (const tag of tags) {
3210
+ const keys = targets.filter((t) => t.tag === tag).map((t) => t.image.key);
3211
+ await remoteRun(config, ["deploy", tag, "--images", keys.join(","), "--yes"], reporter, signal);
3212
+ }
3213
+ },
3214
+ async rollback(reporter, signal) {
3215
+ await remoteRun(config, ["rollback", "--yes"], reporter, signal);
3216
+ },
3217
+ async rollbackPreview() {
3218
+ return rollbackTargets(project2, await this.history());
3219
+ }
3220
+ };
3221
+ }
3222
+ var init_backend = __esm({
3223
+ "src/tui/backend.ts"() {
3224
+ "use strict";
3225
+ init_config();
3226
+ init_deploy();
3227
+ init_envfile();
3228
+ init_remote();
3229
+ }
3230
+ });
3231
+
3232
+ // src/tui/screens/dialogs.ts
3233
+ var panelWidth, ConfirmScreen, InputScreen;
3234
+ var init_dialogs = __esm({
3235
+ "src/tui/screens/dialogs.ts"() {
3236
+ "use strict";
3237
+ init_ansi();
3238
+ init_theme();
3239
+ init_widgets();
3240
+ panelWidth = (frame) => Math.min(72, frame.width - 4);
3241
+ ConfirmScreen = class {
3242
+ constructor(app, opts) {
3243
+ this.app = app;
3244
+ this.opts = opts;
3245
+ this.title = opts.title;
3246
+ this.buttons = new ButtonBar([
3247
+ { label: opts.confirmLabel ?? "Confirm", tone: opts.danger ? "danger" : "primary", action: () => this.confirm() },
3248
+ { label: "Cancel", action: () => this.app.pop() }
3249
+ ]);
3250
+ }
3251
+ app;
3252
+ opts;
3253
+ title;
3254
+ buttons;
3255
+ confirm() {
3256
+ this.app.pop();
3257
+ this.opts.onConfirm();
3258
+ }
3259
+ render(frame) {
3260
+ const width = panelWidth(frame);
3261
+ const lines = ["", ...wrap(this.opts.message, width - 4).map((l) => c.text(l)), ""];
3262
+ const color = this.opts.danger ? palette.danger : palette.brand;
3263
+ frame.blank(Math.max(1, Math.floor((frame.height - lines.length - 5) / 3)));
3264
+ for (const line of box(lines, width, bold(this.opts.title), color)) frame.line(` ${line}`);
3265
+ frame.blank();
3266
+ this.buttons.render(frame, " ");
3267
+ }
3268
+ onKey(event) {
3269
+ if (event.name === "char" && event.char === "y") {
3270
+ this.confirm();
3271
+ return true;
3272
+ }
3273
+ if (event.name === "char" && event.char === "n") {
3274
+ this.app.pop();
3275
+ return true;
3276
+ }
3277
+ return this.buttons.onKey(event);
3278
+ }
3279
+ hints() {
3280
+ return [
3281
+ { key: "y", label: this.opts.confirmLabel?.toLowerCase() ?? "yes", action: () => this.confirm() },
3282
+ { key: "n", label: "cancel", action: () => this.app.pop() },
3283
+ { key: "\u2190\u2192", label: "choose" }
3284
+ ];
3285
+ }
3286
+ };
3287
+ InputScreen = class {
3288
+ constructor(app, opts) {
3289
+ this.app = app;
3290
+ this.opts = opts;
3291
+ this.title = opts.title;
3292
+ this.input = new TextInput(opts.initial ?? "", { mask: opts.mask, placeholder: opts.placeholder });
3293
+ this.buttons = new ButtonBar([
3294
+ { label: opts.submitLabel ?? "Save", tone: "primary", action: () => void this.submit() },
3295
+ { label: "Cancel", action: () => this.app.pop() }
3296
+ ]);
3297
+ }
3298
+ app;
3299
+ opts;
3300
+ title;
3301
+ input;
3302
+ busy = false;
3303
+ error = "";
3304
+ buttons;
3305
+ async submit() {
3306
+ if (this.busy) return;
3307
+ const value = this.input.value.trim();
3308
+ const invalid = this.opts.validate?.(value);
3309
+ if (invalid) {
3310
+ this.error = invalid;
3311
+ this.app.invalidate();
3312
+ return;
3313
+ }
3314
+ this.busy = true;
3315
+ this.error = "";
3316
+ this.app.invalidate();
3317
+ try {
3318
+ await this.opts.submit(value);
3319
+ if (this.app.current === this) this.app.pop();
3320
+ } catch (err) {
3321
+ const info = describeError(err);
3322
+ this.error = info.detail ? `${info.title} \u2014 ${info.detail}` : info.title;
3323
+ } finally {
3324
+ this.busy = false;
3325
+ this.app.invalidate();
3326
+ }
3327
+ }
3328
+ animated() {
3329
+ return this.busy;
3330
+ }
3331
+ capturesText() {
3332
+ return true;
3333
+ }
3334
+ render(frame) {
3335
+ const width = panelWidth(frame);
3336
+ const inner = width - 4;
3337
+ const field = box([this.input.render(inner - 2, !this.busy)], inner, void 0, this.error ? palette.danger : palette.brand);
3338
+ const lines = ["", c.bold(c.text(this.opts.label)), ""];
3339
+ for (const line of this.opts.help ?? []) lines.push(...wrap(line, inner).map((l) => c.muted(l)));
3340
+ if (this.opts.help?.length) lines.push("");
3341
+ lines.push(...field);
3342
+ lines.push(this.busy ? `${c.brandSoft(spinnerFrame(this.app.tick))} ${c.muted("Checking\u2026")}` : this.error ? c.danger(`\u2717 ${this.error}`) : "");
3343
+ frame.blank(Math.max(1, Math.floor((frame.height - lines.length - 5) / 3)));
3344
+ for (const line of box(lines, width, bold(this.opts.title))) frame.line(` ${line}`);
3345
+ frame.blank();
3346
+ this.buttons.render(frame, " ", !this.busy);
3347
+ }
3348
+ onPaste(text) {
3349
+ if (!this.busy) this.input.insert(text.trim());
3350
+ }
3351
+ onKey(event) {
3352
+ if (this.busy) return event.name !== "escape";
3353
+ if (event.name === "enter") {
3354
+ void this.submit();
3355
+ return true;
3356
+ }
3357
+ if (event.name === "tab") return this.buttons.onKey(event);
3358
+ return this.input.onKey(event);
3359
+ }
3360
+ hints() {
3361
+ return [
3362
+ { key: "\u23CE", label: this.opts.submitLabel?.toLowerCase() ?? "save", action: () => void this.submit() },
3363
+ { key: "ctrl+u", label: "clear" }
3364
+ ];
3365
+ }
3366
+ };
3367
+ }
3368
+ });
3369
+
3370
+ // src/tui/screens/task.ts
3371
+ var MAX_LOG, TaskScreen;
3372
+ var init_task = __esm({
3373
+ "src/tui/screens/task.ts"() {
3374
+ "use strict";
3375
+ init_ansi();
3376
+ init_theme();
3377
+ init_widgets();
3378
+ init_errors();
3379
+ MAX_LOG = 5e3;
3380
+ TaskScreen = class {
3381
+ constructor(app, opts) {
3382
+ this.app = app;
3383
+ this.opts = opts;
3384
+ this.title = opts.title;
3385
+ }
3386
+ app;
3387
+ opts;
3388
+ title;
3389
+ state = "running";
3390
+ steps = [];
3391
+ log = [];
3392
+ scroll = 0;
3393
+ // lines up from the bottom; 0 = follow
3394
+ started = Date.now();
3395
+ ended;
3396
+ outcome;
3397
+ buttons = new ButtonBar([]);
3398
+ controller = new AbortController();
3399
+ mount() {
3400
+ void this.start();
3401
+ }
3402
+ reporter() {
3403
+ const push = (kind, text) => {
3404
+ this.log.push({ kind, text: stripAnsi(text) });
3405
+ if (this.log.length > MAX_LOG) this.log.splice(0, this.log.length - MAX_LOG);
3406
+ this.app.invalidate();
3407
+ };
3408
+ return {
3409
+ step: (m) => {
3410
+ const now = Date.now();
3411
+ const prev = this.steps[this.steps.length - 1];
3412
+ if (prev?.state === "running") {
3413
+ prev.state = "done";
3414
+ prev.ended = now;
3415
+ }
3416
+ this.steps.push({ text: m, state: "running", started: now });
3417
+ push("step", m);
3418
+ },
3419
+ info: (m) => push("info", m),
3420
+ warn: (m) => push("warn", m),
3421
+ success: (m) => push("success", m),
3422
+ output: (l) => push("output", l),
3423
+ fail: () => {
3424
+ const last = this.steps[this.steps.length - 1];
3425
+ if (last?.state === "running") {
3426
+ last.state = "failed";
3427
+ last.ended = Date.now();
3428
+ }
3429
+ this.app.invalidate();
3430
+ }
3431
+ };
3432
+ }
3433
+ async start() {
3434
+ try {
3435
+ const result = await this.opts.run(this.reporter(), this.controller.signal);
3436
+ this.finishSteps("done");
3437
+ this.state = "success";
3438
+ this.outcome = this.opts.onSuccess(result, this);
3439
+ } catch (err) {
3440
+ const cancelled = err instanceof CancelledError || this.controller.signal.aborted;
3441
+ this.finishSteps("failed");
3442
+ this.state = cancelled ? "cancelled" : "failed";
3443
+ const message = err instanceof Error ? err.message : String(err);
3444
+ this.outcome = this.opts.onFailure?.(err, this) ?? {
3445
+ lines: cancelled ? [c.warning("Cancelled.")] : message.split("\n").map((l, i) => i === 0 ? c.danger(`\u2717 ${l}`) : c.muted(` ${l}`)),
3446
+ buttons: [{ label: "Back", action: () => this.app.pop() }]
3447
+ };
3448
+ } finally {
3449
+ this.ended = Date.now();
3450
+ this.buttons = new ButtonBar(this.outcome?.buttons ?? []);
3451
+ this.app.invalidate();
3452
+ }
3453
+ }
3454
+ finishSteps(final) {
3455
+ const last = this.steps[this.steps.length - 1];
3456
+ const alreadyFailed = this.steps.some((s) => s.state === "failed");
3457
+ if (last?.state === "running") {
3458
+ last.state = alreadyFailed ? "done" : final;
3459
+ last.ended = Date.now();
3460
+ }
3461
+ }
3462
+ get running() {
3463
+ return this.state === "running";
3464
+ }
3465
+ cancel() {
3466
+ if (this.running && this.opts.cancellable) {
3467
+ this.controller.abort();
3468
+ this.app.toast("Cancelling\u2026", "warning");
3469
+ }
3470
+ }
3471
+ animated() {
3472
+ return this.running;
3473
+ }
3474
+ blocksExit() {
3475
+ if (!this.running) return void 0;
3476
+ return this.opts.cancellable ? "Still running \u2014 ctrl+c cancels it" : "Deploy in progress \u2014 wait for it to finish";
3477
+ }
3478
+ onInterrupt() {
3479
+ if (!this.running) return false;
3480
+ if (this.opts.cancellable) this.cancel();
3481
+ else this.app.toast("A deploy cannot be interrupted half-way \u2014 wait for it to finish", "warning");
3482
+ return true;
3483
+ }
3484
+ render(frame) {
3485
+ const elapsed = formatClock((this.ended ?? Date.now()) - this.started);
3486
+ const badge = {
3487
+ running: c.brandSoft(spinnerFrame(this.app.tick)),
3488
+ success: c.success("\u2713"),
3489
+ failed: c.danger("\u2717"),
3490
+ cancelled: c.warning("\u25A0")
3491
+ }[this.state];
3492
+ frame.blank();
3493
+ frame.line(` ${badge} ${bold(c.text(this.opts.heading))} ${c.faint(elapsed)}`);
3494
+ frame.blank();
3495
+ const maxSteps = Math.max(3, Math.min(10, Math.floor(frame.height / 3)));
3496
+ const shown = this.steps.slice(-maxSteps);
3497
+ if (this.steps.length > shown.length) frame.line(c.faint(` \u2026 ${this.steps.length - shown.length} earlier steps`));
3498
+ for (const step of shown) {
3499
+ const icon = step.state === "running" ? c.brandSoft(spinnerFrame(this.app.tick)) : step.state === "done" ? c.success("\u2713") : c.danger("\u2717");
3500
+ const time = formatClock((step.ended ?? Date.now()) - step.started);
3501
+ const text = step.state === "running" ? c.text(step.text) : c.muted(step.text);
3502
+ frame.line(` ${icon} ${text} ${c.faint(time)}`);
3503
+ }
3504
+ frame.blank();
3505
+ const outcomeLines = this.outcome ? this.outcome.lines.length + 3 : 0;
3506
+ const logHeight = Math.max(3, frame.remaining - outcomeLines - 1);
3507
+ const label = this.scroll > 0 ? ` Output \xB7 \u2191 scrolled ${this.scroll} ` : " Output ";
3508
+ frame.line(` ${c.border("\u2500")}${c.faint(label)}${c.border("\u2500".repeat(Math.max(0, frame.width - label.length - 5)))}`);
3509
+ const width = frame.width - 6;
3510
+ const rendered = [];
3511
+ for (const entry of this.log) {
3512
+ for (const piece of wrap(entry.text, width)) rendered.push(this.styleLine(entry.kind, piece));
3513
+ }
3514
+ const maxScroll = Math.max(0, rendered.length - logHeight);
3515
+ this.scroll = Math.min(this.scroll, maxScroll);
3516
+ const end = rendered.length - this.scroll;
3517
+ const view = rendered.slice(Math.max(0, end - logHeight), end);
3518
+ for (const line of view) frame.line(` ${line}`);
3519
+ for (let i = view.length; i < logHeight; i++) frame.line();
3520
+ if (this.outcome) {
3521
+ frame.blank();
3522
+ for (const line of this.outcome.lines) frame.line(` ${line}`);
3523
+ frame.blank();
3524
+ this.buttons.render(frame, " ");
3525
+ }
3526
+ }
3527
+ styleLine(kind, text) {
3528
+ switch (kind) {
3529
+ case "step":
3530
+ return c.accent(`==> ${text}`);
3531
+ case "warn":
3532
+ return c.warning(`!! ${text}`);
3533
+ case "success":
3534
+ return c.success(`\u2713 ${text}`);
3535
+ case "error":
3536
+ return c.danger(`\u2717 ${text}`);
3537
+ case "info":
3538
+ return c.text(text);
3539
+ default:
3540
+ return c.faint(text);
3541
+ }
3542
+ }
3543
+ onWheel(direction) {
3544
+ this.scroll = Math.max(0, this.scroll - direction * 3);
3545
+ }
3546
+ onKey(event) {
3547
+ switch (event.name) {
3548
+ case "up":
3549
+ this.scroll++;
3550
+ return true;
3551
+ case "down":
3552
+ this.scroll = Math.max(0, this.scroll - 1);
3553
+ return true;
3554
+ case "pageup":
3555
+ this.scroll += 10;
3556
+ return true;
3557
+ case "pagedown":
3558
+ this.scroll = Math.max(0, this.scroll - 10);
3559
+ return true;
3560
+ case "end":
3561
+ this.scroll = 0;
3562
+ return true;
3563
+ case "home":
3564
+ this.scroll = Number.MAX_SAFE_INTEGER;
3565
+ return true;
3566
+ }
3567
+ if (this.running) {
3568
+ if (event.name === "char" && event.char === "c" && !event.ctrl && this.opts.cancellable) {
3569
+ this.cancel();
3570
+ return true;
3571
+ }
3572
+ return false;
3573
+ }
3574
+ return this.buttons.onKey(event);
3575
+ }
3576
+ hints() {
3577
+ const hints = [{ key: "\u2191\u2193", label: "scroll output" }];
3578
+ if (this.running && this.opts.cancellable) hints.push({ key: "c", label: "cancel", action: () => this.cancel() });
3579
+ if (!this.running) hints.push({ key: "\u2190\u2192 \u23CE", label: "choose" });
3580
+ return hints;
3581
+ }
3582
+ };
3583
+ }
3584
+ });
3585
+
3586
+ // src/tui/screens/run.ts
3587
+ function runTask(app, opts) {
3588
+ const depth = app.depth;
3589
+ app.push(new TaskScreen(app, {
3590
+ ...opts,
3591
+ run: (rep, signal) => opts.run(rep, signal),
3592
+ onSuccess: opts.onSuccess ?? (() => ({
3593
+ lines: [c.success(`\u2713 ${opts.successText ?? "Done"}`)],
3594
+ buttons: [{ label: "Done", tone: "primary", action: () => app.popTo(1) }, { label: "Back", action: () => app.popTo(depth) }]
3595
+ }))
3596
+ }));
3597
+ }
3598
+ var init_run = __esm({
3599
+ "src/tui/screens/run.ts"() {
3600
+ "use strict";
3601
+ init_theme();
3602
+ init_task();
3603
+ }
3604
+ });
3605
+
3606
+ // src/tui/screens/build.ts
3607
+ function deployTargets(project2, keys, tag) {
3608
+ return deployableImages(project2.config).filter((i) => keys.includes(i.key)).map((image) => ({ image, tag }));
3609
+ }
3610
+ var BuildScreen;
3611
+ var init_build2 = __esm({
3612
+ "src/tui/screens/build.ts"() {
3613
+ "use strict";
3614
+ init_ansi();
3615
+ init_theme();
3616
+ init_widgets();
3617
+ init_dialogs();
3618
+ init_run();
3619
+ init_build();
3620
+ init_config();
3621
+ BuildScreen = class {
3622
+ constructor(app, project2, backend) {
3623
+ this.app = app;
3624
+ this.project = project2;
3625
+ this.backend = backend;
3626
+ const { config } = project2;
3627
+ this.selected = new Set(config.images.filter((i) => i.isDefault).map((i) => i.key));
3628
+ this.ref = config.ref;
3629
+ this.pushLatest = config.pushLatest;
3630
+ }
3631
+ app;
3632
+ project;
3633
+ backend;
3634
+ title = "Build & push";
3635
+ selected;
3636
+ tag = "";
3637
+ ref;
3638
+ pushLatest;
3639
+ runChecks = false;
3640
+ deployAfter = false;
3641
+ dryRun = false;
3642
+ menu = new Menu([]);
3643
+ plan;
3644
+ planError = "";
3645
+ planning = false;
3646
+ planSeq = 0;
3647
+ mount() {
3648
+ this.replan();
3649
+ }
3650
+ replan() {
3651
+ const seq = ++this.planSeq;
3652
+ this.planning = true;
3653
+ this.app.invalidate();
3654
+ planBuild(this.project, { images: [...this.selected], tag: this.tag || void 0, ref: this.ref, pushLatest: this.pushLatest }).then((plan) => {
3655
+ if (seq !== this.planSeq) return;
3656
+ this.plan = plan;
3657
+ this.planError = "";
3658
+ }, (err) => {
3659
+ if (seq !== this.planSeq) return;
3660
+ this.plan = void 0;
3661
+ this.planError = err instanceof Error ? err.message.split("\n")[0] : String(err);
3662
+ }).finally(() => {
3663
+ if (seq !== this.planSeq) return;
3664
+ this.planning = false;
3665
+ this.app.invalidate();
3666
+ });
3667
+ }
3668
+ items() {
3669
+ const { config } = this.project;
3670
+ const box2 = (on) => on ? c.success("\u25C9") : c.faint("\u25CB");
3671
+ const items = [{ heading: "Images", label: "", action: () => {
3672
+ } }];
3673
+ items.push(...config.images.map((img) => ({
3674
+ label: img.key,
3675
+ icon: box2(this.selected.has(img.key)),
3676
+ description: `${img.dockerfile}${img.isDefault ? "" : " (opt-in)"}${img.versioned ? "" : ` \u2192 ${img.tags.join(", ")}`}`,
3677
+ action: () => {
3678
+ if (this.selected.has(img.key)) this.selected.delete(img.key);
3679
+ else this.selected.add(img.key);
3680
+ this.replan();
3681
+ }
3682
+ })));
3683
+ items.push(
3684
+ { heading: "Options", label: "", action: () => {
3685
+ } },
3686
+ {
3687
+ label: "Tag",
3688
+ icon: c.accent("\u270E"),
3689
+ shortcut: "t",
3690
+ description: this.tag ? `${this.tag} (custom)` : `auto: ${config.versionFormat}`,
3691
+ action: () => this.app.push(new InputScreen(this.app, {
3692
+ title: "Image tag",
3693
+ label: "Tag for this release (empty = the configured format)",
3694
+ initial: this.tag,
3695
+ placeholder: this.plan?.tag ?? config.versionFormat,
3696
+ submitLabel: "Use",
3697
+ validate: (v) => v && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(v) ? "Letters, digits, _ . - only (max 128)" : void 0,
3698
+ submit: async (v) => {
3699
+ this.tag = v;
3700
+ this.replan();
3701
+ }
3702
+ }))
3703
+ },
3704
+ {
3705
+ label: "Git ref",
3706
+ icon: c.accent("\u270E"),
3707
+ shortcut: "g",
3708
+ description: this.ref,
3709
+ action: () => this.app.push(new InputScreen(this.app, {
3710
+ title: "Git ref",
3711
+ label: "Branch, tag or commit to build (its committed tree only)",
3712
+ initial: this.ref,
3713
+ submitLabel: "Use",
3714
+ submit: async (v) => {
3715
+ this.ref = v || "HEAD";
3716
+ this.replan();
3717
+ }
3718
+ }))
3719
+ },
3720
+ {
3721
+ label: "Move :latest",
3722
+ icon: box2(this.pushLatest),
3723
+ shortcut: "l",
3724
+ description: "also tag the images as latest",
3725
+ action: () => {
3726
+ this.pushLatest = !this.pushLatest;
3727
+ this.replan();
3728
+ }
3729
+ }
3730
+ );
3731
+ if (config.checks.length) {
3732
+ items.push({
3733
+ label: "Run checks",
3734
+ icon: box2(this.runChecks),
3735
+ shortcut: "k",
3736
+ description: config.checks.map((ch) => ch.name).join(", "),
3737
+ action: () => {
3738
+ this.runChecks = !this.runChecks;
3739
+ }
3740
+ });
3741
+ }
3742
+ if (this.backend) {
3743
+ items.push({
3744
+ label: "Then deploy",
3745
+ icon: box2(this.deployAfter),
3746
+ shortcut: "p",
3747
+ description: `deploy the new version${this.backend.kind === "remote" ? ` on ${config.remote.host}` : " here"} once pushed`,
3748
+ action: () => {
3749
+ this.deployAfter = !this.deployAfter;
3750
+ }
3751
+ });
3752
+ }
3753
+ items.push(
3754
+ { label: "Dry run", icon: box2(this.dryRun), shortcut: "n", description: "print the docker commands only", action: () => {
3755
+ this.dryRun = !this.dryRun;
3756
+ } },
3757
+ {
3758
+ label: this.dryRun ? "Show commands" : "Start build",
3759
+ icon: c.brand("\u25B6"),
3760
+ shortcut: "s",
3761
+ description: this.plan ? `${this.selected.size} image${this.selected.size === 1 ? "" : "s"} as ${this.plan.tag}` : "",
3762
+ disabled: !this.plan || this.planning,
3763
+ action: () => this.start()
3764
+ }
3765
+ );
3766
+ return items;
3767
+ }
3768
+ start() {
3769
+ const plan = this.plan;
3770
+ if (!plan) return;
3771
+ const opts = {
3772
+ images: [...this.selected],
3773
+ tag: plan.tag,
3774
+ // freeze the previewed tag (a {date}/{time} format must not drift)
3775
+ ref: this.ref,
3776
+ pushLatest: this.pushLatest,
3777
+ runChecks: this.runChecks,
3778
+ dryRun: this.dryRun
3779
+ };
3780
+ const backend = this.deployAfter && !this.dryRun ? this.backend : void 0;
3781
+ const project2 = this.project;
3782
+ const app = this.app;
3783
+ runTask(app, {
3784
+ title: "Building",
3785
+ heading: `${this.dryRun ? "Dry run of" : "Building"} ${plan.tag}`,
3786
+ cancellable: true,
3787
+ run: async (rep, signal) => {
3788
+ const result = await build(project2, rep, { ...opts, signal });
3789
+ if (backend) {
3790
+ const targets = deployTargets(project2, result.images.map((i) => i.key), result.tag);
3791
+ if (targets.length) {
3792
+ rep.step(`Deploying ${result.tag}`);
3793
+ await backend.deploy(targets, rep, signal);
3794
+ }
3795
+ }
3796
+ return result;
3797
+ },
3798
+ onSuccess: (result) => {
3799
+ const lines = this.dryRun ? [c.success("\u2713 Dry run \u2014 nothing was built or pushed")] : [
3800
+ c.success(`\u2713 Published ${bold(result.tag)} in ${formatSeconds(result.seconds)}`),
3801
+ ...result.pushed.map((t) => c.muted(` ${t}`))
3802
+ ];
3803
+ const targets = deployTargets(project2, result.images.map((i) => i.key), result.tag);
3804
+ const canDeployNow = !this.dryRun && !backend && this.backend && targets.length > 0;
3805
+ if (backend) lines.push(c.success(`\u2713 Deployed ${result.tag}`));
3806
+ return {
3807
+ lines,
3808
+ buttons: [
3809
+ ...canDeployNow ? [{
3810
+ label: `Deploy ${result.tag}`,
3811
+ tone: "primary",
3812
+ action: () => runTask(app, {
3813
+ title: "Deploying",
3814
+ heading: `Deploying ${result.tag}`,
3815
+ run: (rep, signal) => this.backend.deploy(targets, rep, signal),
3816
+ successText: `Deployed ${result.tag}`
3817
+ })
3818
+ }] : [],
3819
+ { label: "Done", tone: canDeployNow ? "default" : "primary", action: () => app.popTo(1) }
3820
+ ]
3821
+ };
3822
+ }
3823
+ });
3824
+ }
3825
+ render(frame) {
3826
+ this.menu.items = this.items();
3827
+ frame.blank();
3828
+ this.menu.render(frame, " ", 22);
3829
+ frame.blank();
3830
+ frame.line(sectionTitle("Will push", frame.width));
3831
+ frame.blank();
3832
+ if (this.planning) frame.line(` ${c.brandSoft(spinnerFrame(this.app.tick))} ${c.muted("Resolving\u2026")}`);
3833
+ else if (this.planError) frame.line(` ${c.danger(`\u2717 ${this.planError}`)}`);
3834
+ else if (this.plan) {
3835
+ frame.line(` ${c.muted("commit")} ${c.text(this.plan.sha.slice(0, 8))} ${c.faint(`(${this.plan.ref})`)}`);
3836
+ for (const tags of Object.values(this.plan.tags)) for (const t of tags) frame.line(` ${c.text(t)}`);
3837
+ }
3838
+ }
3839
+ onWheel(direction) {
3840
+ this.menu.items = this.items();
3841
+ this.menu.move(direction);
3842
+ }
3843
+ onKey(event) {
3844
+ this.menu.items = this.items();
3845
+ return this.menu.onKey(event);
3846
+ }
3847
+ hints() {
3848
+ return [
3849
+ { key: "\u2191\u2193", label: "move" },
3850
+ { key: "\u23CE/space", label: "toggle" },
3851
+ { key: "s", label: "start", action: () => this.start() }
3852
+ ];
3853
+ }
3854
+ };
3855
+ }
3856
+ });
3857
+
3858
+ // src/tui/screens/deploy.ts
3859
+ var DeployScreen;
3860
+ var init_deploy2 = __esm({
3861
+ "src/tui/screens/deploy.ts"() {
3862
+ "use strict";
3863
+ init_ansi();
3864
+ init_theme();
3865
+ init_widgets();
3866
+ init_run();
3867
+ init_config();
3868
+ init_deploy();
3869
+ DeployScreen = class {
3870
+ constructor(app, project2, backend, release, running) {
3871
+ this.app = app;
3872
+ this.project = project2;
3873
+ this.backend = backend;
3874
+ this.release = release;
3875
+ this.title = `Deploy ${release.tag}`;
3876
+ this.running = running;
3877
+ this.buttons = new ButtonBar([
3878
+ { label: `Deploy ${release.tag}`, tone: "primary", action: () => this.start() },
3879
+ { label: "Cancel", action: () => this.app.pop() }
3880
+ ]);
3881
+ this.menu.onFocus = () => {
3882
+ this.focus = "menu";
3883
+ };
3884
+ this.pickDefaults();
3885
+ }
3886
+ app;
3887
+ project;
3888
+ backend;
3889
+ release;
3890
+ title;
3891
+ chosen = /* @__PURE__ */ new Set();
3892
+ menu = new Menu([]);
3893
+ buttons;
3894
+ focus = "buttons";
3895
+ running;
3896
+ envVars;
3897
+ loadingState = false;
3898
+ mount() {
3899
+ void this.backend.vars().then((v) => {
3900
+ this.envVars = v;
3901
+ this.app.invalidate();
3902
+ }, () => void 0);
3903
+ if (!this.running) {
3904
+ this.loadingState = true;
3905
+ this.backend.state().then((s) => {
3906
+ this.running = s;
3907
+ this.pickDefaults();
3908
+ }, () => {
3909
+ this.running = /* @__PURE__ */ new Map();
3910
+ }).finally(() => {
3911
+ this.loadingState = false;
3912
+ this.app.invalidate();
3913
+ });
3914
+ }
3915
+ }
3916
+ /** Everything published under the tag, minus what already runs it (unless that is everything). */
3917
+ pickDefaults() {
3918
+ this.chosen.clear();
3919
+ const available = deployableImages(this.project.config).filter((i) => this.release.images.includes(i.key));
3920
+ const moving = available.filter((i) => this.running?.get(i.key) !== this.release.tag);
3921
+ for (const i of moving.length ? moving : available) this.chosen.add(i.key);
3922
+ }
3923
+ targets() {
3924
+ return deployableImages(this.project.config).filter((i) => this.chosen.has(i.key)).map((image) => ({ image, tag: this.release.tag }));
3925
+ }
3926
+ items() {
3927
+ return deployableImages(this.project.config).map((img) => {
3928
+ const published = this.release.images.includes(img.key);
3929
+ const now = this.running?.get(img.key);
3930
+ const on = this.chosen.has(img.key);
3931
+ const change = !published ? c.faint("not published at this tag") : now === this.release.tag ? c.faint(`${now} (already running)`) : `${c.muted(now ?? "unset")} ${c.faint("\u2192")} ${c.success(this.release.tag)}`;
3932
+ return {
3933
+ label: img.key,
3934
+ icon: published ? on ? c.success("\u25C9") : c.faint("\u25CB") : c.faint("\xB7"),
3935
+ description: change,
3936
+ disabled: !published,
3937
+ action: () => {
3938
+ if (on) this.chosen.delete(img.key);
3939
+ else this.chosen.add(img.key);
3940
+ }
3941
+ };
3942
+ });
3943
+ }
3944
+ start() {
3945
+ const targets = this.targets();
3946
+ if (targets.length === 0) {
3947
+ this.app.toast("Select at least one image", "warning");
3948
+ return;
3949
+ }
3950
+ const backend = this.backend;
3951
+ const tag = this.release.tag;
3952
+ const app = this.app;
3953
+ app.pop();
3954
+ runTask(app, {
3955
+ title: "Deploying",
3956
+ heading: `Deploying ${tag}${backend.kind === "remote" ? ` on ${this.project.config.remote.host}` : ""}`,
3957
+ run: (rep, signal) => backend.deploy(targets, rep, signal),
3958
+ successText: `${targets.map((t) => t.image.key).join(", ")} now run ${tag}`
3959
+ });
3960
+ }
3961
+ render(frame) {
3962
+ this.menu.items = this.items();
3963
+ const width = Math.min(frame.width - 4, 90);
3964
+ const where = this.backend.kind === "remote" ? `${this.backend.label} (over ssh)` : this.backend.label;
3965
+ const info = [
3966
+ `${c.muted("Version ")} ${bold(c.text(this.release.tag))}${this.release.latest ? c.accent(" \u2605 latest") : ""}`,
3967
+ `${c.muted("Published")} ${c.text(this.release.created ? `${relativeTime(this.release.created)} (${this.release.created.slice(0, 16).replace("T", " ")})` : "unknown")}`,
3968
+ `${c.muted("Target ")} ${c.text(where)}`
3969
+ ];
3970
+ frame.blank();
3971
+ for (const l of box(info, width, bold("Deploy"), palette.brand)) frame.line(` ${l}`);
3972
+ frame.blank();
3973
+ frame.line(` ${c.bold(c.text("Images"))} ${this.loadingState ? c.faint("reading what runs now\u2026") : ""}`);
3974
+ this.menu.render(frame, " ", 18, this.focus === "menu");
3975
+ if (this.envVars) {
3976
+ const { set, warnings } = planVars(this.project.config, this.targets(), this.envVars);
3977
+ const pins = set.filter((s) => s.reason.startsWith("pin"));
3978
+ if (pins.length || warnings.length) frame.blank();
3979
+ for (const p of pins) frame.line(` ${c.faint(`also sets ${p.key}=${p.value} (${p.reason})`)}`);
3980
+ for (const w of warnings) frame.line(` ${c.warning(`! ${w}`)}`);
3981
+ }
3982
+ frame.blank();
3983
+ const cfg = this.project.config.deploy;
3984
+ const checks = [cfg.waitForServices ? "containers up" : "", cfg.healthcheck ? `GET ${cfg.healthcheck.url}` : "", ...cfg.postDeploy.map((h) => h.name)].filter(Boolean);
3985
+ if (this.backend.kind === "local") {
3986
+ frame.line(` ${c.faint(`After deploy: ${checks.join(" \xB7 ") || "no checks"}`)}`);
3987
+ if (cfg.autoRollback && checks.length) frame.line(` ${c.faint("If a check fails, the previous tags are put back automatically.")}`);
3988
+ frame.blank();
3989
+ }
3990
+ this.buttons.render(frame, " ", this.focus === "buttons");
3991
+ }
3992
+ onWheel(direction) {
3993
+ this.focus = "menu";
3994
+ this.menu.move(direction);
3995
+ }
3996
+ onKey(event) {
3997
+ this.menu.items = this.items();
3998
+ if (event.name === "char" && event.char === "d" && !event.ctrl) {
3999
+ this.start();
4000
+ return true;
4001
+ }
4002
+ if (event.name === "up" || event.name === "down") {
4003
+ if (this.focus === "buttons" && event.name === "up") {
4004
+ this.focus = "menu";
4005
+ this.menu.selected = Math.max(0, this.menu.items.length - 1);
4006
+ if (this.menu.items[this.menu.selected]?.disabled) this.menu.move(-1);
4007
+ return true;
4008
+ }
4009
+ if (this.focus === "menu" && event.name === "down" && this.isLastEnabled()) {
4010
+ this.focus = "buttons";
4011
+ return true;
4012
+ }
4013
+ this.focus = "menu";
4014
+ return this.menu.onKey(event);
4015
+ }
4016
+ if (event.name === "tab") {
4017
+ this.focus = this.focus === "menu" ? "buttons" : "menu";
4018
+ return true;
4019
+ }
4020
+ if (this.focus === "menu") {
4021
+ if (event.name === "space" || event.name === "enter") return this.menu.onKey(event);
4022
+ return false;
4023
+ }
4024
+ return this.buttons.onKey(event);
4025
+ }
4026
+ isLastEnabled() {
4027
+ const items = this.menu.items;
4028
+ for (let i = items.length - 1; i >= 0; i--) if (!items[i].disabled) return i === this.menu.selected;
4029
+ return true;
4030
+ }
4031
+ hints() {
4032
+ return [
4033
+ { key: "space", label: "toggle image" },
4034
+ { key: "d", label: "deploy", action: () => this.start() },
4035
+ { key: "tab", label: "focus" }
4036
+ ];
4037
+ }
4038
+ };
4039
+ }
4040
+ });
4041
+
4042
+ // src/tui/screens/history.ts
4043
+ var HistoryScreen;
4044
+ var init_history = __esm({
4045
+ "src/tui/screens/history.ts"() {
4046
+ "use strict";
4047
+ init_theme();
4048
+ init_widgets();
4049
+ init_dialogs();
4050
+ init_run();
4051
+ init_config();
4052
+ HistoryScreen = class {
4053
+ constructor(app, project2, backend) {
4054
+ this.app = app;
4055
+ this.project = project2;
4056
+ this.backend = backend;
4057
+ this.data = new Resource(app, () => backend.history());
4058
+ this.list = new ListView({
4059
+ columns: [
4060
+ { header: "WHEN", width: 12, render: (h) => c.muted(relativeTime(h.at)) },
4061
+ { header: "RESULT", width: 14, render: (h) => statusBadge(h.status === "success" ? "success" : h.status === "rolled-back" ? "degraded" : "failed") },
4062
+ { header: "IMAGES", width: "flex", render: (h) => c.text(Object.entries(h.images).map(([k, v]) => `${k}:${v}`).join(" ")) },
4063
+ { header: "BY", width: 14, render: (h) => c.faint(h.user) }
4064
+ ],
4065
+ searchText: (h) => `${h.status} ${h.user} ${Object.entries(h.images).flat().join(" ")}`,
4066
+ emptyText: "No deploys recorded yet.",
4067
+ onSelect: (h) => this.redeploy(h)
4068
+ });
4069
+ }
4070
+ app;
4071
+ project;
4072
+ backend;
4073
+ title = "History";
4074
+ data;
4075
+ list;
4076
+ mount() {
4077
+ void this.load();
4078
+ }
4079
+ async load() {
4080
+ await this.data.load();
4081
+ if (this.data.data) this.list.setItems(this.data.data);
4082
+ }
4083
+ redeploy(h) {
4084
+ const images = deployableImages(this.project.config);
4085
+ const targets = Object.entries(h.images).flatMap(([key2, tag]) => {
4086
+ const image = images.find((i) => i.key === key2);
4087
+ return image ? [{ image, tag }] : [];
4088
+ });
4089
+ if (targets.length === 0) {
4090
+ this.app.toast("None of those images are in deployer.json any more", "warning");
4091
+ return;
4092
+ }
4093
+ this.app.push(new ConfirmScreen(this.app, {
4094
+ title: "Re-deploy",
4095
+ message: `Deploy ${targets.map((t) => `${t.image.key}:${t.tag}`).join(", ")} again on ${this.backend.label}?`,
4096
+ confirmLabel: "Deploy",
4097
+ onConfirm: () => runTask(this.app, {
4098
+ title: "Deploying",
4099
+ heading: `Re-deploying ${[...new Set(targets.map((t) => t.tag))].join(", ")}`,
4100
+ run: (rep, signal) => this.backend.deploy(targets, rep, signal)
4101
+ })
4102
+ }));
4103
+ }
4104
+ animated() {
4105
+ return this.data.state === "loading";
4106
+ }
4107
+ capturesText() {
4108
+ return this.list.filtering;
4109
+ }
4110
+ render(frame) {
4111
+ if (!renderResource(frame, this.data, this.app, "Loading history\u2026", { retry: () => void this.load() })) return;
4112
+ frame.blank();
4113
+ this.list.render(frame, frame.remaining, this.app.tick);
4114
+ const current = this.list.current;
4115
+ if (current?.error && frame.remaining > 1) {
4116
+ frame.blank();
4117
+ frame.line(` ${c.danger(current.error.split("\n")[0])}`);
4118
+ }
4119
+ }
4120
+ onWheel(direction) {
4121
+ this.list.onWheel(direction);
4122
+ }
4123
+ onKey(event) {
4124
+ if (recoveryKey(event, this.data, { retry: () => void this.load() })) return true;
4125
+ return this.list.onKey(event);
4126
+ }
4127
+ hints() {
4128
+ return recoveryHints(this.data, { retry: () => void this.load() }) ?? [
4129
+ { key: "\u23CE", label: "re-deploy" },
4130
+ { key: "/", label: "filter" }
4131
+ ];
4132
+ }
4133
+ };
4134
+ }
4135
+ });
4136
+
4137
+ // src/tui/screens/status.ts
4138
+ var StatusScreen;
4139
+ var init_status = __esm({
4140
+ "src/tui/screens/status.ts"() {
4141
+ "use strict";
4142
+ init_ansi();
4143
+ init_theme();
4144
+ init_widgets();
4145
+ init_config();
4146
+ StatusScreen = class {
4147
+ constructor(app, project2, backend) {
4148
+ this.app = app;
4149
+ this.project = project2;
4150
+ this.backend = backend;
4151
+ this.data = new Resource(app, async () => {
4152
+ const [state, services, history] = await Promise.all([backend.state(), backend.services(), backend.history()]);
4153
+ return { state, services, last: history[0] };
4154
+ });
4155
+ }
4156
+ app;
4157
+ project;
4158
+ backend;
4159
+ title = "Status";
4160
+ data;
4161
+ mount() {
4162
+ void this.data.load();
4163
+ }
4164
+ animated() {
4165
+ return this.data.state === "loading";
4166
+ }
4167
+ render(frame) {
4168
+ if (!renderResource(frame, this.data, this.app, `Reading ${this.backend.label}\u2026`, { retry: () => void this.data.load() })) return;
4169
+ const d = this.data.data;
4170
+ const width = Math.min(frame.width - 4, 96);
4171
+ frame.blank();
4172
+ const rows = deployableImages(this.project.config).map((img) => [
4173
+ img.key,
4174
+ `${d.state.get(img.key) ? c.text(d.state.get(img.key)) : c.faint("unset")} ${c.faint(img.tagVar)}`
4175
+ ]);
4176
+ for (const l of box(keyValues(rows, 16), width, bold(`Running on ${this.backend.label}`))) frame.line(` ${l}`);
4177
+ if (d.services) {
4178
+ frame.blank();
4179
+ frame.line(sectionTitle("Containers", frame.width));
4180
+ frame.blank();
4181
+ if (d.services.length === 0) frame.line(` ${c.muted("No containers \u2014 the stack is not up.")}`);
4182
+ for (const s of d.services) {
4183
+ const state = s.health ? s.health === "healthy" ? "healthy" : s.health : s.state;
4184
+ frame.line(` ${s.service.padEnd(18)} ${statusBadge(state === "running" ? "up" : state, this.app.tick).padEnd(20)} ${c.faint(s.status)}`);
4185
+ }
4186
+ }
4187
+ if (d.last) {
4188
+ frame.blank();
4189
+ frame.line(sectionTitle("Last deploy", frame.width));
4190
+ frame.blank();
4191
+ const l = d.last;
4192
+ frame.line(` ${statusBadge(l.status === "success" ? "success" : l.status === "rolled-back" ? "degraded" : "failed")} ${c.text(relativeTime(l.at))} ${c.faint(`by ${l.user} \xB7 ${l.seconds} s`)}`);
4193
+ frame.line(` ${c.muted(Object.entries(l.images).map(([k, v]) => `${k}:${v}`).join(" "))}`);
4194
+ if (l.error) frame.line(` ${c.danger(l.error.split("\n")[0])}`);
4195
+ }
4196
+ }
4197
+ onKey(event) {
4198
+ if (recoveryKey(event, this.data, { retry: () => void this.data.load() })) return true;
4199
+ if (event.name === "char" && event.char === "r") {
4200
+ void this.data.load({ silent: true });
4201
+ return true;
4202
+ }
4203
+ return false;
4204
+ }
4205
+ hints() {
4206
+ return recoveryHints(this.data, { retry: () => void this.data.load() }) ?? [
4207
+ { key: "r", label: "refresh", action: () => void this.data.load({ silent: true }) }
4208
+ ];
4209
+ }
4210
+ };
4211
+ }
4212
+ });
4213
+
4214
+ // src/tui/screens/versions.ts
4215
+ var VersionsScreen;
4216
+ var init_versions = __esm({
4217
+ "src/tui/screens/versions.ts"() {
4218
+ "use strict";
4219
+ init_theme();
4220
+ init_widgets();
4221
+ init_deploy2();
4222
+ init_config();
4223
+ init_registry();
4224
+ VersionsScreen = class {
4225
+ constructor(app, project2, backend) {
4226
+ this.app = app;
4227
+ this.project = project2;
4228
+ this.backend = backend;
4229
+ const images = deployableImages(project2.config);
4230
+ this.data = new Resource(app, async () => {
4231
+ const [listing, running] = await Promise.all([
4232
+ listReleases(images),
4233
+ backend.state().then((s) => ({ s }), (err) => ({ err }))
4234
+ ]);
4235
+ return "s" in running ? { listing, running: running.s } : { listing, running: /* @__PURE__ */ new Map(), stateError: running.err instanceof Error ? running.err.message.split("\n")[0] : String(running.err) };
4236
+ });
4237
+ const total = images.length;
4238
+ this.list = new ListView({
4239
+ columns: [
4240
+ { header: "", width: 2, render: (r) => this.runningTags.has(r.tag) ? c.success("\u25CF") : r.tag === this.latestTag ? c.accent("\u2605") : " " },
4241
+ { header: "TAG", width: "flex", render: (r) => c.text(r.tag) },
4242
+ { header: "PUBLISHED", width: 12, render: (r) => c.muted(r.created ? relativeTime(r.created) : "\u2014") },
4243
+ { header: "IMAGES", width: 26, render: (r) => r.images.length === total ? c.muted(`all ${total}`) : c.warning(r.images.join(" ")) },
4244
+ {
4245
+ header: "",
4246
+ width: 16,
4247
+ render: (r) => [
4248
+ this.runningTags.has(r.tag) ? c.success("running") : "",
4249
+ r.tag === this.latestTag ? c.accent("latest") : ""
4250
+ ].filter(Boolean).join(" ")
4251
+ }
4252
+ ],
4253
+ searchText: (r) => `${r.tag} ${r.images.join(" ")}`,
4254
+ emptyText: "No published versions yet \u2014 build one first.",
4255
+ onSelect: (r) => this.app.push(new DeployScreen(this.app, this.project, this.backend, r, this.data.data?.running))
4256
+ });
4257
+ }
4258
+ app;
4259
+ project;
4260
+ backend;
4261
+ title = "Versions";
4262
+ data;
4263
+ list;
4264
+ latestTag;
4265
+ runningTags = /* @__PURE__ */ new Set();
4266
+ mount() {
4267
+ void this.load();
4268
+ }
4269
+ async load() {
4270
+ await this.data.load({ silent: true });
4271
+ const d = this.data.data;
4272
+ if (!d) return;
4273
+ this.latestTag = latestRelease(d.listing)?.tag;
4274
+ this.runningTags = new Set([...d.running.values()].filter((t) => Boolean(t)));
4275
+ this.list.setItems(d.listing.releases);
4276
+ this.app.invalidate();
4277
+ }
4278
+ animated() {
4279
+ return this.data.state === "loading";
4280
+ }
4281
+ capturesText() {
4282
+ return this.list.filtering;
4283
+ }
4284
+ render(frame) {
4285
+ if (!renderResource(frame, this.data, this.app, "Loading published versions\u2026", { retry: () => void this.load() })) return;
4286
+ const d = this.data.data;
4287
+ frame.blank();
4288
+ const notes = [];
4289
+ if (d.listing.releases.length && d.listing.releases.every((r) => !r.created)) notes.push(c.faint("dates unavailable from this registry \u2014 sorted by tag"));
4290
+ for (const e of d.listing.errors) notes.push(c.warning(`! ${e.image}: ${e.message.split("\n")[0]}`));
4291
+ if (d.stateError) notes.push(c.warning(`! could not read what runs: ${d.stateError}`));
4292
+ frame.line(` ${c.muted(`${d.listing.releases.length} versions`)} ${c.success("\u25CF")} ${c.faint("running")} ${c.accent("\u2605")} ${c.faint("latest")}${this.data.refreshing ? c.faint(" refreshing\u2026") : ""}`);
4293
+ for (const n of notes) frame.line(` ${n}`);
4294
+ frame.blank();
4295
+ this.list.render(frame, frame.remaining, this.app.tick);
4296
+ }
4297
+ onWheel(direction) {
4298
+ this.list.onWheel(direction);
4299
+ }
4300
+ onKey(event) {
4301
+ if (recoveryKey(event, this.data, { retry: () => void this.load() })) return true;
4302
+ if (!this.list.filtering && event.name === "char" && event.char === "r") {
4303
+ void this.load();
4304
+ return true;
4305
+ }
4306
+ return this.list.onKey(event);
4307
+ }
4308
+ hints() {
4309
+ return recoveryHints(this.data, { retry: () => void this.load() }) ?? [
4310
+ { key: "\u23CE", label: "deploy" },
4311
+ { key: "/", label: "filter" },
4312
+ { key: "r", label: "refresh", action: () => void this.load() }
4313
+ ];
4314
+ }
4315
+ };
4316
+ }
4317
+ });
4318
+
4319
+ // src/tui/screens/home.ts
4320
+ function imageSummary(p) {
4321
+ const keys = p.config.images.map((i) => i.key);
4322
+ const prefixed = p.config.images.every((i) => !i.explicitRepository);
4323
+ return prefixed ? `${p.imagePrefix}/{${keys.join(",")}}` : p.config.images.map((i) => i.repository).join(" ");
4324
+ }
4325
+ var HomeScreen;
4326
+ var init_home = __esm({
4327
+ "src/tui/screens/home.ts"() {
4328
+ "use strict";
4329
+ init_ansi();
4330
+ init_logo();
4331
+ init_theme();
4332
+ init_widgets();
4333
+ init_backend();
4334
+ init_build2();
4335
+ init_dialogs();
4336
+ init_deploy2();
4337
+ init_history();
4338
+ init_status();
4339
+ init_run();
4340
+ init_versions();
4341
+ init_config();
4342
+ init_git();
4343
+ init_init();
4344
+ init_registry();
4345
+ init_remote();
4346
+ HomeScreen = class {
4347
+ constructor(app, ctx) {
4348
+ this.app = app;
4349
+ this.ctx = ctx;
4350
+ }
4351
+ app;
4352
+ ctx;
4353
+ title = "Home";
4354
+ fullBleed = true;
4355
+ menu = new Menu([]);
4356
+ revealStart = Date.now();
4357
+ source = "";
4358
+ running = "";
4359
+ backend;
4360
+ mount() {
4361
+ this.refresh();
4362
+ }
4363
+ resume() {
4364
+ this.refresh();
4365
+ }
4366
+ refresh() {
4367
+ const p = this.ctx.project;
4368
+ this.backend = p ? backendFor(p) : void 0;
4369
+ this.menu.items = this.items();
4370
+ if (p?.gitRoot) {
4371
+ const root = p.gitRoot;
4372
+ void Promise.all([currentBranch(root), headCommit(root), isDirty(root)]).then(([branch, sha, dirty]) => {
4373
+ this.source = `${branch} @ ${sha?.slice(0, 8) ?? "?"}${dirty ? c.warning(" (uncommitted changes)") : ""}`;
4374
+ this.app.invalidate();
4375
+ });
4376
+ }
4377
+ if (this.backend) {
4378
+ this.running = c.faint(this.backend.kind === "remote" ? "asking the server\u2026" : "\u2026");
4379
+ void this.backend.state().then((state) => {
4380
+ const tags = [...new Set(state.values())];
4381
+ this.running = tags.length === 0 || tags.every((t) => !t) ? c.muted("nothing deployed yet") : tags.length === 1 ? c.success(tags[0]) : [...state].map(([k, v]) => `${k}:${v ?? "\u2014"}`).join(" ");
4382
+ this.app.invalidate();
4383
+ }, (err) => {
4384
+ this.running = c.danger(err instanceof Error ? err.message.split("\n")[0] : String(err));
4385
+ this.app.invalidate();
4386
+ });
4387
+ }
4388
+ }
4389
+ items() {
4390
+ const p = this.ctx.project;
4391
+ if (!p) {
4392
+ return [
4393
+ { label: "Create deployer.json", icon: "\u271A", shortcut: "i", description: "detect the Dockerfiles in this repository", action: () => void this.init() },
4394
+ { label: "Quit", icon: "\u23FB", shortcut: "q", action: () => this.app.exit() }
4395
+ ];
4396
+ }
4397
+ const backend = this.backend;
4398
+ const where = backend?.kind === "remote" ? ` on ${p.config.remote.host}` : "";
4399
+ const noDeploy = !backend ? 'needs a compose file here, or a "remote" section' : void 0;
4400
+ return [
4401
+ {
4402
+ label: "Build & push",
4403
+ icon: "\u2B22",
4404
+ shortcut: "b",
4405
+ description: p.canBuild ? `build images and push them to ${p.imagePrefix.split("/")[0] || "the registry"}` : "needs a git checkout with the Dockerfiles",
4406
+ disabled: !p.canBuild,
4407
+ action: () => this.app.push(new BuildScreen(this.app, p, backend))
4408
+ },
4409
+ {
4410
+ label: "Deploy latest",
4411
+ icon: "\u25B2",
4412
+ shortcut: "l",
4413
+ description: noDeploy ?? `pull the newest version and run it${where}`,
4414
+ disabled: !backend,
4415
+ action: () => void this.deployLatest()
4416
+ },
4417
+ {
4418
+ label: "Pick a version",
4419
+ icon: "\u2630",
4420
+ shortcut: "d",
4421
+ description: noDeploy ?? "browse every published version and deploy one",
4422
+ disabled: !backend,
4423
+ action: () => this.app.push(new VersionsScreen(this.app, p, backend))
4424
+ },
4425
+ {
4426
+ label: "Roll back",
4427
+ icon: "\u21BA",
4428
+ shortcut: "r",
4429
+ description: noDeploy ?? "put back what the last deploy replaced",
4430
+ disabled: !backend,
4431
+ action: () => void this.rollback()
4432
+ },
4433
+ {
4434
+ label: "Status",
4435
+ icon: "\u25C9",
4436
+ shortcut: "s",
4437
+ description: noDeploy ?? `running tags and containers${where}`,
4438
+ disabled: !backend,
4439
+ action: () => this.app.push(new StatusScreen(this.app, p, backend))
4440
+ },
4441
+ {
4442
+ label: "History",
4443
+ icon: "\u25F7",
4444
+ shortcut: "h",
4445
+ description: noDeploy ?? "past deploys \u2014 re-deploy any of them",
4446
+ disabled: !backend,
4447
+ action: () => this.app.push(new HistoryScreen(this.app, p, backend))
4448
+ },
4449
+ ...p.config.remote && p.canBuild ? [{
4450
+ label: "Sync to server",
4451
+ icon: "\u21EA",
4452
+ shortcut: "y",
4453
+ description: `copy deployer.json + compose files to ${p.config.remote.host}`,
4454
+ action: () => runTask(this.app, {
4455
+ title: "Sync",
4456
+ heading: `Sync to ${p.config.remote.host}`,
4457
+ cancellable: true,
4458
+ run: (rep, signal) => syncToRemote(p, rep, signal)
4459
+ })
4460
+ }] : [],
4461
+ { label: "Quit", icon: "\u23FB", shortcut: "q", action: () => this.app.exit() }
4462
+ ];
4463
+ }
4464
+ async init() {
4465
+ try {
4466
+ const { path } = await initConfig(process.cwd());
4467
+ this.app.toast(`Wrote ${path} \u2014 edit "remote" for your server`, "success", 6e3);
4468
+ await this.ctx.reload();
4469
+ this.refresh();
4470
+ } catch (err) {
4471
+ this.app.toast(err instanceof Error ? err.message.split("\n")[0] : String(err), "danger", 6e3);
4472
+ }
4473
+ }
4474
+ async deployLatest() {
4475
+ const p = this.ctx.project;
4476
+ const backend = this.backend;
4477
+ this.app.toast("Looking up the latest version\u2026", "info");
4478
+ try {
4479
+ const listing = await listReleases(deployableImages(p.config));
4480
+ const rel = latestRelease(listing);
4481
+ if (!rel) {
4482
+ this.app.toast("No published versions yet \u2014 build one first", "warning");
4483
+ return;
4484
+ }
4485
+ this.app.push(new DeployScreen(this.app, p, backend, rel));
4486
+ } catch (err) {
4487
+ this.app.toast(err instanceof Error ? err.message.split("\n")[0] : String(err), "danger", 8e3);
4488
+ }
4489
+ }
4490
+ async rollback() {
4491
+ const backend = this.backend;
4492
+ try {
4493
+ const rb = await backend.rollbackPreview();
4494
+ if (!rb) {
4495
+ this.app.toast("Nothing to roll back to yet", "warning");
4496
+ return;
4497
+ }
4498
+ const lines = rb.targets.map((t) => `${t.image.key}: ${rb.entry.images[t.image.key]} \u2192 ${t.tag}`).join(", ");
4499
+ this.app.push(new ConfirmScreen(this.app, {
4500
+ title: "Roll back",
4501
+ message: `Undo the deploy of ${relativeTime(rb.entry.at)} (${rb.entry.user}). ${lines}`,
4502
+ confirmLabel: "Roll back",
4503
+ danger: true,
4504
+ onConfirm: () => runTask(this.app, {
4505
+ title: "Rollback",
4506
+ heading: "Rolling back",
4507
+ run: (rep, signal) => backend.rollback(rep, signal)
4508
+ })
4509
+ }));
4510
+ } catch (err) {
4511
+ this.app.toast(err instanceof Error ? err.message.split("\n")[0] : String(err), "danger", 8e3);
4512
+ }
4513
+ }
4514
+ animated() {
4515
+ return Date.now() - this.revealStart < 900;
4516
+ }
4517
+ render(frame) {
4518
+ const progress = Math.min(1, (Date.now() - this.revealStart) / 800);
4519
+ frame.blank();
4520
+ for (const line of renderLogo(frame.width - 4, progress)) frame.line(` ${line}`);
4521
+ frame.line(` ${c.muted("build \xB7 push \xB7 pull \xB7 deploy")}`);
4522
+ frame.blank();
4523
+ const p = this.ctx.project;
4524
+ const width = Math.min(frame.width - 4, 96);
4525
+ if (!p) {
4526
+ const lines = [c.warning(this.ctx.problem ?? "No deployer.json here."), c.muted("Create one, or cd into a project / deploy directory.")];
4527
+ for (const l of box(lines, width, bold("Setup"), palette.warning)) frame.line(` ${l}`);
4528
+ } else {
4529
+ const rows = [
4530
+ ["Project", c.text(p.config.name)],
4531
+ ["Images", c.text(imageSummary(p))]
4532
+ ];
4533
+ if (p.gitRoot) rows.push(["Source", this.source || c.faint("\u2026")]);
4534
+ if (this.backend) rows.push([this.backend.kind === "remote" ? "Server" : "Deploy dir", c.text(this.backend.label)], ["Running", this.running]);
4535
+ rows.push(["Config", c.faint(p.config.file)]);
4536
+ for (const l of box(keyValues(rows, 11), width)) frame.line(` ${l}`);
4537
+ }
4538
+ frame.blank();
4539
+ this.menu.render(frame, " ", 18);
4540
+ }
4541
+ onWheel(direction) {
4542
+ this.menu.move(direction);
4543
+ }
4544
+ onKey(event) {
4545
+ if (event.name === "char" && event.char === "q") return false;
4546
+ return this.menu.onKey(event);
4547
+ }
4548
+ hints() {
4549
+ return [{ key: "\u2191\u2193", label: "move" }, { key: "\u23CE", label: "select" }];
4550
+ }
4551
+ };
4552
+ }
4553
+ });
4554
+
4555
+ // src/tui/index.ts
4556
+ var tui_exports = {};
4557
+ __export(tui_exports, {
4558
+ launch: () => launch
4559
+ });
4560
+ import { basename as basename2 } from "path";
4561
+ async function launch(configPath) {
4562
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
4563
+ throw new DeployerError("The interactive UI needs a terminal. Use the commands instead \u2014 see `deployer --help`.");
4564
+ }
4565
+ const ctx = {
4566
+ reload: async () => {
4567
+ try {
4568
+ ctx.project = await openProject(loadConfig(configPath));
4569
+ ctx.problem = void 0;
4570
+ } catch (err) {
4571
+ ctx.project = void 0;
4572
+ ctx.problem = err instanceof Error ? err.message.split("\n").slice(0, 3).join(" ") : String(err);
4573
+ }
4574
+ }
4575
+ };
4576
+ await ctx.reload();
4577
+ const app = new App({
4578
+ location: () => ctx.project ? ctx.project.config.name : basename2(process.cwd()),
4579
+ version: VERSION
4580
+ });
4581
+ try {
4582
+ await app.run(new HomeScreen(app, ctx));
4583
+ } finally {
4584
+ app.exit();
4585
+ }
4586
+ process.stderr.write(`${gradient("\u25B2 deployer", brandGradient)} bye.
4587
+ `);
4588
+ }
4589
+ var init_tui = __esm({
4590
+ "src/tui/index.ts"() {
4591
+ "use strict";
4592
+ init_ansi();
4593
+ init_app();
4594
+ init_home();
4595
+ init_theme();
4596
+ init_config();
4597
+ init_project();
4598
+ init_errors();
4599
+ init_version();
4600
+ }
4601
+ });
4602
+
4603
+ // src/bin/deployer.ts
4604
+ init_args();
4605
+ init_errors();
4606
+ init_reporter();
4607
+ init_version();
4608
+ process.removeAllListeners("warning");
4609
+ process.on("warning", (w) => {
4610
+ if (w.name !== "ExperimentalWarning") process.stderr.write(`${w.name}: ${w.message}
4611
+ `);
4612
+ });
4613
+ var GLOBAL = {
4614
+ config: { value: true, alias: "c" },
4615
+ help: { alias: "h" },
4616
+ version: { alias: "v" }
4617
+ };
4618
+ var COMMANDS = {
4619
+ build: {
4620
+ summary: "Build images from a commit and push them to the registry",
4621
+ usage: "deployer build [image...] [--tag T] [--ref R] [--platforms P] [--no-latest] [--checks] [--deploy] [--dry-run] [--plan]",
4622
+ details: [
4623
+ ' image... only these images (default: every image without "default": false)',
4624
+ " --tag T explicit tag instead of the configured format",
4625
+ ' --ref R branch or commit to build (default: config "ref", else HEAD)',
4626
+ " --platforms P e.g. linux/amd64,linux/arm64",
4627
+ " --no-latest do not move :latest",
4628
+ " --checks run the configured checks on the exported tree first",
4629
+ ' --deploy then run `deployer deploy` on the server over ssh ("remote")',
4630
+ " --dry-run print the docker commands without running them",
4631
+ " --plan print the resolved tag and image names as JSON, and stop"
4632
+ ].join("\n"),
4633
+ flags: { tag: { value: true, alias: "t" }, ref: { value: true }, platforms: { value: true }, latest: {}, checks: {}, deploy: {}, "dry-run": {}, plan: {} },
4634
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdBuild
4635
+ },
4636
+ versions: {
4637
+ summary: "List published versions (newest first)",
4638
+ usage: "deployer versions [--limit N] [--json]",
4639
+ flags: { limit: { value: true, alias: "n" }, json: {} },
4640
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdVersions
4641
+ },
4642
+ deploy: {
4643
+ summary: "Pull a version and run it with docker compose (on the server)",
4644
+ usage: "deployer deploy [tag|latest] [--images a,b] [--yes]",
4645
+ details: [
4646
+ ' tag a published tag, or "latest" (default)',
4647
+ " --images a,b only these images (default: every image published under the tag)",
4648
+ " --yes do not ask for confirmation (required without a terminal)"
4649
+ ].join("\n"),
4650
+ flags: { images: { value: true, alias: "i" }, yes: { alias: "y" } },
4651
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdDeploy
4652
+ },
4653
+ rollback: {
4654
+ summary: "Put back the versions the last successful deploy replaced",
4655
+ usage: "deployer rollback [--yes]",
4656
+ flags: { yes: { alias: "y" } },
4657
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdRollback
4658
+ },
4659
+ status: {
4660
+ summary: "Show which tag each image runs",
4661
+ usage: "deployer status [--json]",
4662
+ flags: { json: {} },
4663
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdStatus
4664
+ },
4665
+ history: {
4666
+ summary: "Show past deploys on this server",
4667
+ usage: "deployer history [--json]",
4668
+ flags: { json: {} },
4669
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdHistory
4670
+ },
4671
+ sync: {
4672
+ summary: 'Copy deployer.json and the compose files to the server ("remote")',
4673
+ usage: "deployer sync",
4674
+ flags: {},
4675
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdSync
4676
+ },
4677
+ init: {
4678
+ summary: "Create a deployer.json from the Dockerfiles in this repository",
4679
+ usage: "deployer init [--force]",
4680
+ flags: { force: {} },
4681
+ run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdInit
4682
+ },
4683
+ ui: {
4684
+ summary: "Open the interactive UI (the default with no command)",
4685
+ usage: "deployer ui",
4686
+ flags: {},
4687
+ run: async () => async ({ flags }) => (await Promise.resolve().then(() => (init_tui(), tui_exports))).launch(typeof flags.config === "string" ? flags.config : void 0)
4688
+ }
4689
+ };
4690
+ function help() {
4691
+ const width = Math.max(...Object.keys(COMMANDS).map((k) => k.length));
4692
+ return [
4693
+ `deployer ${VERSION} \u2014 build Docker images, push them, deploy any version`,
4694
+ "",
4695
+ "Usage: deployer [command] [options]",
4696
+ "",
4697
+ "Commands:",
4698
+ ...Object.entries(COMMANDS).map(([name, c2]) => ` ${name.padEnd(width)} ${c2.summary}`),
4699
+ "",
4700
+ "Options:",
4701
+ " -c, --config <file> deployer.json to use (default: nearest one upward; or $DEPLOYER_CONFIG)",
4702
+ " -h, --help help for a command: deployer <command> --help",
4703
+ " -v, --version",
4704
+ "",
4705
+ "Run `deployer` with no command in a terminal for the interactive UI."
4706
+ ].join("\n");
4707
+ }
4708
+ async function main(argv) {
4709
+ let at = -1;
4710
+ for (let i = 0; i < argv.length; i++) {
4711
+ if (argv[i] === "-c" || argv[i] === "--config") {
4712
+ i++;
4713
+ continue;
4714
+ }
4715
+ if (argv[i] === "--") break;
4716
+ if (!argv[i].startsWith("-")) {
4717
+ at = i;
4718
+ break;
4719
+ }
4720
+ }
4721
+ const first = at >= 0 ? argv[at] : void 0;
4722
+ const name = first && COMMANDS[first] ? first : void 0;
4723
+ if (first && !name) throw new DeployerError(`Unknown command "${first}"
4724
+
4725
+ ${help()}`);
4726
+ const rest = name ? argv.filter((_, i) => i !== at) : argv;
4727
+ const def = name ? COMMANDS[name] : void 0;
4728
+ const parsed = parseArgs(rest, { ...GLOBAL, ...def?.flags ?? {} });
4729
+ if (parsed.flags.version) {
4730
+ process.stdout.write(`${VERSION}
4731
+ `);
4732
+ return;
4733
+ }
4734
+ if (parsed.flags.help) {
4735
+ process.stdout.write(def ? `${def.summary}
4736
+
4737
+ Usage: ${def.usage}
4738
+ ${def.details ? `
4739
+ ${def.details}
4740
+ ` : ""}` : `${help()}
4741
+ `);
4742
+ return;
4743
+ }
4744
+ if (!def) {
4745
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
4746
+ process.stdout.write(`${help()}
4747
+ `);
4748
+ return;
4749
+ }
4750
+ await (await Promise.resolve().then(() => (init_tui(), tui_exports))).launch(typeof parsed.flags.config === "string" ? parsed.flags.config : void 0);
4751
+ return;
4752
+ }
4753
+ const handler = await def.run();
4754
+ await handler(parsed);
4755
+ }
4756
+ main(process.argv.slice(2)).catch((err) => {
4757
+ if (err instanceof CancelledError) {
4758
+ printError(err.message);
4759
+ process.exit(130);
4760
+ }
4761
+ if (err instanceof DeployerError) {
4762
+ printError(err.message);
4763
+ process.exit(err.exitCode);
4764
+ }
4765
+ printError(err instanceof Error ? err.stack ?? err.message : String(err));
4766
+ process.exit(1);
4767
+ });