@cruxy/cli 0.9.0 → 0.11.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.
Files changed (48) hide show
  1. package/dist/approval/classify.js +21 -0
  2. package/dist/approval/policy.js +6 -0
  3. package/dist/approval/prompt.js +8 -29
  4. package/dist/approval/types.d.ts +5 -0
  5. package/dist/cli/commands/rollback.js +45 -0
  6. package/dist/cli/commands/test.d.ts +9 -0
  7. package/dist/cli/commands/test.js +47 -0
  8. package/dist/cli/program.js +2 -0
  9. package/dist/cli/repl.d.ts +5 -0
  10. package/dist/cli/repl.js +17 -0
  11. package/dist/cli/session-factory.js +6 -2
  12. package/dist/components/autocomplete.d.ts +32 -0
  13. package/dist/components/autocomplete.js +50 -0
  14. package/dist/components/frame.d.ts +25 -0
  15. package/dist/components/frame.js +49 -0
  16. package/dist/components/fuzzy.d.ts +61 -0
  17. package/dist/components/fuzzy.js +174 -0
  18. package/dist/components/index.d.ts +6 -0
  19. package/dist/components/index.js +6 -0
  20. package/dist/components/input.d.ts +78 -0
  21. package/dist/components/input.js +111 -0
  22. package/dist/components/keys.d.ts +48 -0
  23. package/dist/components/keys.js +105 -0
  24. package/dist/components/select.d.ts +28 -0
  25. package/dist/components/select.js +69 -0
  26. package/dist/config/schema.d.ts +47 -0
  27. package/dist/config/schema.js +20 -0
  28. package/dist/errors/constructors.d.ts +12 -0
  29. package/dist/errors/constructors.js +31 -0
  30. package/dist/errors/types.d.ts +4 -0
  31. package/dist/errors/types.js +10 -0
  32. package/dist/onboarding/io.d.ts +3 -2
  33. package/dist/onboarding/io.js +35 -81
  34. package/dist/testing/detect.d.ts +3 -0
  35. package/dist/testing/detect.js +44 -0
  36. package/dist/testing/index.d.ts +5 -0
  37. package/dist/testing/index.js +5 -0
  38. package/dist/testing/parse.d.ts +33 -0
  39. package/dist/testing/parse.js +137 -0
  40. package/dist/testing/run-tests-tool.d.ts +42 -0
  41. package/dist/testing/run-tests-tool.js +128 -0
  42. package/dist/testing/runner.d.ts +26 -0
  43. package/dist/testing/runner.js +124 -0
  44. package/dist/testing/types.d.ts +61 -0
  45. package/dist/testing/types.js +7 -0
  46. package/dist/tools/registry.js +3 -0
  47. package/dist/tools/types.d.ts +2 -2
  48. package/package.json +1 -1
