ostia 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/live.ts ADDED
@@ -0,0 +1,965 @@
1
+ // Output that moves while a tool works: a task list, a status line
2
+ // pinned under a log, the ready and waiting lines, and Ctrl-C handled
3
+ // as a result. Each component renders its data to lines in a pure
4
+ // function and a small driver writes them, so the lines are tested
5
+ // without a terminal. Like terminal.ts, a package carries an identical
6
+ // copy, beside its copy of terminal.ts, and it runs on Node as on Bun.
7
+ import {
8
+ aligned,
9
+ cursorHidden,
10
+ fitWidth,
11
+ type Glyphs,
12
+ hideCursor,
13
+ isDumb,
14
+ type KeyHint,
15
+ keyHints,
16
+ markOf,
17
+ MEASURE,
18
+ type Paint,
19
+ plural,
20
+ SEPARATOR,
21
+ showCursor,
22
+ textWidth,
23
+ truncateWords,
24
+ } from "./terminal.ts";
25
+
26
+ export {
27
+ ASCII_GLYPHS,
28
+ type Glyphs,
29
+ type KeyHint,
30
+ keyHints,
31
+ UNICODE_GLYPHS,
32
+ wantsAscii,
33
+ } from "./terminal.ts";
34
+
35
+ type Env = Readonly<Record<string, string | undefined>>;
36
+
37
+ // A coding agent and a log file read every frame a redraw writes, and
38
+ // TERM=dumb knows no cursor movement, so each gets plain lines instead.
39
+ /** Whether a live view redraws in place, from where its stream goes. */
40
+ export const wantsRedraw = (
41
+ terminal: boolean,
42
+ env: Env,
43
+ agent: boolean,
44
+ ): boolean => terminal && !agent && !isDumb(env);
45
+
46
+ // A line that appears and vanishes within 300 ms reads as a glitch;
47
+ // 10 frames a second looks alive and costs little; and seconds counted
48
+ // before one would only flicker.
49
+ /**
50
+ * When live output appears, how often it redraws, and when it
51
+ * counts seconds.
52
+ */
53
+ export const TIMING = {
54
+ showAfterMs: 300,
55
+ frameMs: 100,
56
+ countAfterMs: 1000,
57
+ } as const;
58
+
59
+ /**
60
+ * Formats a finished step's time at three significant figures: `812 ms`,
61
+ * `1.23 s`, `2 min 5 s`.
62
+ */
63
+ export function formatDuration(ms: number): string {
64
+ if (Math.round(ms) < 1000) return `${Math.round(ms)} ms`;
65
+ const seconds = (ms / 1000).toPrecision(3);
66
+ if (Number(seconds) < 100) return `${seconds} s`;
67
+ return minutes(Math.round(ms / 1000));
68
+ }
69
+
70
+ const minutes = (seconds: number) =>
71
+ `${Math.floor(seconds / 60)} min ${seconds % 60} s`;
72
+
73
+ // Whole seconds while it runs, since a tenth that changes every frame
74
+ // is motion that says nothing.
75
+ const formatElapsed = (ms: number) => {
76
+ const seconds = Math.floor(ms / 1000);
77
+ return seconds < 100 ? `${seconds} s` : minutes(seconds);
78
+ };
79
+
80
+ /** What a component draws with: the colors, the glyphs and the width. */
81
+ export type Look = { paint: Paint; glyphs: Glyphs; columns: number };
82
+
83
+ /** A key a person can press, and what it does: terminal.ts's KeyHint. */
84
+ export type Key = KeyHint;
85
+
86
+ /** One task of a task list, in one of its five states. */
87
+ export type Task =
88
+ | { name: string; status: "pending" }
89
+ | { name: string; status: "running"; startedMs: number; detail?: string }
90
+ | {
91
+ name: string;
92
+ status: "done" | "failed";
93
+ tookMs: number;
94
+ detail?: string;
95
+ }
96
+ | { name: string; status: "skipped"; detail?: string };
97
+
98
+ /** The moment a frame shows: the clock, and the spinner's frame. */
99
+ export type Moment = { nowMs: number; frame: number };
100
+
101
+ const asIs = (text: string) => text;
102
+
103
+ type Cell = readonly [text: string, paint: (text: string) => string];
104
+
105
+ // The glyph and the name are one cell, a space apart, since a second
106
+ // column's gap would set the name adrift from its mark.
107
+ const label = (
108
+ glyph: string,
109
+ paintGlyph: (text: string) => string,
110
+ name: string,
111
+ paintName: (text: string) => string,
112
+ ): Cell => [
113
+ `${glyph} ${name}`,
114
+ () => `${paintGlyph(glyph)} ${paintName(name)}`,
115
+ ];
116
+
117
+ // A label, a time and a detail, so the times line up in a column; a
118
+ // state reads from its glyph's shape, and its color repeats it.
119
+ function taskCells(task: Task, look: Look, moment?: Moment): Cell[] {
120
+ const { paint, glyphs } = look;
121
+ switch (task.status) {
122
+ case "pending":
123
+ return [label(glyphs.pending, paint.dim, task.name, paint.dim)];
124
+ case "running": {
125
+ const ms = moment === undefined ? 0 : moment.nowMs - task.startedMs;
126
+ const spinner = glyphs.spinner;
127
+ const frame = spinner[(moment?.frame ?? 0) % spinner.length] ?? "";
128
+ return [
129
+ label(frame, asIs, task.name, asIs),
130
+ [ms >= TIMING.countAfterMs ? formatElapsed(ms) : "", paint.dim],
131
+ [task.detail ?? "", paint.dim],
132
+ ];
133
+ }
134
+ case "done":
135
+ return [
136
+ label(glyphs.done, paint.good, task.name, asIs),
137
+ [formatDuration(task.tookMs), paint.dim],
138
+ [task.detail ?? "", paint.dim],
139
+ ];
140
+ case "failed":
141
+ return [
142
+ label(glyphs.failed, paint.bad, task.name, asIs),
143
+ [formatDuration(task.tookMs), paint.dim],
144
+ [task.detail ?? "", asIs],
145
+ ];
146
+ case "skipped":
147
+ return [
148
+ label(glyphs.skipped, paint.dim, task.name, paint.dim),
149
+ ["", asIs],
150
+ [task.detail ?? "skipped", paint.dim],
151
+ ];
152
+ default:
153
+ return task satisfies never;
154
+ }
155
+ }
156
+
157
+ const TIME_COLUMN = 1;
158
+ const DETAIL_COLUMN = 2;
159
+
160
+ // A line wider than the terminal wraps, and a redraw that counts lines
161
+ // then erases the wrong ones, so a frame's detail shortens at a word,
162
+ // and anything still too wide is cut.
163
+ function fitCells(rows: readonly Cell[][], columns: number): string[] {
164
+ const plainLines = aligned(
165
+ rows.map((row) => row.map(([text]) => text)),
166
+ [TIME_COLUMN],
167
+ asIs,
168
+ "",
169
+ );
170
+ const fitted = rows.map((row, i) => {
171
+ const over = textWidth(plainLines[i] ?? "") - columns;
172
+ const detail = row[DETAIL_COLUMN];
173
+ if (over <= 0 || detail === undefined) return row;
174
+ const room = textWidth(detail[0]) - over;
175
+ const shorter = room >= 4 ? truncateWords(detail[0], room) : "";
176
+ return row.with(DETAIL_COLUMN, [shorter, detail[1]]);
177
+ });
178
+ return aligned(
179
+ fitted.map((row) => row.map(([text, paint]) => paint(text))),
180
+ [TIME_COLUMN],
181
+ asIs,
182
+ "",
183
+ ).map((line) => cutLine(line, columns));
184
+ }
185
+
186
+ // eslint-disable-next-line no-control-regex -- escape codes are what it skips
187
+ const SGR = /^\x1b\[[0-9;]*m/;
188
+ // eslint-disable-next-line no-control-regex -- escape codes are what it keeps
189
+ const TRAILING_SPACE = / +((?:\x1b\[[0-9;]*m)*)$/;
190
+
191
+ function cutLine(line: string, columns: number): string {
192
+ if (textWidth(line) <= columns) return line;
193
+ let out = "";
194
+ let seen = 0;
195
+ let i = 0;
196
+ while (i < line.length) {
197
+ const code = SGR.exec(line.slice(i));
198
+ if (code) {
199
+ out += code[0];
200
+ i += code[0].length;
201
+ continue;
202
+ }
203
+ const ch = String.fromCodePoint(line.codePointAt(i) ?? 32);
204
+ if (seen + textWidth(ch) > columns - 1) break;
205
+ out += ch;
206
+ seen += textWidth(ch);
207
+ i += ch.length;
208
+ }
209
+ // The ellipsis follows the last word, not a column's gap; and a cut
210
+ // can fall inside a color, which would bleed into what follows.
211
+ const cut = out.replace(TRAILING_SPACE, "$1");
212
+ return line.includes("\x1b") ? `${cut}…\x1b[0m` : `${cut}…`;
213
+ }
214
+
215
+ /**
216
+ * Renders a task list as aligned lines; with a moment, the live frame,
217
+ * and without one, the static record that stays in the scrollback.
218
+ */
219
+ export function renderTasks(
220
+ tasks: readonly Task[],
221
+ look: Look,
222
+ moment?: Moment,
223
+ ): string[] {
224
+ return fitCells(
225
+ tasks.map((task) => taskCells(task, look, moment)),
226
+ look.columns,
227
+ );
228
+ }
229
+
230
+ const finished = (task: Task) =>
231
+ task.status === "done" ||
232
+ task.status === "failed" ||
233
+ task.status === "skipped";
234
+
235
+ const BAR_WIDTH = 20;
236
+
237
+ // Done and to-do differ in shape as well as color, so the bar reads
238
+ // without color too; the count says it in words.
239
+ /**
240
+ * Renders how far a task list is as a bar and
241
+ * a count: `━━━━━━━━──────────── 4 of 10 benchmarks · 1 failed`.
242
+ */
243
+ export function renderTaskBar(
244
+ tasks: readonly Task[],
245
+ look: Look,
246
+ noun = "task",
247
+ ): string {
248
+ const { paint, glyphs } = look;
249
+ const total = tasks.length;
250
+ const ended = tasks.filter(finished).length;
251
+ const failed = tasks.filter((t) => t.status === "failed").length;
252
+ const filled =
253
+ total === 0 ? BAR_WIDTH : Math.round((ended / total) * BAR_WIDTH);
254
+ const bar =
255
+ paint.good(markOf(glyphs, "barDone").repeat(filled)) +
256
+ paint.dim(markOf(glyphs, "barTodo").repeat(BAR_WIDTH - filled));
257
+ const count = `${ended} of ${plural(total, noun)}`;
258
+ const failures =
259
+ failed === 0 ? "" : paint.dim(`${SEPARATOR}${failed} failed`);
260
+ return cutLine(`${bar} ${count}${failures}`, look.columns);
261
+ }
262
+
263
+ /** What a live frame of a task list holds besides its tasks. */
264
+ export type FrameOptions = {
265
+ /**
266
+ * The terminal's height: a list taller than it shows a window around
267
+ * the tasks still running, and how many more are above and below.
268
+ */
269
+ rows?: number;
270
+ /** Draws renderTaskBar under the tasks. */
271
+ bar?: boolean;
272
+ /** What the bar counts. @default "task" */
273
+ noun?: string;
274
+ };
275
+
276
+ // The window starts at the first task still to end, since a queue runs
277
+ // in order, and the ones above have their record to come; a frame never
278
+ // fills the terminal's last row, where the cursor rests.
279
+ function windowOf(
280
+ tasks: readonly Task[],
281
+ room: number,
282
+ ): { start: number; end: number } {
283
+ const count = tasks.length;
284
+ if (count <= room) return { start: 0, end: count };
285
+ const at = tasks.findIndex((t) => !finished(t));
286
+ const first = at === -1 ? count : at;
287
+ const one = Math.max(1, room - 1);
288
+ if (first < one) return { start: 0, end: one };
289
+ if (first >= count - one) return { start: count - one, end: count };
290
+ return { start: first, end: first + Math.max(1, room - 2) };
291
+ }
292
+
293
+ /**
294
+ * Renders a task list's live frame: renderTasks, windowed to fit `rows`,
295
+ * with the bar under it when asked.
296
+ */
297
+ export function renderTaskFrame(
298
+ tasks: readonly Task[],
299
+ look: Look,
300
+ moment: Moment,
301
+ options: FrameOptions = {},
302
+ ): string[] {
303
+ const { paint, glyphs } = look;
304
+ const lines = renderTasks(tasks, look, moment);
305
+ const bar =
306
+ options.bar === true ? [renderTaskBar(tasks, look, options.noun)] : [];
307
+ if (options.rows === undefined) return [...lines, ...bar];
308
+ const room = Math.max(1, options.rows - 1 - bar.length);
309
+ const { start, end } = windowOf(tasks, room);
310
+ const more = (mark: string, n: number) =>
311
+ n > 0 ? [paint.dim(`${mark} ${n} more`)] : [];
312
+ return [
313
+ ...more(markOf(glyphs, "up"), start),
314
+ ...lines.slice(start, end),
315
+ ...more(markOf(glyphs, "down"), tasks.length - end),
316
+ ...bar,
317
+ ];
318
+ }
319
+
320
+ // Unaligned, since piped lines print one at a time as tasks finish, and
321
+ // a program or grep reads each alone.
322
+ /** Renders one finished task as a line for a pipe: `✓ lint · 812 ms`. */
323
+ export function renderTaskLine(task: Task, look: Look): string {
324
+ return taskCells(task, look)
325
+ .flatMap(([text, paint]) => (text === "" ? [] : [paint(text)]))
326
+ .join(SEPARATOR);
327
+ }
328
+
329
+ const markLine = (mark: string, what: string, paint: Paint, detail: string) =>
330
+ `${mark} ${what}${paint.dim(`${SEPARATOR}${detail}`)}`;
331
+
332
+ /**
333
+ * Renders the closing line: what ran, what failed or was skipped, and
334
+ * how long, or, when it was stopped, how far it got.
335
+ */
336
+ export function renderTaskSummary(
337
+ tasks: readonly Task[],
338
+ tookMs: number,
339
+ look: Look,
340
+ options: { noun?: string; stopped?: boolean } = {},
341
+ ): string {
342
+ const { paint, glyphs } = look;
343
+ const noun = options.noun ?? "task";
344
+ const took = formatDuration(tookMs);
345
+ const total = tasks.length;
346
+ const count = (status: Task["status"]) =>
347
+ tasks.filter((t) => t.status === status).length;
348
+ const failed = tasks.filter((t) => t.status === "failed");
349
+ const bad = paint.bad(glyphs.failed);
350
+ if (options.stopped === true) {
351
+ return markLine(
352
+ bad,
353
+ "Stopped",
354
+ paint,
355
+ `${count("done")} of ${plural(total, noun)} done${SEPARATOR}${took}`,
356
+ );
357
+ }
358
+ if (failed.length > 0) {
359
+ const names = truncateWords(failed.map((t) => t.name).join(", "), 40);
360
+ return markLine(
361
+ bad,
362
+ `${failed.length} of ${plural(total, noun)} failed: ${names}`,
363
+ paint,
364
+ took,
365
+ );
366
+ }
367
+ const skipped = count("skipped");
368
+ const ran = total - skipped;
369
+ return markLine(
370
+ paint.good(glyphs.done),
371
+ skipped === 0
372
+ ? `Ran ${plural(total, noun)}`
373
+ : `Ran ${ran} of ${plural(total, noun)}`,
374
+ paint,
375
+ skipped === 0 ? took : `${skipped} skipped${SEPARATOR}${took}`,
376
+ );
377
+ }
378
+
379
+ // A stopped run's record keeps every task, so it shows what never
380
+ // finished as well as what did.
381
+ /** Marks each running task stopped and each pending one not started. */
382
+ export const stopTasks = (tasks: readonly Task[]): Task[] =>
383
+ tasks.map((task) => {
384
+ if (task.status === "running") {
385
+ return { name: task.name, status: "skipped", detail: "stopped" };
386
+ }
387
+ if (task.status === "pending") {
388
+ return { name: task.name, status: "skipped", detail: "not started" };
389
+ }
390
+ return task;
391
+ });
392
+
393
+ // Mode 2026 holds a frame until it's whole, so a terminal that knows it
394
+ // never shows half of one; the rest ignore it.
395
+ const SYNC_START = "\x1b[?2026h";
396
+ const SYNC_END = "\x1b[?2026l";
397
+
398
+ /**
399
+ * Returns the codes that erase a drawn region, `lineCount` lines above
400
+ * the cursor.
401
+ */
402
+ export const erase = (lineCount: number): string =>
403
+ lineCount === 0 ? "" : `\x1b[${lineCount}A\r\x1b[J`;
404
+
405
+ // The cursor rests at the start of the line under the region, so
406
+ // anything else written, a log line or a crash's trace, starts on a line
407
+ // of its own.
408
+ /**
409
+ * Returns the codes that turn the region drawn as `previous` into
410
+ * `next`, rewriting only the lines that changed, so a screen reader
411
+ * hears each line once.
412
+ */
413
+ export function redraw(
414
+ previous: readonly string[],
415
+ next: readonly string[],
416
+ ): string {
417
+ if (previous.length !== next.length) {
418
+ return erase(previous.length) + next.map((line) => `${line}\n`).join("");
419
+ }
420
+ let codes = "";
421
+ for (const [i, line] of next.entries()) {
422
+ if (line === previous[i]) continue;
423
+ const up = next.length - i;
424
+ codes += `\x1b[${up}A\r\x1b[2K${line}\r\x1b[${up}B`;
425
+ }
426
+ return codes;
427
+ }
428
+
429
+ type Region = {
430
+ readonly shown: boolean;
431
+ draw: (lines: readonly string[]) => void;
432
+ above: (text: string) => void;
433
+ replace: (text: string) => void;
434
+ };
435
+
436
+ function createRegion(write: (text: string) => void): Region {
437
+ let lines: readonly string[] = [];
438
+ let shown = false;
439
+ const frame = (codes: string) => {
440
+ if (codes !== "") write(`${SYNC_START}${codes}${SYNC_END}`);
441
+ };
442
+ return {
443
+ get shown() {
444
+ return shown;
445
+ },
446
+ draw(next) {
447
+ frame((shown ? "" : hideCursor()) + redraw(lines, next));
448
+ shown = true;
449
+ lines = next;
450
+ },
451
+ above(text) {
452
+ frame(erase(lines.length) + text + lines.map((l) => `${l}\n`).join(""));
453
+ },
454
+ replace(text) {
455
+ frame(erase(lines.length) + text + (shown ? showCursor() : ""));
456
+ lines = [];
457
+ shown = false;
458
+ },
459
+ };
460
+ }
461
+
462
+ /** Where a live component writes, and how. */
463
+ export type LiveOptions = {
464
+ write: (text: string) => void;
465
+ /** Whether to redraw in place; `wantsRedraw` decides it. */
466
+ redraw: boolean;
467
+ paint: Paint;
468
+ glyphs: Glyphs;
469
+ nowMs: () => number;
470
+ /** The terminal's width now, read at every frame so a resize fits. */
471
+ columns?: () => number | undefined;
472
+ /**
473
+ * The terminal's height now, read at every frame: a task list taller
474
+ * than it shows a window. Without it, nothing is windowed.
475
+ */
476
+ rows?: () => number | undefined;
477
+ };
478
+
479
+ /** A task list a run updates as its tasks start and end. */
480
+ export type TaskList = {
481
+ readonly tasks: readonly Task[];
482
+ start: (name: string, detail?: string) => void;
483
+ done: (name: string, detail?: string) => void;
484
+ fail: (name: string, detail?: string) => void;
485
+ skip: (name: string, detail?: string) => void;
486
+ /**
487
+ * Runs `work` as the task: done with the detail it returns, failed
488
+ * with the message it throws; resolves whether it passed.
489
+ */
490
+ run: (name: string, work: () => Promise<string | void>) => Promise<boolean>;
491
+ /** Leaves the record and the closing line, and returns the tasks. */
492
+ finish: () => readonly Task[];
493
+ /** Leaves the record of a stopped run, what finished and what didn't. */
494
+ stop: () => readonly Task[];
495
+ /**
496
+ * Erases the list and leaves no record, for a run whose report, on
497
+ * stdout, is the record; returns the tasks. Piped, the lines already
498
+ * written stay, and no more are.
499
+ */
500
+ clear: () => readonly Task[];
501
+ };
502
+
503
+ /** What a task list takes besides where it writes. */
504
+ export type TaskListOptions = LiveOptions & {
505
+ /** What it counts, in the closing line and the bar. @default "task" */
506
+ noun?: string;
507
+ /** Draws done of total as a bar under the live list. */
508
+ bar?: boolean;
509
+ };
510
+
511
+ const lookOf = (options: LiveOptions): Look => ({
512
+ paint: options.paint,
513
+ glyphs: options.glyphs,
514
+ columns: Math.min(MEASURE, options.columns?.() || MEASURE),
515
+ });
516
+
517
+ /**
518
+ * Creates a task list for tasks that run in parallel. On a terminal it
519
+ * appears after 300 ms and redraws at most 10 times a second; otherwise
520
+ * it writes one line per task as it finishes. Either way it ends in a
521
+ * static record and a closing line.
522
+ */
523
+ export function createTaskList(
524
+ names: readonly string[],
525
+ options: TaskListOptions,
526
+ ): TaskList {
527
+ const { write, nowMs } = options;
528
+ const startMs = nowMs();
529
+ let tasks: Task[] = names.map((name) => ({ name, status: "pending" }));
530
+ const written = new Set<string>();
531
+ const region = createRegion(write);
532
+ const state = { frame: 0, settled: false };
533
+ const timer = options.redraw
534
+ ? setInterval(() => {
535
+ if (!region.shown && nowMs() - startMs < TIMING.showAfterMs) return;
536
+ state.frame++;
537
+ const rows = options.rows?.();
538
+ region.draw(
539
+ renderTaskFrame(
540
+ tasks,
541
+ lookOf(options),
542
+ { nowMs: nowMs(), frame: state.frame },
543
+ {
544
+ ...(rows !== undefined && rows > 0 && { rows }),
545
+ ...(options.bar === true && { bar: true }),
546
+ ...(options.noun !== undefined && { noun: options.noun }),
547
+ },
548
+ ),
549
+ );
550
+ }, TIMING.frameMs)
551
+ : undefined;
552
+ timer?.unref();
553
+
554
+ const set = (task: Task) => {
555
+ const i = tasks.findIndex((t) => t.name === task.name);
556
+ if (i === -1) throw new Error(`no task ${JSON.stringify(task.name)}`);
557
+ if (state.settled) return;
558
+ tasks = tasks.with(i, task);
559
+ if (options.redraw || task.status === "running") return;
560
+ written.add(task.name);
561
+ write(`${renderTaskLine(task, lookOf(options))}\n`);
562
+ };
563
+ const tookMs = (name: string) => {
564
+ const task = tasks.find((t) => t.name === name);
565
+ return task?.status === "running" ? nowMs() - task.startedMs : 0;
566
+ };
567
+ const withDetail = (detail: string | undefined) =>
568
+ detail === undefined ? {} : { detail };
569
+ const settle = (stopped: boolean, record = true) => {
570
+ if (state.settled) return tasks;
571
+ state.settled = true;
572
+ clearInterval(timer);
573
+ if (stopped) tasks = stopTasks(tasks);
574
+ if (!record) {
575
+ if (options.redraw) region.replace("");
576
+ return tasks;
577
+ }
578
+ const look = lookOf(options);
579
+ const summary = renderTaskSummary(tasks, nowMs() - startMs, look, {
580
+ stopped,
581
+ ...(options.noun !== undefined && { noun: options.noun }),
582
+ });
583
+ if (options.redraw) {
584
+ // The closing line wraps at a word, since it stays in the
585
+ // scrollback whole, where a cut would lose what failed.
586
+ const lines = [
587
+ ...renderTasks(tasks, look),
588
+ fitWidth(summary, look.columns),
589
+ ];
590
+ region.replace(lines.map((l) => `${l}\n`).join(""));
591
+ } else {
592
+ const rest = tasks.filter((t) => !written.has(t.name));
593
+ for (const task of rest) write(`${renderTaskLine(task, look)}\n`);
594
+ write(`${summary}\n`);
595
+ }
596
+ return tasks;
597
+ };
598
+ const end = (status: "done" | "failed") => (name: string, detail?: string) =>
599
+ set({ name, status, tookMs: tookMs(name), ...withDetail(detail) });
600
+ const list: TaskList = {
601
+ get tasks() {
602
+ return tasks;
603
+ },
604
+ start: (name, detail) =>
605
+ set({
606
+ name,
607
+ status: "running",
608
+ startedMs: nowMs(),
609
+ ...withDetail(detail),
610
+ }),
611
+ done: end("done"),
612
+ fail: end("failed"),
613
+ skip: (name, detail) =>
614
+ set({ name, status: "skipped", ...withDetail(detail) }),
615
+ async run(name, work) {
616
+ list.start(name);
617
+ try {
618
+ const detail = await work();
619
+ list.done(name, typeof detail === "string" ? detail : undefined);
620
+ return true;
621
+ } catch (error) {
622
+ list.fail(name, error instanceof Error ? error.message : String(error));
623
+ return false;
624
+ }
625
+ },
626
+ finish: () => settle(false),
627
+ stop: () => settle(true),
628
+ clear: () => settle(false, false),
629
+ };
630
+ return list;
631
+ }
632
+
633
+ /** Renders a status line: `⠋ Building · 12 of 40 files · 3 s`. */
634
+ export function renderStatus(
635
+ text: string,
636
+ elapsedMs: number,
637
+ frame: number,
638
+ look: Look,
639
+ ): string {
640
+ const { paint, glyphs } = look;
641
+ const spinner = glyphs.spinner[frame % glyphs.spinner.length] ?? "";
642
+ const seconds =
643
+ elapsedMs >= TIMING.countAfterMs
644
+ ? paint.dim(`${SEPARATOR}${formatElapsed(elapsedMs)}`)
645
+ : "";
646
+ // The seconds are what moves, so a narrow terminal shortens the text
647
+ // first, and loses them only when the text would have no room left.
648
+ const lead = `${spinner} `;
649
+ const room = look.columns - textWidth(lead) - textWidth(seconds);
650
+ if (textWidth(text) <= room) return `${lead}${text}${seconds}`;
651
+ if (room >= MIN_TEXT) return `${lead}${cutLine(text, room)}${seconds}`;
652
+ return cutLine(`${lead}${text}`, look.columns);
653
+ }
654
+
655
+ const MIN_TEXT = 8;
656
+
657
+ /** A line pinned under streaming output, while the output prints above it. */
658
+ export type StatusLine = {
659
+ /** Changes what the line says. */
660
+ update: (text: string) => void;
661
+ /** Prints a line of output above the status line. */
662
+ log: (line: string) => void;
663
+ /** Removes the status line, for output that follows in its place. */
664
+ clear: () => void;
665
+ /** Replaces the status line with a static one that stays. */
666
+ settle: (line: string) => void;
667
+ };
668
+
669
+ /**
670
+ * Creates a status line pinned under the output `log` prints. On a
671
+ * terminal it appears after 300 ms and redraws at most 10 times a
672
+ * second; otherwise only the log and the settled line are written.
673
+ */
674
+ export function createStatusLine(
675
+ text: string,
676
+ options: LiveOptions,
677
+ ): StatusLine {
678
+ const { write, nowMs } = options;
679
+ const startMs = nowMs();
680
+ const region = createRegion(write);
681
+ // Output that arrives between frames waits for the next one, so a
682
+ // fast log redraws the status line 10 times a second, not per line.
683
+ const queued: string[] = [];
684
+ const state = { text, frame: 0, settled: false };
685
+ const flush = () => queued.splice(0).join("");
686
+ const timer = options.redraw
687
+ ? setInterval(() => {
688
+ const elapsedMs = nowMs() - startMs;
689
+ if (!region.shown && elapsedMs < TIMING.showAfterMs) return;
690
+ state.frame++;
691
+ if (queued.length > 0) region.above(flush());
692
+ region.draw([
693
+ renderStatus(state.text, elapsedMs, state.frame, lookOf(options)),
694
+ ]);
695
+ }, TIMING.frameMs)
696
+ : undefined;
697
+ timer?.unref();
698
+ const end = (line: string) => {
699
+ if (state.settled) return;
700
+ state.settled = true;
701
+ clearInterval(timer);
702
+ if (region.shown) region.replace(flush() + line);
703
+ else write(flush() + line);
704
+ };
705
+ return {
706
+ update(next) {
707
+ state.text = next;
708
+ },
709
+ log(line) {
710
+ if (state.settled || !region.shown) write(`${line}\n`);
711
+ else queued.push(`${line}\n`);
712
+ },
713
+ clear: () => end(""),
714
+ settle: (line) => end(`${line}\n`),
715
+ };
716
+ }
717
+
718
+ /** What a server shows once it listens. */
719
+ export type Ready = {
720
+ /** Where it listens, as `http://localhost:1776`. */
721
+ address: string;
722
+ /** How long it took to start. */
723
+ tookMs?: number;
724
+ /** The keys it reads; give none when stdin isn't a terminal. */
725
+ keys?: readonly KeyHint[];
726
+ };
727
+
728
+ // The address is bold and stands alone, so it reads first and copies
729
+ // whole; the keys are faint, since a person reads them once.
730
+ /** Renders a server's ready line, and its keys under it. */
731
+ export function readyLines(look: Look, ready: Ready): string[] {
732
+ const { paint, glyphs } = look;
733
+ const took =
734
+ ready.tookMs === undefined
735
+ ? ""
736
+ : paint.dim(`${SEPARATOR}${formatDuration(ready.tookMs)}`);
737
+ const keys = ready.keys ?? [];
738
+ return [
739
+ `${paint.good(glyphs.done)} Ready at ${paint.bold(ready.address)}${took}`,
740
+ ...(keys.length === 0 ? [] : [` ${keyHints(paint, keys)}`]),
741
+ ];
742
+ }
743
+
744
+ // No spinner and no clock: a watch loop waits for minutes, and motion
745
+ // that long only distracts.
746
+ /**
747
+ * Renders a watch loop's line
748
+ * between runs: `○ Waiting for changes in src/`.
749
+ */
750
+ export function waitingLine(
751
+ look: Look,
752
+ watching?: string,
753
+ keys: readonly KeyHint[] = [],
754
+ ): string {
755
+ const { paint, glyphs } = look;
756
+ const where = watching === undefined ? "" : ` in ${watching}`;
757
+ const hints = keys.length === 0 ? "" : `${SEPARATOR}${keyHints(paint, keys)}`;
758
+ return `${paint.dim(glyphs.pending)} Waiting for changes${where}${hints}`;
759
+ }
760
+
761
+ /** The exit code of a run stopped by Ctrl-C: 128 plus SIGINT's 2. */
762
+ export const EXIT_INTERRUPTED = 130;
763
+ /** The exit code of a run stopped by SIGTERM: 128 plus its 15. */
764
+ export const EXIT_TERMINATED = 143;
765
+ const ERASE_ECHO = "\r\x1b[2K";
766
+
767
+ /** A signal that stops a run: Ctrl-C's, or a supervisor's SIGTERM. */
768
+ export type StopSignal = "SIGINT" | "SIGTERM";
769
+
770
+ /** The exit code for a run `signal` stopped: 128 plus its number. */
771
+ export const exitCodeOf = (signal: StopSignal): number =>
772
+ signal === "SIGINT" ? EXIT_INTERRUPTED : EXIT_TERMINATED;
773
+
774
+ /** The process, or what a test passes for it. */
775
+ export type SignalTarget = {
776
+ on: (event: StopSignal | "exit", listener: () => void) => unknown;
777
+ off: (event: StopSignal | "exit", listener: () => void) => unknown;
778
+ exit: (code: number) => void;
779
+ };
780
+
781
+ /**
782
+ * What to do with the `^C` a terminal echoes where the cursor rests:
783
+ * erase it, end its line so what prints next starts on its own, or leave
784
+ * it, as in a pipe, where there is none.
785
+ */
786
+ export type Echo = "erase" | "newline" | "keep";
787
+
788
+ /** What `handleInterrupt` restores and calls. */
789
+ export type InterruptOptions = {
790
+ process: SignalTarget;
791
+ /** Writes to the terminal the live output is on. */
792
+ write: (text: string) => void;
793
+ /**
794
+ * Whether `write` goes to a terminal, so the restoring codes are safe;
795
+ * pass `wantsRedraw`'s answer.
796
+ */
797
+ terminal: boolean;
798
+ /**
799
+ * What to do with Ctrl-C's `^C`: `erase` on a terminal that redraws;
800
+ * `newline` on one that doesn't, as for a coding agent or TERM=dumb,
801
+ * and on one a child process shares, whose line an erase would clear;
802
+ * `keep` in a pipe.
803
+ * @default "erase" when `terminal`, else "keep"
804
+ */
805
+ echo?: Echo;
806
+ /**
807
+ * Whether it exits once `onStop` ends. Without, `stopped` resolves
808
+ * instead, and the caller prints the partial result and returns
809
+ * `exitCodeOf` the signal; a second Ctrl-C still exits at once, unless
810
+ * `secondExit` is false.
811
+ * @default true
812
+ */
813
+ exit?: boolean;
814
+ /**
815
+ * Whether a second Ctrl-C or SIGTERM exits at once. Without, it calls
816
+ * `onQuit`, restores the terminal, sets `forced` and resolves `stopped`
817
+ * if `onStop` hasn't ended, and the caller exits, at once, with
818
+ * `exitCodeOf(forced)`; a signal after it does nothing.
819
+ * @default true
820
+ */
821
+ secondExit?: boolean;
822
+ /** stdin, whose raw mode is undone on every exit, if it's on. */
823
+ input?: {
824
+ isTTY?: boolean;
825
+ isRaw?: boolean;
826
+ setRawMode?: (raw: boolean) => unknown;
827
+ };
828
+ /**
829
+ * Prints the partial result, once the work has stopped; the process
830
+ * exits when it resolves.
831
+ */
832
+ onStop?: (signal: StopSignal) => void | Promise<void>;
833
+ /** Prints a last line when a second Ctrl-C quits before `onStop` ends. */
834
+ onQuit?: () => void;
835
+ };
836
+
837
+ /** A run that Ctrl-C stops. */
838
+ export type Interrupt = {
839
+ /** Aborted at the first Ctrl-C, so the work stops. */
840
+ readonly signal: AbortSignal;
841
+ /** The signal that stopped the run, from the moment it arrived. */
842
+ readonly stoppedBy: StopSignal | undefined;
843
+ /**
844
+ * Resolves with the signal once `onStop` has ended, or, when
845
+ * `secondExit` is false, at a second signal, whichever comes first.
846
+ */
847
+ readonly stopped: Promise<StopSignal>;
848
+ /** The second signal, which asks to quit at once, from its arrival. */
849
+ readonly forced: StopSignal | undefined;
850
+ /** Acts as Ctrl-C, for a program in raw mode, which reads it as a key. */
851
+ interrupt: () => void;
852
+ /**
853
+ * Call when the work ends, before printing its result: waits a turn of
854
+ * the event loop, so a signal already sent is handled, then resolves
855
+ * the signal that stopped the run, or removes the handlers and
856
+ * resolves undefined. The Ctrl-C that stops a child process, a build
857
+ * or a browser, reaches this one too, and the child's failure can
858
+ * come back first.
859
+ */
860
+ settle: () => Promise<StopSignal | undefined>;
861
+ /** Removes the handlers, once the run is done. */
862
+ dispose: () => void;
863
+ };
864
+
865
+ /**
866
+ * Handles Ctrl-C and SIGTERM: the first stops the work and prints what
867
+ * finished, then exits 130 (143 for SIGTERM); a second exits at once.
868
+ * On every exit, a crash included, it shows the cursor if a component
869
+ * hid it, and undoes raw mode if it's on.
870
+ */
871
+ export function handleInterrupt(options: InterruptOptions): Interrupt {
872
+ const { process: target } = options;
873
+ const controller = new AbortController();
874
+ const exits = options.exit ?? true;
875
+ const secondExits = options.secondExit ?? true;
876
+ const echo = options.echo ?? (options.terminal ? "erase" : "keep");
877
+ const state: {
878
+ restored: boolean;
879
+ stoppedBy: StopSignal | undefined;
880
+ forced: StopSignal | undefined;
881
+ } = { restored: false, stoppedBy: undefined, forced: undefined };
882
+ let markStopped: (signal: StopSignal) => void = () => {};
883
+ const stopped = new Promise<StopSignal>((resolve) => {
884
+ markStopped = resolve;
885
+ });
886
+ const restore = () => {
887
+ if (state.restored) return;
888
+ state.restored = true;
889
+ const input = options.input;
890
+ if (input?.isTTY === true && input.isRaw !== false) {
891
+ input.setRawMode?.(false);
892
+ }
893
+ if (options.terminal && cursorHidden()) options.write(showCursor());
894
+ };
895
+ const quit = (code: number) => {
896
+ restore();
897
+ target.exit(code);
898
+ };
899
+ const stop = (signal: StopSignal, echoed: boolean) => {
900
+ // The terminal echoes Ctrl-C as ^C where the cursor rests, the line
901
+ // under a live region, and the record printed next would follow it.
902
+ if (echoed) {
903
+ if (echo === "erase") options.write(ERASE_ECHO);
904
+ else if (echo === "newline") options.write("\n");
905
+ }
906
+ // Past the second, the caller is already exiting.
907
+ if (!secondExits && state.forced !== undefined) return;
908
+ if (state.stoppedBy !== undefined) {
909
+ state.forced = signal;
910
+ options.onQuit?.();
911
+ if (secondExits) {
912
+ quit(exitCodeOf(signal));
913
+ } else {
914
+ restore();
915
+ markStopped(state.stoppedBy);
916
+ }
917
+ return;
918
+ }
919
+ state.stoppedBy = signal;
920
+ controller.abort();
921
+ const end = () => {
922
+ restore();
923
+ markStopped(signal);
924
+ // Without secondExit, a forced quit is the caller's to make.
925
+ if (exits && (secondExits || state.forced === undefined)) {
926
+ target.exit(exitCodeOf(signal));
927
+ }
928
+ };
929
+ // A failing onStop still exits with the signal's code, since the run
930
+ // was stopped either way.
931
+ void Promise.resolve()
932
+ .then(() => options.onStop?.(signal))
933
+ .then(end, end);
934
+ };
935
+ const onInt = () => stop("SIGINT", true);
936
+ const onTerm = () => stop("SIGTERM", false);
937
+ const dispose = () => {
938
+ target.off("SIGINT", onInt);
939
+ target.off("SIGTERM", onTerm);
940
+ target.off("exit", restore);
941
+ };
942
+ target.on("SIGINT", onInt);
943
+ target.on("SIGTERM", onTerm);
944
+ target.on("exit", restore);
945
+ return {
946
+ signal: controller.signal,
947
+ get stoppedBy() {
948
+ return state.stoppedBy;
949
+ },
950
+ get forced() {
951
+ return state.forced;
952
+ },
953
+ stopped,
954
+ // A key read in raw mode has no echo to erase.
955
+ interrupt: () => stop("SIGINT", false),
956
+ settle: () =>
957
+ new Promise((resolve) => {
958
+ setImmediate(() => {
959
+ if (state.stoppedBy === undefined) dispose();
960
+ resolve(state.stoppedBy);
961
+ });
962
+ }),
963
+ dispose,
964
+ };
965
+ }