@moku-labs/common 0.1.1 → 0.2.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/dist/cli.cjs ADDED
@@ -0,0 +1,669 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_readline = require("node:readline");
3
+ //#region src/cli/ansi.ts
4
+ /**
5
+ * @file `@moku-labs/common/cli` — TTY/`NO_COLOR`-aware ANSI color + box-drawing
6
+ * primitives: the shared "brand DNA" every Moku CLI renders through (the brand pink,
7
+ * the palette, the box/spinner/progress glyphs). Color and Unicode glyphs are emitted
8
+ * only on a real TTY with `NO_COLOR` unset; otherwise plain ASCII so CI logs and pipes
9
+ * stay readable. Pure: depends on nothing but `process.stdout`/`process.env` defaults,
10
+ * so a consuming framework can build its own panels on top without pulling in any UI lib.
11
+ */
12
+ /** The ANSI escape byte (ESC, `0x1b`), built so no literal control char is in source. */
13
+ const ESC = String.fromCodePoint(27);
14
+ /** ANSI SGR codes used by the brand renderer (each prefixed with the ESC byte). */
15
+ const ANSI = {
16
+ reset: `${ESC}[0m`,
17
+ bold: `${ESC}[1m`,
18
+ dim: `${ESC}[2m`,
19
+ red: `${ESC}[31m`,
20
+ green: `${ESC}[32m`,
21
+ yellow: `${ESC}[33m`,
22
+ blue: `${ESC}[34m`,
23
+ magenta: `${ESC}[35m`,
24
+ cyan: `${ESC}[36m`,
25
+ gray: `${ESC}[90m`
26
+ };
27
+ /**
28
+ * The Moku brand pink (`#FF1E6F`) as an RGB triple, used for 24-bit truecolor output.
29
+ * Degrades to {@link ANSI.magenta} on a 16-color TTY and to plain text off a TTY.
30
+ */
31
+ const BRAND_PINK = {
32
+ r: 255,
33
+ g: 30,
34
+ b: 111
35
+ };
36
+ /**
37
+ * Build a 24-bit (truecolor) SGR foreground escape for the given RGB triple.
38
+ *
39
+ * @param r - Red channel (0–255).
40
+ * @param g - Green channel (0–255).
41
+ * @param b - Blue channel (0–255).
42
+ * @returns The `ESC[38;2;r;g;bm` foreground sequence.
43
+ * @example
44
+ * fg24(255, 30, 111); // "\x1b[38;2;255;30;111m"
45
+ */
46
+ function fg24(r, g, b) {
47
+ return `${ESC}[38;2;${r};${g};${b}m`;
48
+ }
49
+ /** ANSI: erase the entire current line, leaving the cursor where it is. */
50
+ const CLEAR_LINE = `${ESC}[2K`;
51
+ /** ANSI: erase from the cursor to the end of the screen (drops stale trailing rows). */
52
+ const CLEAR_BELOW = `${ESC}[0J`;
53
+ /**
54
+ * Braille spinner frames for live "working…" indicators on a TTY (advance one per tick).
55
+ * Off a TTY a renderer never animates, so this is unused in plain/CI output.
56
+ */
57
+ const SPINNER_FRAMES = [
58
+ "⠋",
59
+ "⠙",
60
+ "⠹",
61
+ "⠸",
62
+ "⠼",
63
+ "⠴",
64
+ "⠦",
65
+ "⠧",
66
+ "⠇",
67
+ "⠏"
68
+ ];
69
+ /**
70
+ * The ANSI sequence to move the cursor up `n` lines (empty string for `n <= 0`). A
71
+ * renderer uses it to repaint a live block in place — move up over the previous draw,
72
+ * then rewrite each row — so progress updates a fixed region instead of scrolling lines.
73
+ *
74
+ * @param n - Number of lines to move the cursor up.
75
+ * @returns The cursor-up escape sequence, or `""` when `n <= 0`.
76
+ * @example
77
+ * cursorUp(3); // "\x1b[3A"
78
+ */
79
+ function cursorUp(n) {
80
+ return n > 0 ? `${ESC}[${n}A` : "";
81
+ }
82
+ /** Unicode rounded box glyphs used when output is a color-capable TTY. */
83
+ const UNICODE_BOX = {
84
+ topLeft: "╭",
85
+ topRight: "╮",
86
+ bottomLeft: "╰",
87
+ bottomRight: "╯",
88
+ horizontal: "─",
89
+ vertical: "│"
90
+ };
91
+ /** ASCII box glyphs used when output is piped/CI (plain mode). */
92
+ const ASCII_BOX = {
93
+ topLeft: "+",
94
+ topRight: "+",
95
+ bottomLeft: "+",
96
+ bottomRight: "+",
97
+ horizontal: "-",
98
+ vertical: "|"
99
+ };
100
+ /**
101
+ * Matches every ANSI SGR escape sequence (used to measure visible width). Built from
102
+ * the {@link ESC} byte so no literal control character appears in the source regex.
103
+ */
104
+ const ANSI_PATTERN = new RegExp(String.raw`${ESC}\[[0-9;]*m`, "g");
105
+ /**
106
+ * Whether ANSI color/box glyphs should be emitted: a TTY stream with `NO_COLOR`
107
+ * unset. Reads `process.stdout.isTTY` and `process.env.NO_COLOR` by default so the
108
+ * renderer auto-degrades in CI and pipes.
109
+ *
110
+ * @param stream - Stream to probe for `isTTY` (defaults to `process.stdout`).
111
+ * @param noColor - The `NO_COLOR` value (defaults to `process.env.NO_COLOR`).
112
+ * @returns `true` when color should be used.
113
+ * @example
114
+ * supportsColor(); // true in an interactive terminal
115
+ */
116
+ function supportsColor(stream = process.stdout, noColor = process.env.NO_COLOR) {
117
+ return stream.isTTY === true && noColor === void 0;
118
+ }
119
+ /**
120
+ * Whether the terminal advertises 24-bit (truecolor) support via `COLORTERM`, so the
121
+ * renderer may emit the exact brand pink ({@link BRAND_PINK}) instead of the 16-color
122
+ * `magenta` approximation. Always layered on top of {@link supportsColor} — truecolor
123
+ * is never used when color itself is disabled.
124
+ *
125
+ * @param colorTerm - The `COLORTERM` value (defaults to `process.env.COLORTERM`).
126
+ * @returns `true` when `COLORTERM` is `truecolor` or `24bit`.
127
+ * @example
128
+ * supportsTruecolor("truecolor"); // true
129
+ */
130
+ function supportsTruecolor(colorTerm = process.env.COLORTERM) {
131
+ return colorTerm === "truecolor" || colorTerm === "24bit";
132
+ }
133
+ /**
134
+ * The braille spinner glyph for a given elapsed time, advancing one frame per
135
+ * `frameMs`. Deriving the frame from wall-clock elapsed (rather than a tick counter)
136
+ * keeps the spinner correct even when the animation ticker is briefly starved by a
137
+ * synchronous build phase and several ticks coalesce — the glyph still reflects real
138
+ * elapsed time instead of freezing on a stale frame.
139
+ *
140
+ * @param elapsedMs - Milliseconds since the live region opened.
141
+ * @param frameMs - Milliseconds per frame (defaults to `80`).
142
+ * @returns The active spinner glyph.
143
+ * @example
144
+ * spinnerFrameAt(240); // "⠹" (the 4th frame at 80ms/frame)
145
+ */
146
+ function spinnerFrameAt(elapsedMs, frameMs = 80) {
147
+ return SPINNER_FRAMES[Math.floor(Math.max(0, elapsedMs) / frameMs) % SPINNER_FRAMES.length] ?? "⠋";
148
+ }
149
+ /**
150
+ * Select the box glyph set for the given color mode (Unicode on a TTY, ASCII off it).
151
+ *
152
+ * @param color - Whether color/Unicode output is enabled.
153
+ * @returns The matching {@link BoxGlyphs} set.
154
+ * @example
155
+ * const glyphs = boxGlyphs(supportsColor());
156
+ */
157
+ function boxGlyphs(color) {
158
+ return color ? UNICODE_BOX : ASCII_BOX;
159
+ }
160
+ /**
161
+ * The visible width of a string, ignoring any ANSI escape sequences it contains.
162
+ *
163
+ * @param text - The (possibly colorized) text to measure.
164
+ * @returns The number of visible characters.
165
+ * @example
166
+ * visibleWidth(`${ANSI.red}hi${ANSI.reset}`); // 2
167
+ */
168
+ function visibleWidth(text) {
169
+ return text.replaceAll(ANSI_PATTERN, "").length;
170
+ }
171
+ /**
172
+ * Build a {@link Palette} bound to a fixed color mode. When `color` is `false` every
173
+ * helper returns its input unchanged, so the same render code path produces plain
174
+ * output in CI/pipes.
175
+ *
176
+ * @param color - Whether color is enabled (typically `supportsColor()`).
177
+ * @param truecolor - Whether 24-bit output is enabled (typically `supportsTruecolor()`);
178
+ * only consulted by {@link Palette.pink}. Defaults to `false` (16-color magenta).
179
+ * @returns The bound color palette.
180
+ * @example
181
+ * const palette = makePalette(supportsColor(), supportsTruecolor());
182
+ * const line = palette.green("done");
183
+ */
184
+ function makePalette(color, truecolor = false) {
185
+ return {
186
+ enabled: color,
187
+ /**
188
+ * Wrap text in the given ANSI code (returns it unchanged when color is off).
189
+ *
190
+ * @param code - The ANSI SGR code to apply.
191
+ * @param text - The text to colorize.
192
+ * @returns The colorized (or unchanged) text.
193
+ * @example
194
+ * palette.paint(ANSI.green, "ok");
195
+ */
196
+ paint(code, text) {
197
+ return color ? `${code}${text}${ANSI.reset}` : text;
198
+ },
199
+ /**
200
+ * Bold the given text (no-op in plain mode).
201
+ *
202
+ * @param text - The text to embolden.
203
+ * @returns The bold (or unchanged) text.
204
+ * @example
205
+ * palette.bold("title");
206
+ */
207
+ bold(text) {
208
+ return this.paint(ANSI.bold, text);
209
+ },
210
+ /**
211
+ * Dim the given text (no-op in plain mode).
212
+ *
213
+ * @param text - The text to dim.
214
+ * @returns The dim (or unchanged) text.
215
+ * @example
216
+ * palette.dim("· 84ms");
217
+ */
218
+ dim(text) {
219
+ return this.paint(ANSI.dim, text);
220
+ },
221
+ /**
222
+ * Color the given text green (no-op in plain mode).
223
+ *
224
+ * @param text - The text to colorize.
225
+ * @returns The green (or unchanged) text.
226
+ * @example
227
+ * palette.green("✓");
228
+ */
229
+ green(text) {
230
+ return this.paint(ANSI.green, text);
231
+ },
232
+ /**
233
+ * Color the given text yellow (no-op in plain mode).
234
+ *
235
+ * @param text - The text to colorize.
236
+ * @returns The yellow (or unchanged) text.
237
+ * @example
238
+ * palette.yellow("~");
239
+ */
240
+ yellow(text) {
241
+ return this.paint(ANSI.yellow, text);
242
+ },
243
+ /**
244
+ * Color the given text red (no-op in plain mode).
245
+ *
246
+ * @param text - The text to colorize.
247
+ * @returns The red (or unchanged) text.
248
+ * @example
249
+ * palette.red("✗");
250
+ */
251
+ red(text) {
252
+ return this.paint(ANSI.red, text);
253
+ },
254
+ /**
255
+ * Color the given text cyan (no-op in plain mode).
256
+ *
257
+ * @param text - The text to colorize.
258
+ * @returns The cyan (or unchanged) text.
259
+ * @example
260
+ * palette.cyan("http://localhost:4173");
261
+ */
262
+ cyan(text) {
263
+ return this.paint(ANSI.cyan, text);
264
+ },
265
+ /**
266
+ * Color the given text the Moku brand pink: exact `#FF1E6F` (24-bit) when truecolor
267
+ * is enabled, the 16-color `magenta` approximation otherwise, unchanged in plain mode.
268
+ *
269
+ * @param text - The text to colorize.
270
+ * @returns The pink (or unchanged) text.
271
+ * @example
272
+ * palette.pink("▟▙ moku web");
273
+ */
274
+ pink(text) {
275
+ if (!color) return text;
276
+ if (truecolor) return `${fg24(BRAND_PINK.r, BRAND_PINK.g, BRAND_PINK.b)}${text}${ANSI.reset}`;
277
+ return this.paint(ANSI.magenta, text);
278
+ }
279
+ };
280
+ }
281
+ /**
282
+ * Frame a list of already-rendered content lines in a box, padding each line to the
283
+ * widest visible line (or `minInnerWidth`, whichever is larger — so several boxes can be
284
+ * forced to a shared width). Uses Unicode borders when `color` is enabled and ASCII
285
+ * otherwise. Visible width ignores embedded ANSI so colored lines align.
286
+ *
287
+ * @param lines - The content lines (may contain ANSI color codes).
288
+ * @param color - Whether to use Unicode borders (and assume color-capable output).
289
+ * @param minInnerWidth - Minimum inner (content) width to pad every row to. Defaults to `0`.
290
+ * @returns The boxed lines (top border, content rows, bottom border).
291
+ * @example
292
+ * box(["Local: http://localhost:4173"], true, 62);
293
+ */
294
+ function box(lines, color, minInnerWidth = 0) {
295
+ const glyphs = boxGlyphs(color);
296
+ const inner = Math.max(0, minInnerWidth, ...lines.map((line) => visibleWidth(line)));
297
+ const horizontal = glyphs.horizontal.repeat(inner + 2);
298
+ const top = `${glyphs.topLeft}${horizontal}${glyphs.topRight}`;
299
+ const bottom = `${glyphs.bottomLeft}${horizontal}${glyphs.bottomRight}`;
300
+ return [
301
+ top,
302
+ ...lines.map((line) => {
303
+ const pad = " ".repeat(inner - visibleWidth(line));
304
+ return `${glyphs.vertical} ${line}${pad} ${glyphs.vertical}`;
305
+ }),
306
+ bottom
307
+ ];
308
+ }
309
+ //#endregion
310
+ //#region src/cli/console.ts
311
+ /**
312
+ * @file `@moku-labs/common/cli` — the branded console: the shared, **stateless** line
313
+ * vocabulary every Moku CLI prints through so the look never drifts between projects.
314
+ * It is the generic counterpart to a framework's own (stateful) panels: the `▟▙` lockup
315
+ * banner, section `heading`s, `info`/`warn`/`error` lines, `✓/✗ check` rows, plus the
316
+ * `railLine`/`box` builders a project composes its own panels from. Built entirely on the
317
+ * {@link makePalette} primitives, TTY/`NO_COLOR`-aware, every line routed through an
318
+ * injectable sink so tests capture output (and a non-CLI consumer can redirect it).
319
+ */
320
+ /** Default total visible width the lockup rule spans and `railLine` right-aligns to. */
321
+ const DEFAULT_WIDTH$1 = 66;
322
+ /**
323
+ * Create a {@link BrandConsole}. Output flows through the injected sink (default
324
+ * `console.log`/`console.error`) and is colorized only when color is enabled, so the
325
+ * identical render path yields branded color/Unicode on a TTY and plain ASCII in CI/pipes.
326
+ *
327
+ * @param options - Optional sinks, color/truecolor overrides, and width (see
328
+ * {@link BrandConsoleOptions}).
329
+ * @returns The branded console.
330
+ * @example
331
+ * const ui = createBrandConsole();
332
+ * ui.lockup({ wordmark: "moku tool", version: "v1.0.0" });
333
+ * ui.check(true, "config loaded");
334
+ */
335
+ function createBrandConsole(options = {}) {
336
+ const write = options.write ?? ((line) => console.log(line));
337
+ const writeError = options.writeError ?? ((line) => console.error(line));
338
+ const color = options.color ?? supportsColor();
339
+ const palette = makePalette(color, options.truecolor ?? (color && supportsTruecolor()));
340
+ const width = options.width ?? DEFAULT_WIDTH$1;
341
+ const cube = color ? "▟▙" : "*";
342
+ const rule = color ? "─" : "-";
343
+ /**
344
+ * Right-align `right` against `left` within `lineWidth`, measuring visible width so
345
+ * embedded ANSI never throws the alignment off.
346
+ *
347
+ * @param left - The left segment (may contain ANSI).
348
+ * @param right - The right segment (may contain ANSI).
349
+ * @param lineWidth - Total visible width to fill (defaults to the console width).
350
+ * @returns The padded line.
351
+ * @example
352
+ * railLine("left", "right", 20);
353
+ */
354
+ const railLine = (left, right, lineWidth = width) => {
355
+ const gap = Math.max(1, lineWidth - visibleWidth(left) - visibleWidth(right));
356
+ return `${left}${" ".repeat(gap)}${right}`;
357
+ };
358
+ return {
359
+ palette,
360
+ color,
361
+ width,
362
+ /**
363
+ * Write a pre-rendered line verbatim through the stdout sink.
364
+ *
365
+ * @param text - The line to write (defaults to an empty line).
366
+ * @example
367
+ * ui.line(" custom row");
368
+ */
369
+ line(text = "") {
370
+ write(text);
371
+ },
372
+ /**
373
+ * Render the `▟▙ <wordmark>` lockup (cube + bold-pink wordmark + optional label,
374
+ * version right-aligned), a dim hairline rule, and an optional dim facts line.
375
+ *
376
+ * @param opts - The lockup fields (see {@link LockupOptions}).
377
+ * @example
378
+ * ui.lockup({ wordmark: "moku web", label: "build", version: "v1.2.0" });
379
+ */
380
+ lockup(opts) {
381
+ const wordmark = palette.pink(palette.bold(opts.wordmark));
382
+ const label = opts.label ? ` ${palette.dim(opts.label)}` : "";
383
+ write(railLine(` ${palette.pink(cube)} ${wordmark}${label}`, opts.version ? palette.dim(opts.version) : ""));
384
+ write(` ${palette.dim(rule.repeat(width - 1))}`);
385
+ if (opts.facts !== void 0) write(` ${palette.dim(opts.facts)}`);
386
+ },
387
+ /**
388
+ * Render a section heading: a blank line followed by a bold brand-pink label.
389
+ *
390
+ * @param text - The heading label.
391
+ * @example
392
+ * ui.heading("Diagnostics");
393
+ */
394
+ heading(text) {
395
+ write("");
396
+ write(` ${palette.bold(palette.pink(text))}`);
397
+ },
398
+ /**
399
+ * Render a neutral informational line (`› message`), indenting continuation lines.
400
+ *
401
+ * @param message - The line to print.
402
+ * @example
403
+ * ui.info("watching for changes…");
404
+ */
405
+ info(message) {
406
+ const [first = "", ...rest] = message.split("\n");
407
+ write(` ${palette.cyan("›")} ${first}`);
408
+ for (const lineText of rest) write(` ${lineText}`);
409
+ },
410
+ /**
411
+ * Render a warning line (`⚠ message`, to stderr).
412
+ *
413
+ * @param message - The warning to print.
414
+ * @example
415
+ * ui.warn("deploy skipped");
416
+ */
417
+ warn(message) {
418
+ writeError(` ${palette.yellow("⚠")} ${message}`);
419
+ },
420
+ /**
421
+ * Render an error line (`✗ message`, to stderr), optionally with a cause beneath.
422
+ *
423
+ * @param message - The error summary to print.
424
+ * @param cause - Optional underlying error/value printed beneath the summary.
425
+ * @example
426
+ * ui.error("build failed", err);
427
+ */
428
+ error(message, cause) {
429
+ writeError(` ${palette.red("✗")} ${message}`);
430
+ if (cause !== void 0) writeError(String(cause));
431
+ },
432
+ /**
433
+ * Render a diagnostic line — green `✓` / red `✗` + label, with optional dim,
434
+ * indented detail beneath.
435
+ *
436
+ * @param ok - Whether the check passed.
437
+ * @param label - The check label.
438
+ * @param detail - Optional multi-line guidance shown indented under the line.
439
+ * @example
440
+ * ui.check(true, "config loaded");
441
+ */
442
+ check(ok, label, detail) {
443
+ write(` ${ok ? palette.green("✓") : palette.red("✗")} ${label}`);
444
+ if (detail !== void 0) for (const lineText of detail.split("\n")) write(` ${palette.dim(lineText)}`);
445
+ },
446
+ railLine,
447
+ /**
448
+ * Frame the given content lines in a brand box and write the result.
449
+ *
450
+ * @param lines - The content lines (may contain ANSI).
451
+ * @param minInnerWidth - Minimum inner width to pad every row to. Defaults to `0`.
452
+ * @example
453
+ * ui.box(["Local http://localhost:4173"]);
454
+ */
455
+ box(lines, minInnerWidth = 0) {
456
+ for (const lineText of box(lines, color, minInnerWidth)) write(lineText);
457
+ }
458
+ };
459
+ }
460
+ //#endregion
461
+ //#region src/cli/log-sink.ts
462
+ /** Severity rank for threshold comparison (higher = more severe). Mirrors the log plugin. */
463
+ const LEVEL_RANK = {
464
+ debug: 10,
465
+ info: 20,
466
+ warn: 30,
467
+ error: 40
468
+ };
469
+ /**
470
+ * Render an entry's optional structured `data` as a compact, dim suffix. Falls back to
471
+ * `String(data)` when it is not JSON-serializable (e.g. a circular object).
472
+ *
473
+ * @param ui - The brand console (for its palette).
474
+ * @param data - The entry's structured payload.
475
+ * @returns A leading-space dim suffix, or `""` when there is no data.
476
+ * @example
477
+ * formatData(ui, { count: 12 }); // ' {"count":12}' (dim)
478
+ */
479
+ function formatData(ui, data) {
480
+ if (data === void 0) return "";
481
+ let text;
482
+ try {
483
+ text = JSON.stringify(data);
484
+ } catch {
485
+ text = String(data);
486
+ }
487
+ return text === void 0 ? "" : ` ${ui.palette.dim(text)}`;
488
+ }
489
+ /**
490
+ * Build a branded log {@link LogSink}: routes each entry to the matching brand line —
491
+ * `error` → `✗` (stderr), `warn` → `⚠` (stderr), `info` → `›`, `debug` → dim — with any
492
+ * structured `data` appended dim. Entries below `minLevel` are dropped (the in-memory
493
+ * trace still records everything). TTY/`NO_COLOR`-aware via the brand console.
494
+ *
495
+ * @param minLevel - Lowest severity to print. Defaults to `"debug"` (print all).
496
+ * @returns A {@link LogSink} that writes branded lines to stdout/stderr.
497
+ * @example
498
+ * ctx.log.clearSinks();
499
+ * ctx.log.addSink(brandedSink("info")); // suppress debug spam, branded output
500
+ */
501
+ function brandedSink(minLevel = "debug") {
502
+ const threshold = LEVEL_RANK[minLevel];
503
+ const ui = createBrandConsole();
504
+ return {
505
+ /**
506
+ * Render one entry as a branded line matching its level (dropping entries below
507
+ * the threshold).
508
+ *
509
+ * @param entry - The entry to emit.
510
+ * @example
511
+ * sink.write({ level: "info", event: "deploy:done", ts: 0 });
512
+ */
513
+ write(entry) {
514
+ if (LEVEL_RANK[entry.level] < threshold) return;
515
+ const message = `${entry.event}${formatData(ui, entry.data)}`;
516
+ switch (entry.level) {
517
+ case "error":
518
+ ui.error(message);
519
+ break;
520
+ case "warn":
521
+ ui.warn(message);
522
+ break;
523
+ case "debug":
524
+ ui.line(` ${ui.palette.dim(message)}`);
525
+ break;
526
+ default: ui.info(message);
527
+ }
528
+ } };
529
+ }
530
+ //#endregion
531
+ //#region src/cli/prompts.ts
532
+ /**
533
+ * @file `@moku-labs/common/cli` — branded interactive prompts (`confirm` y/N and
534
+ * `select` one-of-N) styled with the brand `◆` marker, the dim hint, and the cyan `›`
535
+ * caret, so a guided flow in any Moku CLI looks the same. Built on `node:readline`; the
536
+ * input/output streams and the choices-block sink are injectable so tests drive prompts
537
+ * without a real TTY. Off a color TTY (CI/pipes) every prompt degrades to a plain form.
538
+ */
539
+ /** Default prompt rail width — matches the brand console so hints align with other rows. */
540
+ const DEFAULT_WIDTH = 66;
541
+ /** Matches an explicit affirmative answer (`y`/`yes`, case-insensitive). */
542
+ const YES_PATTERN = /^y(es)?$/i;
543
+ /**
544
+ * Create {@link BrandPrompts} bound to a color mode + streams. Styling matches the brand
545
+ * console (the `◆` marker, dim hints, cyan caret); off a color TTY every prompt uses the
546
+ * plain `question [y/N]` / `question [1-N]` form.
547
+ *
548
+ * @param options - Optional color/width overrides and injectable streams/sink (see
549
+ * {@link BrandPromptsOptions}).
550
+ * @returns The branded prompts.
551
+ * @example
552
+ * const prompts = createBrandPrompts();
553
+ * const i = await prompts.select("Workflow?", ["Auto", "Manual"]);
554
+ */
555
+ function createBrandPrompts(options = {}) {
556
+ const color = options.color ?? supportsColor();
557
+ const palette = makePalette(color, options.truecolor ?? (color && supportsTruecolor()));
558
+ const width = options.width ?? DEFAULT_WIDTH;
559
+ const input = options.input ?? process.stdin;
560
+ const output = options.output ?? process.stdout;
561
+ const write = options.write ?? ((block) => console.log(block));
562
+ /**
563
+ * Build the y/N prompt string: the styled `◆ question … y / N ›` rail on a color TTY,
564
+ * else the plain `question [y/N] ` form.
565
+ *
566
+ * @param question - The yes/no question to display.
567
+ * @returns The readline prompt string.
568
+ * @example
569
+ * confirmPrompt("Deploy?");
570
+ */
571
+ const confirmPrompt = (question) => {
572
+ if (!color) return `${question} [y/N] `;
573
+ const left = ` ${palette.pink("◆")} ${question}`;
574
+ const right = `${palette.dim("y / N")} ${palette.cyan("›")} `;
575
+ const gap = Math.max(1, width - visibleWidth(left) - visibleWidth(right));
576
+ return `${left}${" ".repeat(gap)}${right}`;
577
+ };
578
+ /**
579
+ * Build the select choices block: the styled `◆ question` head + dim-numbered rows on a
580
+ * color TTY, else the plain ` N) label` list.
581
+ *
582
+ * @param question - The prompt shown above the choices (styled mode only).
583
+ * @param choices - The selectable option labels.
584
+ * @returns The multi-line choices block.
585
+ * @example
586
+ * choicesBlock("Pick", ["a", "b"]);
587
+ */
588
+ const choicesBlock = (question, choices) => {
589
+ if (!color) return choices.map((choice, index) => ` ${index + 1}) ${choice}`).join("\n");
590
+ return [` ${palette.pink("◆")} ${question}`, ...choices.map((choice, index) => ` ${palette.dim(String(index + 1))} ${choice}`)].join("\n");
591
+ };
592
+ /**
593
+ * Build the select input prompt: the dim `pick 1–N ›` hint on a color TTY, else the
594
+ * plain `question [1-N] ` form.
595
+ *
596
+ * @param question - The prompt (used only by the plain fallback).
597
+ * @param count - The number of choices.
598
+ * @returns The readline prompt string.
599
+ * @example
600
+ * selectPrompt("Pick", 3);
601
+ */
602
+ const selectPrompt = (question, count) => {
603
+ if (!color) return `${question} [1-${count}] `;
604
+ return ` ${palette.dim(`pick 1–${count}`)} ${palette.cyan("›")} `;
605
+ };
606
+ return {
607
+ /**
608
+ * Ask a yes/no question; resolves `true` only on an explicit `y`/`yes`.
609
+ *
610
+ * @param question - The yes/no question to display.
611
+ * @returns Resolves `true` when the user answered yes.
612
+ * @example
613
+ * await prompts.confirm("Deploy?");
614
+ */
615
+ confirm(question) {
616
+ return new Promise((resolve) => {
617
+ const readline = (0, node_readline.createInterface)({
618
+ input,
619
+ output
620
+ });
621
+ readline.question(confirmPrompt(question), (answer) => {
622
+ readline.close();
623
+ resolve(YES_PATTERN.test(answer.trim()));
624
+ });
625
+ });
626
+ },
627
+ /**
628
+ * Present `choices` numbered from 1 and resolve the chosen zero-based index.
629
+ *
630
+ * @param question - The prompt to display.
631
+ * @param choices - The selectable option labels.
632
+ * @returns Resolves the chosen zero-based index (`0` for empty/out-of-range).
633
+ * @example
634
+ * await prompts.select("Pick", ["a", "b"]);
635
+ */
636
+ select(question, choices) {
637
+ return new Promise((resolve) => {
638
+ const readline = (0, node_readline.createInterface)({
639
+ input,
640
+ output
641
+ });
642
+ write(choicesBlock(question, choices));
643
+ readline.question(selectPrompt(question, choices.length), (answer) => {
644
+ readline.close();
645
+ const picked = Number.parseInt(answer.trim(), 10);
646
+ resolve(Number.isInteger(picked) && picked >= 1 && picked <= choices.length ? picked - 1 : 0);
647
+ });
648
+ });
649
+ }
650
+ };
651
+ }
652
+ //#endregion
653
+ exports.ANSI = ANSI;
654
+ exports.BRAND_PINK = BRAND_PINK;
655
+ exports.CLEAR_BELOW = CLEAR_BELOW;
656
+ exports.CLEAR_LINE = CLEAR_LINE;
657
+ exports.SPINNER_FRAMES = SPINNER_FRAMES;
658
+ exports.box = box;
659
+ exports.boxGlyphs = boxGlyphs;
660
+ exports.brandedSink = brandedSink;
661
+ exports.createBrandConsole = createBrandConsole;
662
+ exports.createBrandPrompts = createBrandPrompts;
663
+ exports.cursorUp = cursorUp;
664
+ exports.fg24 = fg24;
665
+ exports.makePalette = makePalette;
666
+ exports.spinnerFrameAt = spinnerFrameAt;
667
+ exports.supportsColor = supportsColor;
668
+ exports.supportsTruecolor = supportsTruecolor;
669
+ exports.visibleWidth = visibleWidth;