@@ -0,0 +1,174 @@
1
+ import pc from "picocolors";
2
+ import { createFrame } from "./frame.js";
3
+ import { defaultComponentIO, resolveNonInteractive, } from "./input.js";
4
+ /** Word-boundary characters that earn the boundary bonus for the NEXT char. */
5
+ const SEPARATORS = new Set(["/", "-", "_", ".", " "]);
6
+ /** Per-character score weights — the entire ranking formula. */
7
+ const BASE = 1; // every matched character
8
+ const CONSECUTIVE = 2; // extra when adjacent to the previous match
9
+ const BOUNDARY = 2; // extra at label start or right after a separator
10
+ /**
11
+ * Case-insensitive greedy-leftmost subsequence match.
12
+ * - Empty query matches everything: score 0, no positions (nothing to
13
+ * highlight, nothing to fabricate).
14
+ * - Not a subsequence → `null`.
15
+ * - Score = Σ per matched char: {@link BASE} + {@link CONSECUTIVE} when the
16
+ * match continues a run + {@link BOUNDARY} when it starts a word.
17
+ * Deterministic by construction — same inputs, same output, no randomness,
18
+ * no length normalization (ties break in {@link rankItems}).
19
+ */
20
+ export function fuzzyScore(query, label) {
21
+ if (query === "")
22
+ return { score: 0, positions: [] };
23
+ const q = query.toLowerCase();
24
+ const l = label.toLowerCase();
25
+ const positions = [];
26
+ let score = 0;
27
+ let li = 0;
28
+ for (let qi = 0; qi < q.length; qi++) {
29
+ const idx = l.indexOf(q[qi], li);
30
+ if (idx === -1)
31
+ return null;
32
+ score += BASE;
33
+ if (positions.length > 0 && idx === positions[positions.length - 1] + 1) {
34
+ score += CONSECUTIVE;
35
+ }
36
+ if (idx === 0 || SEPARATORS.has(label[idx - 1])) {
37
+ score += BOUNDARY;
38
+ }
39
+ positions.push(idx);
40
+ li = idx + 1;
41
+ }
42
+ return { score, positions };
43
+ }
44
+ /**
45
+ * Filter + rank a list against a query. Ordering is fully stable and
46
+ * deterministic: score descending, then shorter label, then original index.
47
+ * An empty query returns every item in original order.
48
+ */
49
+ export function rankItems(items, toLabel, query) {
50
+ // Empty query: everything matches with score 0 — original order IS the
51
+ // ranking (the length tie-break must not silently reorder the full list).
52
+ if (query === "") {
53
+ return items.map((item) => ({
54
+ item,
55
+ label: toLabel(item),
56
+ match: { score: 0, positions: [] },
57
+ }));
58
+ }
59
+ const ranked = [];
60
+ for (const [index, item] of items.entries()) {
61
+ const label = toLabel(item);
62
+ const match = fuzzyScore(query, label);
63
+ if (match)
64
+ ranked.push({ item, label, match, index });
65
+ }
66
+ ranked.sort((a, b) => b.match.score - a.match.score ||
67
+ a.label.length - b.label.length ||
68
+ a.index - b.index);
69
+ return ranked.map(({ item, label, match }) => ({ item, label, match }));
70
+ }
71
+ /**
72
+ * Bold the matched characters of a label. With color off (NO_COLOR, pipe)
73
+ * picocolors' disabled palette is the identity — plain text, zero ANSI.
74
+ */
75
+ export function highlightMatch(label, positions, colors) {
76
+ if (positions.length === 0)
77
+ return label;
78
+ const matched = new Set(positions);
79
+ let out = "";
80
+ for (let i = 0; i < label.length; i++) {
81
+ out += matched.has(i) ? colors.bold(colors.cyan(label[i])) : label[i];
82
+ }
83
+ return out;
84
+ }
85
+ /**
86
+ * Interactive fuzzy finder: type to filter, ↑/↓ to move through the ranked
87
+ * results, Enter to select the highlighted item (inert while there are no
88
+ * matches), Esc / Ctrl-C / EOF to cancel. The transient frame is fully erased
89
+ * before resolving — the screen keeps no trace of the interaction.
90
+ */
91
+ export async function fuzzyFind(items, opts, io = defaultComponentIO()) {
92
+ const fallback = resolveNonInteractive(io, opts.title ?? "this picker", opts.defaultValue, opts.nonInteractiveHint);
93
+ if (fallback)
94
+ return fallback;
95
+ if (items.length === 0)
96
+ return { kind: "cancelled" };
97
+ const colors = pc.createColors(io.caps.color);
98
+ const maxVisible = opts.maxVisible ?? 10;
99
+ const frame = createFrame(io.write, io.caps);
100
+ let query = "";
101
+ let cursor = 0; // index into the ranked results
102
+ const paint = (ranked) => {
103
+ const lines = [];
104
+ if (opts.title)
105
+ lines.push(colors.bold(opts.title));
106
+ lines.push(`${colors.cyan("›")} ${query}${colors.dim("▏")}`);
107
+ if (ranked.length === 0) {
108
+ lines.push(colors.dim(" no results — backspace to widen"));
109
+ }
110
+ else {
111
+ // Keep the highlighted row inside the viewport.
112
+ const top = Math.min(Math.max(0, cursor - maxVisible + 1), Math.max(0, ranked.length - maxVisible));
113
+ const visible = ranked.slice(top, top + maxVisible);
114
+ for (const [i, row] of visible.entries()) {
115
+ const selected = top + i === cursor;
116
+ const marker = selected ? colors.cyan("❯") : " ";
117
+ const label = highlightMatch(row.label, row.match.positions, colors);
118
+ lines.push(`${marker} ${selected ? label : colors.dim(label)}`);
119
+ }
120
+ const hidden = ranked.length - visible.length;
121
+ if (hidden > 0)
122
+ lines.push(colors.dim(` … ${hidden} more`));
123
+ }
124
+ frame.render(lines);
125
+ };
126
+ io.keys.begin();
127
+ try {
128
+ let ranked = rankItems(items, opts.toLabel, query);
129
+ paint(ranked);
130
+ for (;;) {
131
+ const key = await io.keys.read();
132
+ switch (key.kind) {
133
+ case "ctrl-c":
134
+ case "eof":
135
+ case "escape":
136
+ return { kind: "cancelled" };
137
+ case "enter":
138
+ if (ranked.length === 0)
139
+ break; // inert in the no-results state
140
+ return { kind: "selected", value: ranked[cursor].item };
141
+ case "up":
142
+ if (ranked.length > 0) {
143
+ cursor = (cursor - 1 + ranked.length) % ranked.length;
144
+ }
145
+ break;
146
+ case "down":
147
+ if (ranked.length > 0)
148
+ cursor = (cursor + 1) % ranked.length;
149
+ break;
150
+ case "backspace":
151
+ if (query.length > 0) {
152
+ query = query.slice(0, -1);
153
+ ranked = rankItems(items, opts.toLabel, query);
154
+ cursor = 0;
155
+ }
156
+ break;
157
+ case "char":
158
+ query += key.char;
159
+ ranked = rankItems(items, opts.toLabel, query);
160
+ cursor = 0;
161
+ break;
162
+ default:
163
+ break; // tab / left / right: no meaning here
164
+ }
165
+ paint(ranked);
166
+ }
167
+ }
168
+ finally {
169
+ // Both on selection and on cancel: erase the frame and leave raw mode —
170
+ // no leftover artifact bytes, terminal always restored.
171
+ frame.clear();
172
+ io.keys.restore();
173
+ }
174
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./keys.js";
2
+ export * from "./input.js";
3
+ export * from "./frame.js";
4
+ export * from "./select.js";
5
+ export * from "./fuzzy.js";
6
+ export * from "./autocomplete.js";
@@ -0,0 +1,6 @@
1
+ export * from "./keys.js";
2
+ export * from "./input.js";
3
+ export * from "./frame.js";
4
+ export * from "./select.js";
5
+ export * from "./fuzzy.js";
6
+ export * from "./autocomplete.js";
@@ -0,0 +1,78 @@
1
+ import type { RenderCapabilities } from "../render/index.js";
2
+ import { type Key } from "./keys.js";
3
+ /**
4
+ * The one raw-mode input reader (U.7). Every interactive component — and the
5
+ * refactored approval/onboarding key readers — reads keys through this seam;
6
+ * nothing else in the CLI touches `setRawMode`. The lifecycle is strict:
7
+ * `begin()` → `read()` loop → `restore()` in a `finally`, so the terminal is
8
+ * never left in raw mode on any exit path (selection, cancel, throw).
9
+ */
10
+ /** The minimal stdin surface the reader needs. Injectable for tests. */
11
+ export interface RawInput {
12
+ isTTY?: boolean;
13
+ setRawMode?(mode: boolean): unknown;
14
+ resume(): unknown;
15
+ pause(): unknown;
16
+ on(event: "data" | "end", listener: (chunk: Buffer) => void): unknown;
17
+ removeListener(event: "data" | "end", listener: (chunk: Buffer) => void): unknown;
18
+ }
19
+ /** Raw-mode key source with an explicit begin/read/restore lifecycle. */
20
+ export interface KeyReader {
21
+ /** Enter raw mode and start decoding. Safe to call once per interaction. */
22
+ begin(): void;
23
+ /**
24
+ * The next decoded key. After stream end (or `restore()`), resolves
25
+ * `{kind:"eof"}` forever — a component's read loop can never hang or reject.
26
+ */
27
+ read(): Promise<Key>;
28
+ /** Leave raw mode, detach, pause. Idempotent; call in `finally`, always. */
29
+ restore(): void;
30
+ }
31
+ /** Build the real reader over `stdin` (or an injected fake in tests). */
32
+ export declare function createKeyReader(stdin?: RawInput): KeyReader;
33
+ /**
34
+ * Read exactly one key with the full begin/restore lifecycle — the shared
35
+ * backend for the approval prompt's single-key read and the onboarding
36
+ * `readKey`. Resolves the printable character, `"\n"` for enter, and `""` for
37
+ * anything that means "no answer" (Ctrl-C, EOF, escape, arrows) — preserving
38
+ * the callers' default-deny mapping.
39
+ */
40
+ export declare function readSingleKey(stdin?: RawInput): Promise<string>;
41
+ /**
42
+ * Every component resolves to a selection or a clean, typed cancellation
43
+ * (Ctrl-C / EOF / escape). Cancellation is data for the caller to interpret —
44
+ * never a thrown error, never a partial value.
45
+ */
46
+ export type InteractiveResult<T> = {
47
+ kind: "selected";
48
+ value: T;
49
+ } | {
50
+ kind: "cancelled";
51
+ };
52
+ /**
53
+ * What a component needs from the environment, bundled so tests can script
54
+ * all of it. `caps` is the existing U.2 capability detection — components
55
+ * never re-probe NO_COLOR / width / TTY themselves.
56
+ */
57
+ export interface ComponentIO {
58
+ caps: RenderCapabilities;
59
+ /**
60
+ * The whole interactive contract in one flag: stdin is a TTY *and* the
61
+ * output supports cursor control (`TERM=dumb` fails this). When false, no
62
+ * frame is drawn and no key is read — ever.
63
+ */
64
+ interactive: boolean;
65
+ /** Transient frame bytes. Defaults to stderr so stdout stays pipe-clean. */
66
+ write(text: string): void;
67
+ keys: KeyReader;
68
+ }
69
+ /** The real environment: frames to stderr, keys from stdin, caps from stderr. */
70
+ export declare function defaultComponentIO(): ComponentIO;
71
+ /**
72
+ * The shared non-TTY gate, run before any frame byte or key read:
73
+ * - interactive → proceed;
74
+ * - not interactive + a default was supplied → resolve to it immediately;
75
+ * - otherwise → throw `CRUXY_E_INTERACTIVE_REQUIRED` (usage, exit 2).
76
+ * Never blocks on a pipe, never silently picks an option.
77
+ */
78
+ export declare function resolveNonInteractive<T>(io: ComponentIO, what: string, defaultValue: T | undefined, alternatives?: string[]): InteractiveResult<T> | null;
@@ -0,0 +1,111 @@
1
+ import { interactiveRequired } from "../errors/index.js";
2
+ import { detectCapabilities } from "../render/index.js";
3
+ import { decodeKeys } from "./keys.js";
4
+ /** Build the real reader over `stdin` (or an injected fake in tests). */
5
+ export function createKeyReader(stdin = process.stdin) {
6
+ const queue = [];
7
+ const waiters = [];
8
+ let active = false;
9
+ let ended = false;
10
+ const push = (key) => {
11
+ const waiter = waiters.shift();
12
+ if (waiter)
13
+ waiter(key);
14
+ else
15
+ queue.push(key);
16
+ };
17
+ const onData = (chunk) => {
18
+ for (const key of decodeKeys(chunk))
19
+ push(key);
20
+ };
21
+ const onEnd = () => {
22
+ ended = true;
23
+ // Wake every waiter: EOF is a key, not an error.
24
+ while (waiters.length > 0)
25
+ push({ kind: "eof" });
26
+ };
27
+ return {
28
+ begin() {
29
+ if (active)
30
+ return;
31
+ active = true;
32
+ if (stdin.isTTY)
33
+ stdin.setRawMode?.(true);
34
+ stdin.resume();
35
+ stdin.on("data", onData);
36
+ stdin.on("end", onEnd);
37
+ },
38
+ read() {
39
+ const next = queue.shift();
40
+ if (next)
41
+ return Promise.resolve(next);
42
+ if (ended || !active)
43
+ return Promise.resolve({ kind: "eof" });
44
+ return new Promise((resolve) => waiters.push(resolve));
45
+ },
46
+ restore() {
47
+ if (!active)
48
+ return;
49
+ active = false;
50
+ stdin.removeListener("data", onData);
51
+ stdin.removeListener("end", onEnd);
52
+ if (stdin.isTTY)
53
+ stdin.setRawMode?.(false);
54
+ stdin.pause();
55
+ // Unblock anything still awaiting a key — restore means the interaction
56
+ // is over, and a hung promise would leak the caller.
57
+ while (waiters.length > 0)
58
+ waiters.shift()({ kind: "eof" });
59
+ },
60
+ };
61
+ }
62
+ /**
63
+ * Read exactly one key with the full begin/restore lifecycle — the shared
64
+ * backend for the approval prompt's single-key read and the onboarding
65
+ * `readKey`. Resolves the printable character, `"\n"` for enter, and `""` for
66
+ * anything that means "no answer" (Ctrl-C, EOF, escape, arrows) — preserving
67
+ * the callers' default-deny mapping.
68
+ */
69
+ export async function readSingleKey(stdin = process.stdin) {
70
+ const keys = createKeyReader(stdin);
71
+ keys.begin();
72
+ try {
73
+ const key = await keys.read();
74
+ switch (key.kind) {
75
+ case "char":
76
+ return key.char;
77
+ case "enter":
78
+ return "\n";
79
+ default:
80
+ return "";
81
+ }
82
+ }
83
+ finally {
84
+ keys.restore();
85
+ }
86
+ }
87
+ /** The real environment: frames to stderr, keys from stdin, caps from stderr. */
88
+ export function defaultComponentIO() {
89
+ const caps = detectCapabilities(process.stderr);
90
+ return {
91
+ caps,
92
+ interactive: Boolean(process.stdin.isTTY) && caps.cursor,
93
+ write: (text) => void process.stderr.write(text),
94
+ keys: createKeyReader(process.stdin),
95
+ };
96
+ }
97
+ /**
98
+ * The shared non-TTY gate, run before any frame byte or key read:
99
+ * - interactive → proceed;
100
+ * - not interactive + a default was supplied → resolve to it immediately;
101
+ * - otherwise → throw `CRUXY_E_INTERACTIVE_REQUIRED` (usage, exit 2).
102
+ * Never blocks on a pipe, never silently picks an option.
103
+ */
104
+ export function resolveNonInteractive(io, what, defaultValue, alternatives = []) {
105
+ if (io.interactive)
106
+ return null;
107
+ if (defaultValue !== undefined) {
108
+ return { kind: "selected", value: defaultValue };
109
+ }
110
+ throw interactiveRequired(what, alternatives);
111
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Byte → key decoding for the interactive components (U.7). Pure data
3
+ * transformation — no terminal, no state — so every mapping row is directly
4
+ * unit-testable. The stateful raw-mode plumbing lives in `input.ts`.
5
+ */
6
+ /** One decoded keypress. The full vocabulary the U.7 components consume. */
7
+ export type Key =
8
+ /** A printable character (UTF-8; may be multi-byte, never a control char). */
9
+ {
10
+ kind: "char";
11
+ char: string;
12
+ } | {
13
+ kind: "enter";
14
+ } | {
15
+ kind: "backspace";
16
+ } | {
17
+ kind: "tab";
18
+ } | {
19
+ kind: "escape";
20
+ } | {
21
+ kind: "up";
22
+ } | {
23
+ kind: "down";
24
+ } | {
25
+ kind: "left";
26
+ } | {
27
+ kind: "right";
28
+ }
29
+ /** Ctrl-C in raw mode (no SIGINT is delivered) — components must cancel. */
30
+ | {
31
+ kind: "ctrl-c";
32
+ }
33
+ /** Ctrl-D or stream end — components must cancel. */
34
+ | {
35
+ kind: "eof";
36
+ };
37
+ /**
38
+ * Decode one raw-mode chunk into keys. A paste or fast typing delivers many
39
+ * keys per chunk; all are returned in order.
40
+ *
41
+ * Escape handling is deliberately simple: `ESC [ A..D` decodes to an arrow,
42
+ * any other CSI sequence (`ESC [ …final`) is swallowed whole (unmapped keys
43
+ * must not leak garbage chars into a query), and a lone ESC decodes to
44
+ * `escape`. Terminals send arrow sequences atomically in practice; a sequence
45
+ * split across chunks degrades to `escape` + literal chars, which is safe
46
+ * (escape cancels).
47
+ */
48
+ export declare function decodeKeys(chunk: Buffer | string): Key[];
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Byte → key decoding for the interactive components (U.7). Pure data
3
+ * transformation — no terminal, no state — so every mapping row is directly
4
+ * unit-testable. The stateful raw-mode plumbing lives in `input.ts`.
5
+ */
6
+ const CTRL_C = 0x03;
7
+ const CTRL_D = 0x04;
8
+ const BACKSPACE = 0x08;
9
+ const TAB = 0x09;
10
+ const LF = 0x0a;
11
+ const CR = 0x0d;
12
+ const ESC = 0x1b;
13
+ const DELETE = 0x7f;
14
+ /** CSI final byte → arrow key, for `ESC [ <final>` sequences. */
15
+ const ARROWS = {
16
+ 0x41: "up", // A
17
+ 0x42: "down", // B
18
+ 0x43: "right", // C
19
+ 0x44: "left", // D
20
+ };
21
+ /**
22
+ * Decode one raw-mode chunk into keys. A paste or fast typing delivers many
23
+ * keys per chunk; all are returned in order.
24
+ *
25
+ * Escape handling is deliberately simple: `ESC [ A..D` decodes to an arrow,
26
+ * any other CSI sequence (`ESC [ …final`) is swallowed whole (unmapped keys
27
+ * must not leak garbage chars into a query), and a lone ESC decodes to
28
+ * `escape`. Terminals send arrow sequences atomically in practice; a sequence
29
+ * split across chunks degrades to `escape` + literal chars, which is safe
30
+ * (escape cancels).
31
+ */
32
+ export function decodeKeys(chunk) {
33
+ const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
34
+ const keys = [];
35
+ for (let i = 0; i < buf.length;) {
36
+ const byte = buf[i];
37
+ if (byte === ESC) {
38
+ if (buf[i + 1] === 0x5b /* [ */) {
39
+ // CSI: consume parameter/intermediate bytes (0x20–0x3f) up to the
40
+ // final byte (0x40–0x7e); map arrows, swallow everything else.
41
+ let j = i + 2;
42
+ while (j < buf.length && buf[j] >= 0x20 && buf[j] <= 0x3f)
43
+ j++;
44
+ if (j < buf.length) {
45
+ // Only a bare `ESC [ <final>` maps to an arrow; parameterized
46
+ // sequences (modifier arrows, Home/End variants) are swallowed —
47
+ // an unmapped combo must do nothing, not act as a plain arrow.
48
+ const arrow = j === i + 2 ? ARROWS[buf[j]] : undefined;
49
+ if (arrow)
50
+ keys.push({ kind: arrow });
51
+ i = j + 1;
52
+ continue;
53
+ }
54
+ // Truncated CSI at chunk end: treat as escape, drop the partial tail.
55
+ keys.push({ kind: "escape" });
56
+ i = buf.length;
57
+ continue;
58
+ }
59
+ keys.push({ kind: "escape" });
60
+ i++;
61
+ continue;
62
+ }
63
+ if (byte === CTRL_C) {
64
+ keys.push({ kind: "ctrl-c" });
65
+ i++;
66
+ continue;
67
+ }
68
+ if (byte === CTRL_D) {
69
+ keys.push({ kind: "eof" });
70
+ i++;
71
+ continue;
72
+ }
73
+ if (byte === CR || byte === LF) {
74
+ keys.push({ kind: "enter" });
75
+ // Swallow a CRLF pair as one enter.
76
+ if (byte === CR && buf[i + 1] === LF)
77
+ i++;
78
+ i++;
79
+ continue;
80
+ }
81
+ if (byte === BACKSPACE || byte === DELETE) {
82
+ keys.push({ kind: "backspace" });
83
+ i++;
84
+ continue;
85
+ }
86
+ if (byte === TAB) {
87
+ keys.push({ kind: "tab" });
88
+ i++;
89
+ continue;
90
+ }
91
+ if (byte < 0x20) {
92
+ // Other control chars: ignore (same rule as the secret reader).
93
+ i++;
94
+ continue;
95
+ }
96
+ // Printable: consume one UTF-8 code point (1–4 bytes by lead byte).
97
+ const len = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
98
+ keys.push({
99
+ kind: "char",
100
+ char: buf.subarray(i, Math.min(i + len, buf.length)).toString("utf8"),
101
+ });
102
+ i += len;
103
+ }
104
+ return keys;
105
+ }
@@ -0,0 +1,28 @@
1
+ import { type ComponentIO, type InteractiveResult } from "./input.js";
2
+ /**
3
+ * SelectList (U.7): arrow-key pick from a short list of options. Single-select
4
+ * only — multi-select is a deliberate seam for a later build (the result type
5
+ * and key loop extend without breaking callers).
6
+ */
7
+ export interface SelectOptions<T> {
8
+ /** Label an item renders under. Defaults to `String(item)`. */
9
+ toLabel?: (item: T) => string;
10
+ /** Header row above the options. */
11
+ title?: string;
12
+ /** Index highlighted first (so Enter-once picks a sensible default). */
13
+ initialIndex?: number;
14
+ /** Non-TTY fallback: resolve to this instead of failing loud. */
15
+ defaultValue?: T;
16
+ /** `--flag` alternatives listed in the non-TTY error. */
17
+ nonInteractiveHint?: string[];
18
+ /** Visible rows before the list scrolls (default 10). */
19
+ maxVisible?: number;
20
+ }
21
+ /**
22
+ * Pick one item: ↑/↓ move (wrapping past either end), Enter selects the
23
+ * highlighted item, Esc / Ctrl-C / EOF cancel. Renders a transient frame via
24
+ * the shared U.7 frame (width-truncated rows, no soft-wrap) and erases it
25
+ * completely before resolving. Empty `items` resolves cancelled — there is
26
+ * nothing to select.
27
+ */
28
+ export declare function selectList<T>(items: readonly T[], opts?: SelectOptions<T>, io?: ComponentIO): Promise<InteractiveResult<T>>;
@@ -0,0 +1,69 @@
1
+ import pc from "picocolors";
2
+ import { createFrame } from "./frame.js";
3
+ import { defaultComponentIO, resolveNonInteractive, } from "./input.js";
4
+ /**
5
+ * Pick one item: ↑/↓ move (wrapping past either end), Enter selects the
6
+ * highlighted item, Esc / Ctrl-C / EOF cancel. Renders a transient frame via
7
+ * the shared U.7 frame (width-truncated rows, no soft-wrap) and erases it
8
+ * completely before resolving. Empty `items` resolves cancelled — there is
9
+ * nothing to select.
10
+ */
11
+ export async function selectList(items, opts = {}, io = defaultComponentIO()) {
12
+ const fallback = resolveNonInteractive(io, opts.title ?? "this picker", opts.defaultValue, opts.nonInteractiveHint);
13
+ if (fallback)
14
+ return fallback;
15
+ if (items.length === 0)
16
+ return { kind: "cancelled" };
17
+ const toLabel = opts.toLabel ?? ((item) => String(item));
18
+ const colors = pc.createColors(io.caps.color);
19
+ const maxVisible = opts.maxVisible ?? 10;
20
+ const frame = createFrame(io.write, io.caps);
21
+ let cursor = Math.min(Math.max(opts.initialIndex ?? 0, 0), items.length - 1);
22
+ const paint = () => {
23
+ const lines = [];
24
+ if (opts.title)
25
+ lines.push(colors.bold(opts.title));
26
+ const top = Math.min(Math.max(0, cursor - maxVisible + 1), Math.max(0, items.length - maxVisible));
27
+ const visible = items.slice(top, top + maxVisible);
28
+ for (const [i, item] of visible.entries()) {
29
+ const selected = top + i === cursor;
30
+ const marker = selected ? colors.cyan("❯") : " ";
31
+ const label = toLabel(item);
32
+ lines.push(`${marker} ${selected ? label : colors.dim(label)}`);
33
+ }
34
+ const hidden = items.length - visible.length;
35
+ if (hidden > 0)
36
+ lines.push(colors.dim(` … ${hidden} more`));
37
+ lines.push(colors.dim(" ↑/↓ move · enter select · esc cancel"));
38
+ frame.render(lines);
39
+ };
40
+ io.keys.begin();
41
+ try {
42
+ paint();
43
+ for (;;) {
44
+ const key = await io.keys.read();
45
+ switch (key.kind) {
46
+ case "ctrl-c":
47
+ case "eof":
48
+ case "escape":
49
+ return { kind: "cancelled" };
50
+ case "enter":
51
+ return { kind: "selected", value: items[cursor] };
52
+ case "up":
53
+ cursor = (cursor - 1 + items.length) % items.length;
54
+ break;
55
+ case "down":
56
+ cursor = (cursor + 1) % items.length;
57
+ break;
58
+ default:
59
+ break; // chars/tab have no meaning in a plain select
60
+ }
61
+ paint();
62
+ }
63
+ }
64
+ finally {
65
+ // Selection or cancel alike: no leftover frame bytes, raw mode released.
66
+ frame.clear();
67
+ io.keys.restore();
68
+ }
69
+ }