ostia 0.5.0 → 0.6.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,321 @@
1
+ // Terminal output shared by metonym's command-line tools: color, tables,
2
+ // trees, the closing line and the progress line. Each tool carries an
3
+ // identical copy, since a package here has no runtime dependencies; a
4
+ // change is made once and copied to all of them.
5
+
6
+ /**
7
+ * Color for the human format on a terminal only: the agent format and
8
+ * JSON are read by programs. Each color marks a verdict or recedes,
9
+ * never decorates.
10
+ */
11
+ export type Paint = {
12
+ good: (text: string) => string;
13
+ warn: (text: string) => string;
14
+ bad: (text: string) => string;
15
+ dim: (text: string) => string;
16
+ bold: (text: string) => string;
17
+ faint: (text: string) => string;
18
+ };
19
+
20
+ const asIs = (text: string) => text;
21
+
22
+ export const PLAIN: Paint = {
23
+ good: asIs,
24
+ warn: asIs,
25
+ bad: asIs,
26
+ dim: asIs,
27
+ bold: asIs,
28
+ faint: asIs,
29
+ };
30
+
31
+ // The 16 ANSI colors, never a fixed hex: each terminal theme defines
32
+ // its own green or gray, picked to read on its own background, light,
33
+ // dark or pink. The codes are written out, not asked of Bun.color, so
34
+ // a package that also runs on Node prints the same.
35
+ export function createPaint(): Paint {
36
+ const wrap = (code: number) => (text: string) =>
37
+ text === "" ? text : `\x1b[${code}m${text}\x1b[39m`;
38
+ return {
39
+ good: wrap(32),
40
+ warn: wrap(33),
41
+ bad: wrap(31),
42
+ // Bright black, the gray every theme dims secondary text with.
43
+ dim: wrap(90),
44
+ // Bold is a weight, not a color: names and section heads.
45
+ bold: (text) => (text === "" ? text : `\x1b[1m${text}\x1b[22m`),
46
+ // Faint is the text color at lower intensity, so a table's header
47
+ // recedes in every theme, even one whose gray is odd.
48
+ faint: (text) => (text === "" ? text : `\x1b[2m${text}\x1b[22m`),
49
+ };
50
+ }
51
+
52
+ // The person's explicit ask wins, because they know where the output
53
+ // goes: the flag, then NO_COLOR and FORCE_COLOR (no-color.org,
54
+ // force-color.org). Otherwise color only for a terminal no coding agent
55
+ // reads, since escape codes are noise to a program.
56
+ export function wantsColor(
57
+ forced: boolean | undefined,
58
+ terminal: boolean,
59
+ env: Readonly<Record<string, string | undefined>>,
60
+ agent: boolean,
61
+ ): boolean {
62
+ if (forced !== undefined) return forced;
63
+ if ((env.NO_COLOR ?? "") !== "") return false;
64
+ const force = env.FORCE_COLOR;
65
+ if (force !== undefined && force !== "") return force !== "0";
66
+ return terminal && !agent;
67
+ }
68
+
69
+ // "n/a", because an em dash for a missing value reads as punctuation.
70
+ export const MISSING = "n/a";
71
+
72
+ // A zero difference has no sign, so "±" only ever means noise. The
73
+ // minus is ASCII, so a pasted number parses.
74
+ export const signed = (value: number, show: (n: number) => string): string =>
75
+ value === 0 ? show(0) : `${value > 0 ? "+" : "-"}${show(Math.abs(value))}`;
76
+
77
+ // The one separator, so every header and status line splits its parts
78
+ // the same way.
79
+ export const SEPARATOR = " · ";
80
+
81
+ // A sub-row's branch, so a group's last row closes it: ├ then └.
82
+ export const branch = (index: number, count: number): string =>
83
+ index === count - 1 ? "└ " : "├ ";
84
+
85
+ // A note under a row, indented past the label's branch, as a reason or
86
+ // a problem that would push the row past 80 columns.
87
+ export const NOTE_INDENT = " ";
88
+
89
+ // The last line of a run that finished: what it did and what it took,
90
+ // so a person sees it ended and why it took that long.
91
+ export function closingLine(
92
+ paint: Paint,
93
+ what: string,
94
+ detail?: string,
95
+ ): string {
96
+ return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
97
+ }
98
+
99
+ // A run that found problems ends in a cross, so the last line says
100
+ // whether to act, as the check mark does when there's nothing to do.
101
+ export function failLine(paint: Paint, what: string, detail?: string): string {
102
+ return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
103
+ }
104
+
105
+ // Cut at a word boundary, so a label never ends mid-word; JSON keeps
106
+ // it whole.
107
+ export function truncateWords(text: string, max: number): string {
108
+ if ([...text].length <= max) return text;
109
+ const cut = [...text].slice(0, max - 1).join("");
110
+ const space = cut.lastIndexOf(" ");
111
+ return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, "")}…`;
112
+ }
113
+
114
+ // Since the file name matters more than its folders, and its first and
115
+ // last words more than its middle, folders go from the left first, then
116
+ // the stem's middle words, and the build hash and extension always stay,
117
+ // as in …/carbon-…DataTableSkeleton-Lp9Rk3Ds.js.
118
+ const HASH_TAIL = /[-.][^-./]+\.\w+$/;
119
+ const WORD_END = /(?<=[-_.])/;
120
+ const width = (text: string) => [...text].length;
121
+
122
+ export function truncatePath(path: string, max: number): string {
123
+ if (width(path) <= max) return path;
124
+ const parts = path.split("/");
125
+ const name = parts.pop() ?? path;
126
+ for (let keep = parts.length - 1; keep >= 0; keep--) {
127
+ const candidate = `…/${[...parts.slice(parts.length - keep), name].join("/")}`;
128
+ if (width(candidate) <= max) return candidate;
129
+ }
130
+ const prefix = parts.length > 0 ? "…/" : "";
131
+ const tail = HASH_TAIL.exec(name)?.[0] ?? "";
132
+ const stem = name.slice(0, name.length - tail.length);
133
+ const room = max - width(prefix) - width(tail) - 1;
134
+ if (room < 4)
135
+ return `${prefix}…${[...name].slice(-(max - width(prefix) - 1)).join("")}`;
136
+ const words = stem.split(WORD_END);
137
+ const first = words[0] ?? "";
138
+ let end = "";
139
+ for (let i = words.length - 1; i > 0; i--) {
140
+ const word = words[i] ?? "";
141
+ if (width(first) + 1 + width(word + end) > room) break;
142
+ end = word + end;
143
+ }
144
+ return end === ""
145
+ ? `${prefix}${[...stem].slice(0, room).join("")}…${tail}`
146
+ : `${prefix}${first}…${end}${tail}`;
147
+ }
148
+
149
+ // A mark in the left margin for a row that needs work, in its rating's
150
+ // color, so a scan finds what to fix while the numbers stay plain.
151
+ export function withGutter(
152
+ lines: readonly string[],
153
+ marks: ReadonlyMap<number, (text: string) => string>,
154
+ ): string[] {
155
+ return lines.map((line, i) => {
156
+ const mark = marks.get(i);
157
+ return mark === undefined ? line : `${mark("▌")}${line.slice(1)}`;
158
+ });
159
+ }
160
+
161
+ // eslint-disable-next-line no-control-regex -- escape codes are what it strips
162
+ const ESCAPE = /\x1b\[[0-9;]*m/g;
163
+
164
+ // Widths come from Bun when it runs, since it counts wide characters;
165
+ // a package that also runs on Node counts one column per code point,
166
+ // because the text these tools print has no wide ones.
167
+ export const textWidth = (text: string): number =>
168
+ typeof Bun === "undefined"
169
+ ? [...text.replace(ESCAPE, "")].length
170
+ : Bun.stringWidth(text);
171
+
172
+ // 80 columns, because that's the width a terminal opens at.
173
+ export const MEASURE = 80;
174
+
175
+ // A cell that draws a rule as wide as its column, so totals read apart
176
+ // from the rows above them.
177
+ export const RULE = "\u0000rule";
178
+
179
+ // Numbers right-align, so the columns in `right` pad on the left. A
180
+ // left-aligned last cell is left ragged, since padding it would only add
181
+ // trailing spaces.
182
+ export function aligned(
183
+ table: readonly (readonly string[])[],
184
+ rightColumns: readonly number[] = [],
185
+ paintRule: (text: string) => string = asIs,
186
+ indent = " ",
187
+ ): string[] {
188
+ const blank = (cell: string) => cell === "" || cell === RULE;
189
+ // A column empty in every row, such as noise from one run, is left
190
+ // out, or it would print as a double gap.
191
+ const used = new Set(
192
+ table.flatMap((row) => row.flatMap((cell, i) => (blank(cell) ? [] : [i]))),
193
+ );
194
+ const keep = (row: readonly string[]) => row.filter((_, i) => used.has(i));
195
+ const rows = table.map(keep);
196
+ const right = [...used]
197
+ .sort((a, b) => a - b)
198
+ .flatMap((column, i) => (rightColumns.includes(column) ? [i] : []));
199
+ // Escape codes take no columns, so a colored cell pads as wide as
200
+ // it shows.
201
+ const cellWidth = (cell: string) => (cell === RULE ? 0 : textWidth(cell));
202
+ const widths: number[] = [];
203
+ for (const row of rows) {
204
+ for (const [i, cell] of row.entries()) {
205
+ if (i === row.length - 1 && !right.includes(i)) continue;
206
+ widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
207
+ }
208
+ }
209
+ const pad = (cell: string, i: number) =>
210
+ " ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
211
+ const columnsWidth = (from: number, to: number) =>
212
+ widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
213
+ return rows.map((row) => {
214
+ const first = row.indexOf(RULE);
215
+ if (first !== -1) {
216
+ const last = row.lastIndexOf(RULE);
217
+ const line = "─".repeat(columnsWidth(first, last + 1) - 2);
218
+ return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
219
+ }
220
+ // An empty row is a blank line, with no indent left trailing.
221
+ return `${indent}${row
222
+ .map((cell, i) =>
223
+ right.includes(i)
224
+ ? pad(cell, i) + cell
225
+ : i === row.length - 1
226
+ ? cell
227
+ : cell + pad(cell, i),
228
+ )
229
+ .join(" ")}`.trimEnd();
230
+ });
231
+ }
232
+
233
+ // aligned, with a row that overflows the measure shortened in its last
234
+ // cell by `shrink`, by just its overflow. Other rows, the header and a
235
+ // colored cell, which a cut would break, stay as they are.
236
+ export function fitted(
237
+ table: readonly (readonly string[])[],
238
+ rightColumns: readonly number[],
239
+ shrink: (text: string, max: number) => string,
240
+ paintRule: (text: string) => string = asIs,
241
+ ): string[] {
242
+ const lines = aligned(table, rightColumns, paintRule);
243
+ if (lines.every((line) => textWidth(line) <= MEASURE)) return lines;
244
+ const shrunk = table.map((row, r) => {
245
+ const over = textWidth(lines[r] ?? "") - MEASURE;
246
+ const last = row.length - 1;
247
+ const cell = row[last] ?? "";
248
+ if (r === 0 || over <= 0 || cell === RULE || cell.includes("\x1b")) {
249
+ return row;
250
+ }
251
+ const copy = [...row];
252
+ copy[last] = shrink(cell, textWidth(cell) - over);
253
+ return copy;
254
+ });
255
+ return aligned(shrunk, rightColumns, paintRule);
256
+ }
257
+
258
+ // Lines with notes under some of them, keyed by the line's index, so a
259
+ // note follows its row without widening the table.
260
+ export function withNotes(
261
+ lines: readonly string[],
262
+ notes: ReadonlyMap<number, readonly string[]>,
263
+ ): string[] {
264
+ return lines.flatMap((line, i) => [line, ...(notes.get(i) ?? [])]);
265
+ }
266
+
267
+ // A table's header row is read once, then consulted, so it takes the
268
+ // smallest effective difference: faint, with no rule under it.
269
+ export const headerRow = (paint: Paint, cells: readonly string[]): string[] =>
270
+ cells.map((cell) => paint.faint(cell));
271
+
272
+ export const plural = (count: number, one: string, many = `${one}s`): string =>
273
+ `${count} ${count === 1 ? one : many}`;
274
+
275
+ /**
276
+ * One stderr line, rewritten in place while a long run works, so it never
277
+ * looks stuck. Made only when stderr is a terminal, and not for a coding
278
+ * agent or JSON; cleared before the result prints.
279
+ */
280
+ export type Progress = {
281
+ step(text: string, doneRatio: number): void;
282
+ clear(): void;
283
+ };
284
+
285
+ export const SILENT: Progress = { step: () => {}, clear: () => {} };
286
+
287
+ const BAR_WIDTH = 20;
288
+ const CLEAR_LINE = "\r\x1b[2K";
289
+
290
+ export function createProgress(
291
+ write: (text: string) => void,
292
+ paint: Paint,
293
+ nowMs: () => number,
294
+ ): Progress {
295
+ const startMs = nowMs();
296
+ let text = "";
297
+ let doneRatio = 0;
298
+ const render = () => {
299
+ const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
300
+ // Done and to-do differ in shape as well as color, so the bar reads
301
+ // without color too.
302
+ const bar =
303
+ paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
304
+ const seconds = Math.floor((nowMs() - startMs) / 1000);
305
+ write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
306
+ };
307
+ // A tick each second, so the clock moves while a step is in flight.
308
+ const timer = setInterval(render, 1000);
309
+ timer.unref();
310
+ return {
311
+ step(next, ratio) {
312
+ text = next;
313
+ doneRatio = ratio;
314
+ render();
315
+ },
316
+ clear() {
317
+ clearInterval(timer);
318
+ write(CLEAR_LINE);
319
+ },
320
+ };
321
+ }
package/src/time.ts CHANGED
@@ -22,11 +22,7 @@ import {
22
22
  noisyMachineWarning,
23
23
  stampDrift,
24
24
  } from "./measure/environment.ts";
25
- import {
26
- assertSamplingOptions,
27
- createTimingPhase,
28
- drainTimingPhase,
29
- } from "./measure/timing.ts";
25
+ import { assertSamplingOptions, createTimingPhase } from "./measure/timing.ts";
30
26
  import {
31
27
  type PrepareHook,
32
28
  type PrepareRun,
@@ -122,6 +118,19 @@ export interface TimeOptions {
122
118
  * trial still contributes its sample and gets no `nonzero-exit` warning.
123
119
  * */
124
120
  ignoreExitCodes?: number[];
121
+ /** Called after each trial, for a progress line. */
122
+ onProgress?: (progress: TimeProgress) => void;
123
+ }
124
+
125
+ /** What `time()` is doing, for `onProgress`. Counts start at 1. */
126
+ export interface TimeProgress {
127
+ command: number;
128
+ commands: number;
129
+ label: string;
130
+ /** Trials run so far for this command, warmup excluded. */
131
+ runs: number;
132
+ /** How far the whole run is, 0 to 1. */
133
+ doneRatio: number;
125
134
  }
126
135
 
127
136
  export function abortedWarning(): Warning {
@@ -254,19 +263,49 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
254
263
  ? { command: opts.shell, startupNs: await shellStartupNs(opts.shell) }
255
264
  : undefined;
256
265
 
266
+ const runsDone = runs.map(() => 0);
267
+ const report = (index: number) => {
268
+ const entry = runs[index]?.entry;
269
+ if (!opts.onProgress || !entry) return;
270
+ opts.onProgress({
271
+ command: index + 1,
272
+ commands: runs.length,
273
+ label: entry.workload.label ?? entry.argv.join(" "),
274
+ runs: runsDone[index] ?? 0,
275
+ doneRatio:
276
+ runs.reduce((sum, { phase }) => sum + phase.doneRatio(), 0) /
277
+ runs.length,
278
+ });
279
+ };
280
+ const step = async (index: number): Promise<boolean> => {
281
+ const stepped = (await runs[index]?.phase.step()) ?? false;
282
+ if (stepped) {
283
+ runsDone[index] = (runsDone[index] ?? 0) + 1;
284
+ report(index);
285
+ }
286
+ return stepped;
287
+ };
288
+
257
289
  if (interleave) {
258
- for (const { phase } of runs) await phase.warmup();
290
+ for (const [index, { phase }] of runs.entries()) {
291
+ report(index);
292
+ await phase.warmup();
293
+ }
259
294
  let stepped = true;
260
295
  while (stepped) {
261
296
  stepped = false;
262
- for (const { phase } of runs) {
263
- if (await phase.step()) stepped = true;
297
+ for (const index of runs.keys()) {
298
+ if (await step(index)) stepped = true;
264
299
  }
265
300
  }
266
301
  for (const run of runs) await record(run);
267
302
  } else {
268
- for (const run of runs) {
269
- await drainTimingPhase(run.phase);
303
+ for (const [index, run] of runs.entries()) {
304
+ report(index);
305
+ await run.phase.warmup();
306
+ while (await step(index)) {
307
+ // Each step runs one trial.
308
+ }
270
309
  await record(run);
271
310
  }
272
311
  }