@yunuseon/kayra 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/dist/main.js CHANGED
@@ -2,25 +2,34 @@
2
2
  import { run } from "@optique/run";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { existsSync, readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
5
6
  import { join, resolve } from "node:path";
6
7
  import { absolutePath, fleetRoot, kayraRoot, within } from "./brand.js";
7
8
  import { appCheck } from "./commands/app-check.js";
8
- import { parser } from "./cli.js";
9
+ import { parser, runOptions } from "./cli.js";
9
10
  import { doctor } from "./commands/doctor.js";
10
11
  import * as server from "./commands/server.js";
11
- import { status } from "./commands/status.js";
12
- import { findings, report } from "./commands/validate.js";
12
+ import { look, opentofu, statusJson, statusView } from "./commands/status.js";
13
+ import { findings, overall, validateJson, validateView } from "./commands/validate.js";
13
14
  import { gather } from "./gather.js";
14
15
  import { serverNamed } from "./fleet.js";
15
16
  import { interpret } from "./interpret.js";
16
17
  import { findFleetRoot, loadFleet } from "./load.js";
18
+ import { network } from "./net.js";
17
19
  import { render } from "./plan.js";
18
- import { flatMap, ok } from "./result.js";
20
+ import { flatMap, map, ok } from "./result.js";
21
+ import { explain } from "./ui/explain.js";
22
+ import { bad, paint } from "./ui/line.js";
23
+ import { framed, silent } from "./ui/progress.js";
24
+ import { screen, settle, watch } from "./ui/terminal.js";
25
+ import { truncate } from "./ui/text.js";
26
+ import { z } from "zod";
19
27
  const here = absolutePath(process.cwd());
20
28
  const engine = absolutePath(import.meta.dirname);
21
29
  if (!here.ok || !engine.ok)
22
30
  throw new Error("node reported a relative path");
23
31
  const kayra = kayraRoot(within(engine.value, "..", ".."));
32
+ const version = z.object({ version: z.string() }).parse(JSON.parse(readFileSync(join(kayra, "package.json"), "utf8"))).version;
24
33
  const appKinds = { "app runs": "runs", "app logs": "logs", "app deploy": "deploy", "app rollback": "rollback" };
25
34
  const isDeployer = (command) => command.name === "job" || command.name in appKinds;
26
35
  const deployerCommand = (command) => command.name === "job"
@@ -68,33 +77,77 @@ const plan = (fleet, command) => {
68
77
  }
69
78
  return flatMap(serverNamed(fleet, command.server), (target) => onServer(on, target, command));
70
79
  };
80
+ const screens = { out: screen(process.stdout, process.env), err: screen(process.stderr, process.env) };
71
81
  const io = {
72
- out: (line) => {
73
- console.log(line);
82
+ out: (text) => {
83
+ console.log(paint(text, screens.out.colors, screens.out.links));
74
84
  },
75
- err: (line) => {
76
- console.error(line);
85
+ err: (text) => {
86
+ console.error(paint(text, screens.err.colors, screens.err.links));
77
87
  },
78
88
  ask: async (prompt) => {
79
89
  const terminal = createInterface({ input: process.stdin, output: process.stderr });
80
- const answer = await terminal.question(prompt);
90
+ // Ctrl-C at the prompt, or no more input: no answer, so nothing happens.
91
+ const answer = await new Promise((resolve) => {
92
+ terminal.once("SIGINT", () => {
93
+ resolve("");
94
+ });
95
+ terminal.once("close", () => {
96
+ resolve("");
97
+ });
98
+ void terminal.question(paint(prompt, screens.err.colors)).then(resolve, () => {
99
+ resolve("");
100
+ });
101
+ });
81
102
  terminal.close();
82
103
  return answer;
83
104
  },
84
105
  };
85
106
  const fail = (message) => {
86
- console.error(`kayra: ${message}`);
107
+ io.err(screens.err.live ? [bad("✗"), " ", message] : `kayra: ${message}`);
87
108
  process.exit(1);
88
109
  };
110
+ /** The heading's facts: what the server is, and which kayra runs. */
111
+ const invocation = (target) => ({
112
+ command: ["kayra", ...process.argv.slice(2).filter((word) => word !== "--dry-run")].join(" "),
113
+ ...(target === undefined ? {} : { server: target.name }),
114
+ about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
115
+ });
116
+ /** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
117
+ const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
118
+ /** --dry-run: the plan as data, styled on a terminal, plain and copyable for a program. */
119
+ const show = (steps, about, short) => {
120
+ (screens.out.live ? explain(about, steps, short, screens.out.columns) : render(steps)).forEach(io.out);
121
+ };
122
+ /** Runs a plan, framed on stderr unless its output is the point; the exit status says how it went. */
123
+ const execute = async (steps, about, framing) => {
124
+ const interrupt = new AbortController();
125
+ // Ctrl-C reaches the step's program too; the plan stops once it gives up. A second one does not wait.
126
+ process.once("SIGINT", () => {
127
+ interrupt.abort();
128
+ process.once("SIGINT", () => process.exit(130));
129
+ });
130
+ const progress = framing
131
+ ? framed(screens.err, (raw) => process.stderr.write(raw), about)
132
+ : silent;
133
+ const passed = await interpret(steps, io, progress, () => interrupt.signal.aborted);
134
+ // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
135
+ process.exitCode = interrupt.signal.aborted ? 130 : passed ? 0 : 1;
136
+ };
89
137
  const found = flatMap(findFleetRoot(here.value), loadFleet);
90
138
  // Outside a fleet only `app check` runs: it works in an app's repository.
91
139
  const fleet = found.ok ? found : ok({ root: fleetRoot(here.value), servers: [] });
92
140
  if (!fleet.ok)
93
141
  fail(fleet.error);
94
142
  else {
95
- const args = run(parser(fleet.value), { programName: "kayra", help: "both", completion: "both" });
143
+ const args = run(parser(fleet.value), runOptions(version));
96
144
  if (!found.ok && args.command.name !== "app check")
97
145
  fail(found.error);
146
+ const short = shortener([
147
+ [kayra, "<kayra>"],
148
+ ...(found.ok ? [[fleet.value.root, "<fleet>"]] : []),
149
+ [homedir(), "~"],
150
+ ]);
98
151
  if (args.command.name === "app check") {
99
152
  const root = absolutePath(resolve(here.value, args.command.dir ?? "."));
100
153
  const manifestPath = root.ok ? join(root.value, "app.yml") : "";
@@ -102,32 +155,41 @@ else {
102
155
  if (!steps.ok)
103
156
  fail(steps.error);
104
157
  else if (args.dryRun)
105
- render(steps.value).forEach(io.out);
106
- // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
158
+ show(steps.value, invocation(undefined), short);
107
159
  else
108
- process.exitCode = (await interpret(steps.value, io)) ? 0 : 1;
160
+ await execute(steps.value, invocation(undefined), true);
109
161
  }
110
162
  else if (args.command.name === "status") {
111
- (await status(fleet.value)).forEach(io.out);
163
+ const { json, offline } = args.command;
164
+ const { initial, updates } = look(fleet.value, opentofu, offline ? undefined : network(2_000));
165
+ // On a terminal the table is there at once, its cells filled in as the answers arrive; the report itself goes to stdout.
166
+ const draw = (looks, frame) => statusView(looks, { frame, room: screens.err.columns - 1, offline }).map((line) => paint(truncate(line, screens.err.columns - 1), screens.err.colors));
167
+ const looks = !json && screens.out.live && screens.err.live
168
+ ? await watch((raw) => process.stderr.write(raw), initial, updates, draw)
169
+ : await settle(initial, updates);
170
+ (json
171
+ ? [JSON.stringify(statusJson(looks), null, 2)]
172
+ : statusView(looks, { frame: "", room: screens.out.live ? screens.out.columns : Infinity, offline })).forEach(io.out);
112
173
  }
113
174
  else if (args.command.name === "validate") {
114
- const chosen = args.command.server;
175
+ const { server: chosen, json } = args.command;
115
176
  const servers = fleet.value.servers.filter((each) => chosen === undefined || each.name === chosen);
116
- const reports = await Promise.all(servers.map(async (each) => findings(await gather(fleet.value.root, each))));
117
- reports.forEach((found, index) => {
118
- report(servers[index]?.name ?? "", found).forEach(io.out);
119
- });
177
+ const reports = await Promise.all(servers.map(async (each) => ({ server: each, findings: findings(await gather(fleet.value.root, each)) })));
178
+ (json ? [JSON.stringify(validateJson(reports), null, 2)] : validateView(reports)).forEach(io.out);
120
179
  // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
121
- process.exitCode = reports.some((found) => found.some((each) => each.problem)) ? 1 : 0;
180
+ process.exitCode = reports.some((each) => overall(each.findings) === "problem") ? 1 : 0;
122
181
  }
123
182
  else {
124
- const steps = plan(fleet.value, args.command);
183
+ const { command } = args;
184
+ const steps = map(plan(fleet.value, command), (each) => (args.verbose ? server.verbose(each) : each));
185
+ const target = "server" in command ? fleet.value.servers.find((each) => each.name === command.server) : undefined;
186
+ // ssh and the deployer's answers are the output itself: nothing around them.
187
+ const framing = command.name !== "ssh" && !isDeployer(command);
125
188
  if (!steps.ok)
126
189
  fail(steps.error);
127
190
  else if (args.dryRun)
128
- render(steps.value).forEach(io.out);
129
- // eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
191
+ show(steps.value, invocation(target), short);
130
192
  else
131
- process.exitCode = (await interpret(steps.value, io)) ? 0 : 1;
193
+ await execute(steps.value, invocation(target), framing);
132
194
  }
133
195
  }
@@ -0,0 +1,52 @@
1
+ import { Agent, request } from "node:https";
2
+ import { connect } from "node:net";
3
+ import { getCACertificates } from "node:tls";
4
+ import { failure } from "./commands/status.js";
5
+ const codeOf = (error) => typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "ERROR";
6
+ const since = (started) => Math.round(performance.now() - started);
7
+ /** The network, as status asks it: a TCP connect, an HTTPS GET, each given up after `ms`; every answer a Reach, never an exception. */
8
+ export const network = (ms) => {
9
+ // A multipass server's certificates are mkcert's, whose root is in the system's store, not Node's.
10
+ // Reading it takes a while: after the first frame, not before.
11
+ const agent = new Promise((resolve) => {
12
+ setImmediate(() => {
13
+ resolve(new Agent({ ca: [...new Set([...getCACertificates("default"), ...getCACertificates("system")])] }));
14
+ });
15
+ });
16
+ return {
17
+ connect: (host, port) => new Promise((resolve) => {
18
+ const started = performance.now();
19
+ const socket = connect({ host, port, timeout: ms });
20
+ socket.once("connect", () => {
21
+ socket.destroy();
22
+ resolve({ kind: "open", ms: since(started) });
23
+ });
24
+ socket.once("timeout", () => {
25
+ socket.destroy();
26
+ resolve({ kind: "no-answer" });
27
+ });
28
+ socket.once("error", (error) => {
29
+ resolve(failure(codeOf(error)));
30
+ });
31
+ }),
32
+ get: async (url) => {
33
+ const via = await agent;
34
+ return new Promise((resolve) => {
35
+ const started = performance.now();
36
+ const asked = request(url, { agent: via, timeout: ms }, (response) => {
37
+ response.resume();
38
+ resolve({ kind: "answered", status: response.statusCode ?? 0, ms: since(started) });
39
+ asked.destroy();
40
+ });
41
+ asked.once("timeout", () => {
42
+ asked.destroy();
43
+ resolve({ kind: "no-answer" });
44
+ });
45
+ asked.once("error", (error) => {
46
+ resolve(failure(codeOf(error)));
47
+ });
48
+ asked.end();
49
+ });
50
+ },
51
+ };
52
+ };
package/cli/dist/plan.js CHANGED
@@ -1,5 +1,6 @@
1
- export const run = (argv, env = {}) => ({
1
+ export const run = (title, argv, env = {}) => ({
2
2
  kind: "run",
3
+ title,
3
4
  argv,
4
5
  env,
5
6
  stdout: "show",
@@ -16,16 +17,46 @@ const arg = (value) => {
16
17
  return value.words === "one" ? `"${command}"` : command;
17
18
  };
18
19
  const describeProbe = (probe) => probe.kind === "on-path" ? `command -v ${quote(probe.program)}` : assignments(probe.env) + shell(probe.argv);
20
+ /** Every step of a plan as part of one kayra command. */
21
+ export const partOf = (part, plan) => plan.map((step) => ({ ...step, part }));
22
+ /** guard, check, run, confirm or note: what kind of step it is, as --dry-run says. */
23
+ export const kindOf = (step) => (step.kind === "check" ? (step.onFailure === "stop" ? "guard" : "check") : step.kind);
24
+ /** What it is called while it runs; a confirmation and a note say what they say. */
25
+ export const titleOf = (step) => {
26
+ switch (step.kind) {
27
+ case "run":
28
+ return step.title;
29
+ case "check":
30
+ return step.label;
31
+ case "confirm":
32
+ return step.warning;
33
+ case "note":
34
+ return step.text;
35
+ }
36
+ };
37
+ /** The shell command a step runs, or undefined if it runs none. */
38
+ export const commandOf = (step) => {
39
+ switch (step.kind) {
40
+ case "run":
41
+ return `${assignments(step.env)}${step.argv.map(arg).join(" ")}${step.stdout === "discard" ? " >/dev/null" : ""}`;
42
+ case "check":
43
+ return describeProbe(step.probe);
44
+ case "confirm":
45
+ case "note":
46
+ return undefined;
47
+ }
48
+ };
19
49
  const describe = (step) => {
20
50
  switch (step.kind) {
21
51
  case "run":
22
- return `run ${assignments(step.env)}${step.argv.map(arg).join(" ")}${step.stdout === "discard" ? " >/dev/null" : ""}`;
52
+ return `run ${commandOf(step) ?? ""}`;
23
53
  case "check":
24
- return `${step.onFailure === "stop" ? "guard " : "check "} ${step.label}: ${describeProbe(step.probe)}`;
54
+ return `${kindOf(step).padEnd(8)} ${step.label}: ${commandOf(step) ?? ""}`;
25
55
  case "confirm":
26
- return `confirm ${step.prompt}(${step.expect})`;
56
+ return `confirm ${step.warning} (${step.expect})`;
27
57
  case "note":
28
58
  return `note ${step.text}`;
29
59
  }
30
60
  };
61
+ /** The plan as plain lines: --dry-run's output where it is read by a program. */
31
62
  export const render = (plan) => plan.map(describe);
@@ -0,0 +1,37 @@
1
+ import { commandOf, kindOf, titleOf } from "../plan.js";
2
+ import { accent, active, bad, muted, strong, warn } from "./line.js";
3
+ import { position, steps as count } from "./progress.js";
4
+ import { wrap } from "./text.js";
5
+ import { drawnAs } from "./views.js";
6
+ const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
7
+ const tag = (step) => {
8
+ const kind = kindOf(step);
9
+ return (kinds[kind] ?? muted)(kind.padEnd(7));
10
+ };
11
+ /**
12
+ * --dry-run on a terminal: each step numbered, with its title and, below it, the
13
+ * command it runs. `short` names paths by their root (<kayra>, <fleet>, ~), so a
14
+ * command fits on a line or two; render() is the plain, copyable form.
15
+ */
16
+ export const explain = (invocation, plan, short, columns) => {
17
+ const digits = String(plan.length).length;
18
+ const indent = " ".repeat(digits + 13);
19
+ const steps = plan.flatMap((step, index) => {
20
+ const { opens } = position(plan, index);
21
+ const command = commandOf(step);
22
+ return [
23
+ ...(opens === undefined ? [] : index === 0 ? [[accent(opens)]] : [[], [accent(opens)]]),
24
+ [" ", muted(String(index + 1).padStart(digits)), " ", tag(step), " ", strong(titleOf(step))],
25
+ ...(step.kind === "confirm" ? [[indent, muted(`asks for '${step.expect}' to be typed, or stops`)]] : []),
26
+ ...(command === undefined
27
+ ? []
28
+ : wrap(short(command).split(" "), Math.max(40, Math.min(columns, 120) - indent.length - 2)).map((line, at) => [indent, muted(at === 0 ? line : ` ${line}`)])),
29
+ ...(step.kind === "run" && typeof step.stdout === "object" ? [[indent, muted(`→ ${drawnAs(step.stdout)}`)]] : []),
30
+ ];
31
+ });
32
+ return [
33
+ [strong(invocation.command), muted([...invocation.about, count(plan), "dry run: nothing runs"].map((each) => ` · ${each}`).join(""))],
34
+ [],
35
+ ...steps,
36
+ ];
37
+ };
@@ -0,0 +1,39 @@
1
+ import { styleText } from "node:util";
2
+ import { escapes } from "./terminal.js";
3
+ const toned = (tone) => (text) => ({ tone, text });
4
+ export const ok = toned("ok");
5
+ export const bad = toned("bad");
6
+ export const warn = toned("warn");
7
+ export const active = toned("active");
8
+ export const muted = toned("muted");
9
+ export const strong = toned("strong");
10
+ export const accent = toned("accent");
11
+ export const link = (text, href, tone) => ({ text, href, ...(tone === undefined ? {} : { tone }) });
12
+ const looks = {
13
+ ok: ["green"],
14
+ bad: ["red"],
15
+ warn: ["yellow"],
16
+ active: ["cyan"],
17
+ muted: ["dim"],
18
+ strong: ["bold"],
19
+ accent: ["magenta", "bold"],
20
+ };
21
+ const spans = (text) => (typeof text === "string" ? [text] : text);
22
+ const textOf = (span) => (typeof span === "string" ? span : span.text);
23
+ export const flat = (text) => spans(text).map(textOf).join("");
24
+ const graphemes = new Intl.Segmenter();
25
+ /** A string's characters as a reader counts them. */
26
+ export const characters = (text) => Array.from(graphemes.segment(text), (each) => each.segment);
27
+ /** Columns it takes: one per character, which holds for everything kayra writes itself. */
28
+ export const width = (text) => characters(flat(text)).length;
29
+ export const paint = (text, colors, links = false) => spans(text)
30
+ .map((span) => {
31
+ if (typeof span === "string")
32
+ return span;
33
+ const { tone, href } = span;
34
+ const styled = colors && tone !== undefined
35
+ ? looks[tone].reduce((so, format) => styleText(format, so, { validateStream: false }), span.text)
36
+ : span.text;
37
+ return links && href !== undefined ? escapes.link(styled, href) : styled;
38
+ })
39
+ .join("");
@@ -0,0 +1,100 @@
1
+ import { titleOf } from "../plan.js";
2
+ import { accent, active, bad, muted, ok, paint, strong, warn } from "./line.js";
3
+ import { escapes, spinner } from "./terminal.js";
4
+ import { duration, spread, truncate } from "./text.js";
5
+ /** Nothing around the steps: for commands whose output is the point (ssh, logs), and for tests. */
6
+ export const silent = {
7
+ plan: (_plan, work) => work(),
8
+ step: (_step, _at, work) => work(),
9
+ };
10
+ const parts = (plan) => [...new Set(plan.flatMap((step) => (step.part === undefined ? [] : [step.part])))];
11
+ /** Where the step at `index` is, for a plan that may consist of several parts. */
12
+ export const position = (plan, index) => {
13
+ const part = plan[index]?.part;
14
+ const opens = part !== undefined && parts(plan).length > 1 && plan[index - 1]?.part !== part;
15
+ return { index, total: plan.length, ...(opens ? { opens: part } : {}) };
16
+ };
17
+ /** A run of this long earns a notification when it ends: the operator has looked away. */
18
+ const worthNotifying = 30_000;
19
+ /** "8 steps", or "15 checks" for a plan of nothing else (doctor). */
20
+ export const steps = (plan) => {
21
+ const noun = plan.every((step) => step.kind === "check") ? "check" : "step";
22
+ return `${String(plan.length)} ${noun}${plan.length === 1 ? "" : "s"}`;
23
+ };
24
+ /** The footer: how it went, how long it took, and what reruns a failed part alone. */
25
+ export const footer = (invocation, plan, ended, ms) => {
26
+ const took = duration(ms);
27
+ const { command } = invocation;
28
+ const { stop } = ended;
29
+ if (stop === undefined)
30
+ return ended.failures === 0
31
+ ? [[ok("✓"), " ", strong(command), muted(` · ${steps(plan)} · ${took}`)]]
32
+ : [[bad("✗"), " ", strong(command), muted(` · ${String(ended.failures)} of ${steps(plan)} failed · ${took}`)]];
33
+ const where = `step ${String(stop.index + 1)} of ${String(plan.length)}`;
34
+ if (stop.why === "declined")
35
+ return [[warn("■"), " ", strong(command), muted(` stopped at ${where}: not confirmed`)]];
36
+ if (stop.why === "interrupted")
37
+ return [[warn("■"), " ", strong(command), muted(` interrupted at ${where} · ${took}`)]];
38
+ const { part } = stop.step;
39
+ const alone = part !== undefined && parts(plan).length > 1 && invocation.server !== undefined;
40
+ return [
41
+ [bad("✗"), " ", strong(command), " failed at ", strong(titleOf(stop.step)), muted(` · ${where} · ${took}`)],
42
+ ...(alone ? [[" ", active("→"), " ", strong(`kayra ${part} ${invocation.server ?? ""}`), muted(" runs just this part")]] : []),
43
+ ];
44
+ };
45
+ /** Frames on stderr: a heading, each step as it runs and how it went, a footer; on a terminal also spinners, the window title, a notification. */
46
+ export const framed = (screen, write, invocation) => {
47
+ const columns = Math.min(screen.columns, 80);
48
+ const say = (text) => {
49
+ write(`${paint(text, screen.colors)}\n`);
50
+ };
51
+ const tell = (raw, when) => {
52
+ if (when)
53
+ write(raw);
54
+ };
55
+ return {
56
+ plan: async (plan, work) => {
57
+ const started = performance.now();
58
+ tell(escapes.pushTitle + escapes.title(invocation.command), screen.title);
59
+ say([strong(invocation.command), muted([...invocation.about, steps(plan)].map((each) => ` · ${each}`).join(""))]);
60
+ say("");
61
+ const ended = await work();
62
+ const ms = performance.now() - started;
63
+ say("");
64
+ footer(invocation, plan, ended, ms).forEach(say);
65
+ tell(escapes.popTitle, screen.title);
66
+ tell(escapes.progressDone, screen.progressBar);
67
+ const failed = ended.failures > 0 || ended.stop?.why === "failed";
68
+ tell(escapes.notify(`${invocation.command} ${failed ? "failed" : "is done"} after ${duration(ms)}`), screen.notifications && ms >= worthNotifying);
69
+ return ended;
70
+ },
71
+ step: async (step, at, work) => {
72
+ if (step.kind === "confirm" || step.kind === "note")
73
+ return work();
74
+ if (at.opens !== undefined) {
75
+ if (at.index > 0)
76
+ say("");
77
+ say([accent(at.opens)]);
78
+ }
79
+ const title = titleOf(step);
80
+ const counter = `${String(at.index + 1)}/${String(at.total)}`;
81
+ tell(escapes.title(`${invocation.command} · ${counter} ${title}`), screen.title);
82
+ tell(escapes.progress((at.index / at.total) * 100), screen.progressBar);
83
+ const shown = step.kind === "run" && step.stdout === "show";
84
+ if (shown)
85
+ say(spread([" ", active("◆"), " ", strong(title)], [muted(counter)], columns));
86
+ const stop = !shown && screen.live
87
+ ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(ms))], columns), screen.colors))
88
+ : () => undefined;
89
+ const started = performance.now();
90
+ const done = await work();
91
+ stop();
92
+ // A diagnosis reports itself on stdout: that line is doctor's output.
93
+ if (step.kind === "check" && step.onFailure === "continue")
94
+ return done;
95
+ const took = duration(performance.now() - started);
96
+ say(spread([" ", done.failed ? bad("✗") : ok("✓"), " ", title], [muted(done.why === undefined ? took : `${done.why} · ${took}`)], columns));
97
+ return done;
98
+ },
99
+ };
100
+ };
@@ -0,0 +1,93 @@
1
+ /** Optique's rule too, so help and kayra agree: a nonempty FORCE_COLOR, else no NO_COLOR, then a terminal. */
2
+ export const colors = (tty, env) => {
3
+ if ((env["FORCE_COLOR"] ?? "") !== "")
4
+ return true;
5
+ if ((env["NO_COLOR"] ?? "") !== "" || env["NODE_DISABLE_COLORS"] !== undefined)
6
+ return false;
7
+ return tty && env["TERM"] !== "dumb";
8
+ };
9
+ // OSC 9 is a notification in these, and OSC 9;4 a progress bar in some; elsewhere either may print as text.
10
+ const notifying = ["iTerm.app", "WezTerm", "ghostty"];
11
+ const showingProgress = ["WezTerm", "ghostty"];
12
+ const linking = ["iTerm.app", "WezTerm", "ghostty", "vscode"];
13
+ export const screen = (stream, env) => {
14
+ const tty = stream.isTTY === true;
15
+ const live = tty && env["TERM"] !== "dumb" && (env["CI"] ?? "") === "";
16
+ const program = env["TERM_PROGRAM"] ?? "";
17
+ // tmux and screen swallow what they do not know, or pass it to the wrong pane.
18
+ const direct = live && env["TMUX"] === undefined && env["STY"] === undefined;
19
+ return {
20
+ colors: colors(tty, env),
21
+ live,
22
+ // A pseudo-terminal may report 0.
23
+ columns: stream.columns !== undefined && stream.columns > 0 ? stream.columns : Number(env["COLUMNS"]) || 80,
24
+ title: live,
25
+ notifications: direct && notifying.includes(program),
26
+ progressBar: direct && (showingProgress.includes(program) || env["WT_SESSION"] !== undefined),
27
+ links: direct && linking.includes(program),
28
+ };
29
+ };
30
+ const printable = (text) => text.replace(/\p{Cc}/gu, " ");
31
+ const osc = (body) => `\u001b]${body}\u0007`;
32
+ export const escapes = {
33
+ clearLine: "\r\u001b[2K",
34
+ /** xterm's title stack: the shell's title comes back when kayra is done. */
35
+ pushTitle: "\u001b[22;0t",
36
+ popTitle: "\u001b[23;0t",
37
+ title: (text) => osc(`0;${printable(text)}`),
38
+ notify: (text) => osc(`9;${printable(text)}`),
39
+ progress: (percent) => osc(`9;4;1;${String(Math.round(percent))}`),
40
+ progressDone: osc("9;4;0;0"),
41
+ link: (text, href) => `${osc(`8;;${printable(href)}`)}${text}${osc("8;;")}`,
42
+ /** To the start of the line `count` lines up; nothing for none, since CSI 0 F still moves one. */
43
+ up: (count) => (count > 0 ? `\u001b[${String(count)}F` : ""),
44
+ clearDown: "\u001b[J",
45
+ };
46
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
47
+ const frameOf = (ms) => frames[Math.floor(ms / 80) % frames.length] ?? "";
48
+ /** Draws a line in place, again every frame, until stopped; stopping clears it. */
49
+ export const spinner = (write, draw) => {
50
+ const started = performance.now();
51
+ const frame = () => {
52
+ const ms = performance.now() - started;
53
+ write(`${escapes.clearLine}${draw(frameOf(ms), ms)}`);
54
+ };
55
+ frame();
56
+ const timer = setInterval(frame, 80);
57
+ return () => {
58
+ clearInterval(timer);
59
+ write(escapes.clearLine);
60
+ };
61
+ };
62
+ const tick = (ms) => new Promise((resolve) => {
63
+ setTimeout(() => {
64
+ resolve(undefined);
65
+ }, ms);
66
+ });
67
+ /**
68
+ * Draws a block of lines in place, again every frame and as each update lands,
69
+ * until all have; then clears it and returns the state they made. Each line
70
+ * must fit the terminal: one that wraps throws the redraw off.
71
+ */
72
+ export const watch = async (write, initial, updates, draw) => {
73
+ const started = performance.now();
74
+ const redraw = (state, drawn) => {
75
+ const lines = draw(state, frameOf(performance.now() - started));
76
+ write(`${escapes.up(drawn)}${lines.map((line) => `${escapes.clearLine}${line}\n`).join("")}${escapes.clearDown}`);
77
+ return lines.length;
78
+ };
79
+ const go = async (state, waiting, drawn) => {
80
+ const shown = redraw(state, drawn);
81
+ if (waiting.length === 0) {
82
+ write(`${escapes.up(shown)}${escapes.clearDown}`);
83
+ return state;
84
+ }
85
+ const next = await Promise.race([...waiting.map((each) => each.landed), tick(80)]);
86
+ return next === undefined
87
+ ? go(state, waiting, shown)
88
+ : go(next.update(state), waiting.filter((each) => each.id !== next.id), shown);
89
+ };
90
+ return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })), 0);
91
+ };
92
+ /** What watch() returns, drawn nowhere: for a stream that is no terminal. */
93
+ export const settle = async (initial, updates) => (await Promise.all(updates)).reduce((state, update) => update(state), initial);
@@ -0,0 +1,71 @@
1
+ import { characters, width } from "./line.js";
2
+ /** 0.4s, 12s, 2m03s, 1h04m: never more precise than it is worth reading. */
3
+ export const duration = (ms) => {
4
+ const seconds = Math.max(0, ms) / 1000;
5
+ if (seconds < 10)
6
+ return `${(Math.floor(seconds * 10) / 10).toFixed(1)}s`;
7
+ if (seconds < 60)
8
+ return `${String(Math.floor(seconds))}s`;
9
+ const minutes = Math.floor(seconds / 60);
10
+ if (minutes < 60)
11
+ return `${String(minutes)}m${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;
12
+ return `${String(Math.floor(minutes / 60))}h${String(minutes % 60).padStart(2, "0")}m`;
13
+ };
14
+ /** `left`, then `right` flush with the last column, at least two spaces apart. */
15
+ export const spread = (left, right, columns) => [
16
+ ...left,
17
+ " ".repeat(Math.max(2, columns - width(left) - width(right))),
18
+ ...right,
19
+ ];
20
+ /** At most `columns` wide, cut with an ellipsis: a line redrawn in place must not wrap. */
21
+ export const truncate = (line, columns) => {
22
+ if (width(line) <= columns)
23
+ return line;
24
+ const cut = line.reduce((so, span) => {
25
+ const text = typeof span === "string" ? span : span.text;
26
+ const chars = characters(text);
27
+ const kept = chars.slice(0, Math.max(0, so.room)).join("");
28
+ const piece = typeof span === "string" ? kept : { ...span, text: kept };
29
+ return { kept: kept === "" ? so.kept : [...so.kept, piece], room: so.room - chars.length };
30
+ }, { kept: [], room: columns - 1 });
31
+ return [...cut.kept, "…"];
32
+ };
33
+ /** Words in lines of at most `columns`; a word longer than that gets a line of its own. */
34
+ export const wrap = (words, columns) => words.reduce((lines, word) => {
35
+ const last = lines.at(-1);
36
+ if (last === undefined)
37
+ return [word];
38
+ return characters(last).length + 1 + characters(word).length <= columns ? [...lines.slice(0, -1), `${last} ${word}`] : [...lines, word];
39
+ }, []);
40
+ /** How long ago, as a reader rounds it: 45s ago, 12m ago, 30h ago, 3d ago. */
41
+ export const ago = (ms) => {
42
+ const seconds = Math.floor(Math.max(0, ms) / 1000);
43
+ if (seconds < 60)
44
+ return `${String(seconds)}s ago`;
45
+ const minutes = Math.floor(seconds / 60);
46
+ if (minutes < 60)
47
+ return `${String(minutes)}m ago`;
48
+ const hours = Math.floor(minutes / 60);
49
+ return hours < 48 ? `${String(hours)}h ago` : `${String(Math.floor(hours / 24))}d ago`;
50
+ };
51
+ /** Rows of cells in columns as wide as their widest cell, two spaces apart; nothing trails a row's last cell. */
52
+ export const table = (rows) => {
53
+ const filled = rows.map((row) => row.slice(0, row.findLastIndex((cell) => width(cell) > 0) + 1));
54
+ const widths = filled.reduce((most, row) => Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? []))), []);
55
+ return filled.map((row) => row.flatMap((cell, at) => (at === row.length - 1 ? cell : [...cell, " ".repeat((widths[at] ?? 0) - width(cell) + 2)])));
56
+ };
57
+ /**
58
+ * Rows for table() that fit `room` columns: the cells of the columns in
59
+ * `shrink` cut, in that order, each to no less than its first row's (the
60
+ * heading's) width.
61
+ */
62
+ export const fit = (rows, room, shrink) => {
63
+ const widths = rows.reduce((most, row) => Array.from({ length: Math.max(most.length, row.length) }, (_, at) => Math.max(most[at] ?? 0, width(row[at] ?? []))), []);
64
+ const over = widths.reduce((sum, each) => sum + each, 0) + 2 * Math.max(0, widths.length - 1) - room;
65
+ const cut = shrink.reduce((so, at) => {
66
+ const now = so.widths[at] ?? 0;
67
+ const less = Math.min(Math.max(0, so.over), Math.max(0, now - width(rows[0]?.[at] ?? [])));
68
+ return { widths: so.widths.with(at, now - less), over: so.over - less };
69
+ }, { widths, over }).widths;
70
+ return rows.map((row) => row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))));
71
+ };