@orkestrel/terminal 0.0.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.
@@ -0,0 +1,478 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _src_core = require("../core/index.cjs");
3
+ let _orkestrel_console = require("@orkestrel/console");
4
+ let node_readline = require("node:readline");
5
+ let node_process = require("node:process");
6
+ //#region src/server/constants.ts
7
+ /** The Escape byte (ESC, U+001B) — the lead byte of every CSI cursor-control sequence below. */
8
+ var ESCAPE = String.fromCharCode(27);
9
+ /** The Control Sequence Introducer (`ESC[`) — the prefix of every cursor / erase sequence. */
10
+ var CSI = `[`;
11
+ /**
12
+ * The cursor-UP sequence TEMPLATE (`ESC[{count}A`) — {@link import('./helpers.js').moveUp}
13
+ * interpolates `{count}` with the number of lines to climb (the `{count}` placeholder idiom the core
14
+ * terminals' `RULE_MESSAGES` uses). Kept as a template so the count stays out of the constant.
15
+ */
16
+ var CSI_UP = `${CSI}{count}A`;
17
+ /**
18
+ * Hide the cursor (`ESC[?25l`) — written before the driver starts redrawing a prompt so the cursor
19
+ * does not flicker across the view during an in-place re-render; paired with {@link CURSOR_SHOW}.
20
+ */
21
+ var CURSOR_HIDE = `${CSI}?25l`;
22
+ /** Show the cursor (`ESC[?25h`) — restores the cursor after a prompt resolves / cancels (the {@link CURSOR_HIDE} pair). */
23
+ var CURSOR_SHOW = `${CSI}?25h`;
24
+ /**
25
+ * Erase from the cursor down to the end of the screen (`ESC[J`) — wipes the WHOLE previous (possibly
26
+ * multi-line `select` / `checkbox`) view in one write before the new view is rendered, so a redraw
27
+ * never leaves orphaned rows below.
28
+ */
29
+ var CLEAR_DOWN = `${CSI}J`;
30
+ /** A carriage return (`\r`, U+000D) — returns the cursor to column 0 so a redraw starts at the line's left edge. */
31
+ var CARRIAGE_RETURN = String.fromCharCode(13);
32
+ /** A line feed (`\n`, U+000A) — the line terminator the driver writes after the final committed prompt view. */
33
+ var LINE_FEED = String.fromCharCode(10);
34
+ /**
35
+ * The numbered-list prompt the non-TTY {@link import('./Terminal.js').Terminal} `select` / `checkbox`
36
+ * fallback appends — a piped (non-terminal) stream cannot navigate with arrow keys, so the choices are
37
+ * printed numbered and the user types the number(s) on a single readline line.
38
+ */
39
+ var FALLBACK_SELECT_HINT = "Enter a number";
40
+ /** The comma-separated multi-select hint the non-TTY `checkbox` fallback shows (the user types one or more numbers). */
41
+ var FALLBACK_CHECKBOX_HINT = "Enter numbers separated by commas";
42
+ //#endregion
43
+ //#region src/server/helpers.ts
44
+ /**
45
+ * Whether `value` is a usable {@link InputStreamInterface} — a record with callable `on` / `off`
46
+ * `'data'` subscription methods. A total type guard (AGENTS §14): it NEVER throws and returns `false`
47
+ * for anything off-shape, so it narrows the one unavoidable input boundary (the real `process.stdin`,
48
+ * or a fake TTY a test injects) to the exact slice the driver reads — no `as`.
49
+ *
50
+ * @remarks
51
+ * Only `on` / `off` are required (the irreducible event seam); `setRawMode` / `resume` / `pause` /
52
+ * `isTTY` are optional on {@link InputStreamInterface}, so their absence does not disqualify a stream
53
+ * — a piped, non-TTY stream is still a valid input, just one the driver reads through the readline
54
+ * fallback rather than raw mode.
55
+ *
56
+ * @param value - Any value crossing the boundary (a process stream, an injected fake, `unknown`)
57
+ * @returns `true` when `value` has callable `on` and `off`
58
+ */
59
+ function isInputStream(value) {
60
+ return typeof value === "object" && value !== null && "on" in value && typeof value.on === "function" && "off" in value && typeof value.off === "function";
61
+ }
62
+ /**
63
+ * Whether `value` is a usable {@link OutputStreamInterface} — a record with a callable `write`. A
64
+ * total type guard (AGENTS §14): it NEVER throws and returns `false` for anything off-shape, so it
65
+ * narrows the output boundary (the real `process.stdout`, or a recording fake a test injects) to the
66
+ * one method the driver writes through — no `as`.
67
+ *
68
+ * @param value - Any value crossing the boundary (a process stream, an injected fake, `unknown`)
69
+ * @returns `true` when `value` has a callable `write`
70
+ */
71
+ function isOutputStream(value) {
72
+ return typeof value === "object" && value !== null && "write" in value && typeof value.write === "function";
73
+ }
74
+ /**
75
+ * Whether `value` is a Node {@link NodeJS.ReadableStream} — a total structural guard (AGENTS §14)
76
+ * checking for the callable `read` / `pipe` / `on` that `node:readline`'s `createInterface` requires
77
+ * as its `input`. The non-TTY fallback narrows the resolved input stream through this before handing
78
+ * it to readline (never an `as`), so a real piped `process.stdin` (or a `PassThrough` a test injects)
79
+ * crosses into the readline boundary honestly. Never throws; returns `false` for a minimal fake that
80
+ * isn't a full readable.
81
+ *
82
+ * @param value - The resolved input stream (or any value crossing the boundary)
83
+ * @returns `true` when `value` has the readable methods readline needs
84
+ */
85
+ function isReadable(value) {
86
+ return typeof value === "object" && value !== null && "read" in value && typeof value.read === "function" && "pipe" in value && typeof value.pipe === "function";
87
+ }
88
+ /**
89
+ * Whether `value` is a Node {@link NodeJS.WritableStream} — a total structural guard (AGENTS §14)
90
+ * checking for the callable `write` / `end` that `node:readline`'s `createInterface` accepts as its
91
+ * `output`. Paired with {@link isReadable} so the non-TTY fallback narrows BOTH streams to the
92
+ * readline boundary without an `as`. Never throws.
93
+ *
94
+ * @param value - The resolved output stream (or any value crossing the boundary)
95
+ * @returns `true` when `value` has the writable methods readline needs
96
+ */
97
+ function isWritable(value) {
98
+ return typeof value === "object" && value !== null && "write" in value && typeof value.write === "function" && "end" in value && typeof value.end === "function";
99
+ }
100
+ /**
101
+ * Whether an input stream can be driven in RAW mode — it both reports `isTTY === true` AND exposes a
102
+ * callable `setRawMode`. The {@link import('./Terminal.js').Terminal} probes this to choose its path:
103
+ * `true` ⇒ the interactive raw-mode prompts (arrow-key navigation, live re-render); `false` ⇒ the
104
+ * `node:readline` line-input fallback (a piped / non-terminal stream cannot enter raw mode). Total —
105
+ * never throws.
106
+ *
107
+ * @param input - The resolved {@link InputStreamInterface}
108
+ * @returns `true` when the stream is a TTY with `setRawMode`
109
+ */
110
+ function isRawCapable(input) {
111
+ return input.isTTY === true && typeof input.setRawMode === "function";
112
+ }
113
+ /**
114
+ * The number of terminal LINES a rendered prompt `view` occupies — one more than its newline count
115
+ * (a view with no newline is a single line; N newlines span N+1 lines). The basis of the in-place
116
+ * re-render: the driver records the line count of the view it just wrote so the next redraw knows how
117
+ * far up to move the cursor before overwriting. Total; an empty string is one (empty) line.
118
+ *
119
+ * @param view - The rendered (possibly multi-line, possibly ANSI-styled) view string
120
+ * @returns The number of lines the view spans (always at least 1)
121
+ */
122
+ function lineCount(view) {
123
+ let lines = 1;
124
+ for (const character of view) if (character === "\n") lines += 1;
125
+ return lines;
126
+ }
127
+ /**
128
+ * The cursor-UP control sequence that moves the cursor up `count` lines (`ESC[{count}A`) — or the
129
+ * empty string when `count` is zero or negative (no movement needed, and `ESC[0A` is a wasted write).
130
+ * The pure step the in-place re-render uses to climb back over the previous view before clearing it.
131
+ * Total.
132
+ *
133
+ * @param count - How many lines to move the cursor up
134
+ * @returns The `ESC[{count}A` sequence, or `''` when `count <= 0`
135
+ */
136
+ function moveUp(count) {
137
+ if (count <= 0) return "";
138
+ return `${CSI_UP.replace("{count}", String(count))}`;
139
+ }
140
+ /**
141
+ * The full reposition-and-clear prefix to write BEFORE re-rendering a prompt view in place — given
142
+ * the line count of the PREVIOUS view, it moves the cursor up over those lines, returns it to column
143
+ * 0, and erases everything from there to the end of the screen, so the next view is drawn on a clean
144
+ * region (no orphaned rows from a taller previous view). Pure; the driver writes this immediately
145
+ * followed by the new view.
146
+ *
147
+ * @remarks
148
+ * For the FIRST render `previousLines` is `1` (the cursor sits on the line the prompt opened on) so
149
+ * the prefix is just a carriage return + clear-down — the prompt draws from the current line. For a
150
+ * subsequent render it climbs `previousLines - 1` lines (the cursor is on the LAST line of the prior
151
+ * view) before clearing. Keeping the math here (not in the driver) makes the re-render unit-testable
152
+ * without a real terminal.
153
+ *
154
+ * @param previousLines - The line count of the view currently on screen (from {@link lineCount})
155
+ * @returns The control-sequence prefix to write before the new view
156
+ */
157
+ function redrawPrefix(previousLines) {
158
+ return `${moveUp(previousLines - 1)}\r${CLEAR_DOWN}`;
159
+ }
160
+ //#endregion
161
+ //#region src/server/Terminal.ts
162
+ /**
163
+ * The interactive terminal prompt driver (T-c) — the third {@link TerminalInterface} surface (beside
164
+ * the core headless `Prompt` broker and the SSE `PromptClient` bridge), and the ONLY impure part of
165
+ * the prompt stack. It reads the TTY and DRIVES the pure core `*Reduce` reducers: it feeds raw-mode
166
+ * stdin bytes through `parseKey` into the matching reducer, renders the returned `view` in place, and
167
+ * resolves on a `submit` step / rejects with a {@link TerminalError} (`CANCEL`) on ctrl-c. It owns no
168
+ * prompt logic of its own — state, view, validation, and the cancel signal all come from the pure
169
+ * core; this class owns ONLY the cursor + raw-mode + in-place re-render mechanics.
170
+ *
171
+ * @remarks
172
+ * See {@link TerminalInterface} for the behavioral contract (raw-mode leak-freedom, the in-place
173
+ * re-render, the non-TTY readline fallback, event-free).
174
+ */
175
+ var Terminal = class {
176
+ #input;
177
+ #output;
178
+ constructor(options) {
179
+ this.#input = isInputStream(options?.input) ? options.input : node_process.stdin;
180
+ this.#output = isOutputStream(options?.output) ? options.output : node_process.stdout;
181
+ }
182
+ input(options) {
183
+ const state = (0, _src_core.createInputState)(options);
184
+ if (isRawCapable(this.#input)) return this.#drive(state, _src_core.inputReduce);
185
+ return this.#lineFallback(options.message, options.styler, (answer) => {
186
+ const value = answer.length > 0 ? answer : options.default ?? "";
187
+ return (0, _src_core.resolveValidation)(options.validate)(value) === true ? { value } : void 0;
188
+ }, (answer) => answer.length > 0 ? answer : options.default ?? "");
189
+ }
190
+ password(options) {
191
+ const state = (0, _src_core.createPasswordState)(options);
192
+ if (isRawCapable(this.#input)) return this.#drive(state, _src_core.passwordReduce);
193
+ return this.#lineFallback(options.message, options.styler, (answer) => (0, _src_core.resolveValidation)(options.validate)(answer) === true ? { value: answer } : void 0, (answer) => answer, true);
194
+ }
195
+ confirm(options) {
196
+ const state = (0, _src_core.createConfirmState)(options);
197
+ if (isRawCapable(this.#input)) return this.#drive(state, _src_core.confirmReduce);
198
+ return this.#lineFallback(options.message, options.styler, (answer) => {
199
+ const normalized = answer.trim().toLowerCase();
200
+ if (normalized.length === 0) return { value: options.default ?? false };
201
+ if (normalized === "y" || normalized === "yes") return { value: true };
202
+ if (normalized === "n" || normalized === "no") return { value: false };
203
+ }, () => options.default ?? false);
204
+ }
205
+ select(options) {
206
+ const state = (0, _src_core.createSelectState)(options);
207
+ if (isRawCapable(this.#input)) return this.#drive(state, _src_core.selectReduce);
208
+ return this.#listFallback(options.message, options.styler, state.choices, FALLBACK_SELECT_HINT, (line) => {
209
+ const index = Number.parseInt(line.trim(), 10) - 1;
210
+ const choice = state.choices[index];
211
+ return choice === void 0 ? void 0 : { value: choice.value };
212
+ }, "");
213
+ }
214
+ checkbox(options) {
215
+ const state = (0, _src_core.createCheckboxState)(options);
216
+ if (isRawCapable(this.#input)) return this.#drive(state, _src_core.checkboxReduce);
217
+ return this.#listFallback(options.message, options.styler, state.choices, FALLBACK_CHECKBOX_HINT, (line) => {
218
+ const indices = line.split(",").map((part) => Number.parseInt(part.trim(), 10) - 1).filter((index) => index >= 0 && index < state.choices.length);
219
+ if (options.min !== void 0 && indices.length < options.min) return void 0;
220
+ if (options.max !== void 0 && indices.length > options.max) return void 0;
221
+ return { value: indices.map((index) => state.choices[index]?.value).filter((value) => value !== void 0) };
222
+ }, []);
223
+ }
224
+ editor(options) {
225
+ const state = (0, _src_core.createEditorState)(options);
226
+ if (isRawCapable(this.#input)) return this.#drive(state, _src_core.editorReduce);
227
+ return this.#editorFallback(options);
228
+ }
229
+ /**
230
+ * The irreducible Node raw-mode primitive — the ONLY place raw mode is touched. Switches the input
231
+ * into raw mode (each keypress delivered immediately, no echo), resumes its flow, and subscribes
232
+ * `handler` to `'data'`; returns a cleanup closure that unsubscribes, leaves raw mode, and pauses
233
+ * the stream. The closure is ALWAYS invoked (submit / cancel / throw), so raw mode and the listener
234
+ * never leak.
235
+ */
236
+ #enterRaw(handler) {
237
+ this.#input.setRawMode?.(true);
238
+ this.#input.resume?.();
239
+ this.#input.on("data", handler);
240
+ return () => {
241
+ this.#input.off("data", handler);
242
+ this.#input.setRawMode?.(false);
243
+ this.#input.pause?.();
244
+ };
245
+ }
246
+ /**
247
+ * Drive ONE interactive prompt over raw-mode stdin — the generic engine all six TTY prompts share.
248
+ * Renders the reducer's initial `view`, enters raw mode once, and on each keypress runs `parseKey`
249
+ * → `reduce` → an in-place re-render; on `submit` it cleans up + resolves the reducer's `value`, on
250
+ * `cancel` (ctrl-c) it cleans up + rejects a {@link TerminalError} (`CANCEL`). Raw mode is entered
251
+ * exactly once and cleaned up on every exit path (submit / cancel / a throw inside a step), so no
252
+ * raw mode and no `'data'` listener ever leak. The cursor is hidden for the duration and restored
253
+ * on exit.
254
+ */
255
+ #drive(initial, reduce) {
256
+ return new Promise((resolve, reject) => {
257
+ let state = initial;
258
+ this.#output.write(CURSOR_HIDE);
259
+ let firstView;
260
+ try {
261
+ firstView = reduce(state, (0, _src_core.parseKey)("")).view;
262
+ this.#output.write(firstView);
263
+ } catch (error) {
264
+ this.#output.write(`${CURSOR_SHOW}
265
+ `);
266
+ reject(error);
267
+ return;
268
+ }
269
+ let lines = lineCount(firstView);
270
+ const handler = (chunk) => {
271
+ try {
272
+ const step = reduce(state, (0, _src_core.parseKey)(chunk));
273
+ state = step.state;
274
+ if (step.status === "active") {
275
+ this.#render(step.view, lines);
276
+ lines = lineCount(step.view);
277
+ return;
278
+ }
279
+ this.#render(step.view, lines);
280
+ cleanup();
281
+ this.#output.write(`${CURSOR_SHOW}
282
+ `);
283
+ if (step.status === "submit" && step.value !== void 0) resolve(step.value);
284
+ else reject(new _src_core.TerminalError("CANCEL", "Prompt cancelled"));
285
+ } catch (error) {
286
+ cleanup();
287
+ this.#output.write(`${CURSOR_SHOW}
288
+ `);
289
+ reject(error);
290
+ }
291
+ };
292
+ const cleanup = this.#enterRaw(handler);
293
+ });
294
+ }
295
+ /** Redraw a prompt view in place — climb over the previous view's `previousLines`, clear, and write the new view (the pure cursor-math is {@link redrawPrefix}). */
296
+ #render(view, previousLines) {
297
+ this.#output.write(`${redrawPrefix(previousLines)}${view}`);
298
+ }
299
+ /**
300
+ * Read a single line via `node:readline` and accept it through `take` — the non-TTY line-input
301
+ * fallback shared by `input` / `password` / `confirm`. Re-prompts until `take` returns a value (so
302
+ * validation still gates), writing the prompt header each round. A piped stream cannot enter raw
303
+ * mode, so there is no masking / live edit — just a validated line read.
304
+ *
305
+ * @remarks
306
+ * The re-prompt loop is bounded by end-of-input: once the stream reaches EOF (a piped stream that
307
+ * ran out, or one with no trailing newline) it can never deliver another line, so re-prompting
308
+ * would SPIN. On EOF the loop accepts the final line through `take` if it passes, else returns the
309
+ * caller's `eof` fallback (the default / empty value) — the prompt always settles, never spins.
310
+ */
311
+ async #lineFallback(message, styler, take, eof, masked = false) {
312
+ const paint = styler ?? (0, _orkestrel_console.createStyler)();
313
+ for (;;) {
314
+ const { answer, ended } = await this.#question(`${paint.cyan("?")} ${paint.bold(message)} `, masked);
315
+ const accepted = take(answer);
316
+ if (accepted !== void 0) return accepted.value;
317
+ if (ended) return eof(answer);
318
+ }
319
+ }
320
+ /**
321
+ * Print a numbered choice list, then read one readline line and accept it through `take` — the
322
+ * non-TTY fallback for `select` / `checkbox`. The list is rendered once; the user types the
323
+ * number(s); `take` parses + gates the line, re-prompting until it returns a value.
324
+ */
325
+ async #listFallback(message, styler, choices, hint, take, eof) {
326
+ const paint = styler ?? (0, _orkestrel_console.createStyler)();
327
+ let list = `${paint.cyan("?")} ${paint.bold(message)}\n`;
328
+ choices.forEach((choice, index) => {
329
+ list += ` ${paint.dim(`${String(index + 1)})`)} ${choice.name}\n`;
330
+ });
331
+ this.#output.write(list);
332
+ for (;;) {
333
+ const { answer, ended } = await this.#question(`${paint.dim(`${hint}:`)} `);
334
+ const accepted = take(answer);
335
+ if (accepted !== void 0) return accepted.value;
336
+ if (ended) return eof;
337
+ }
338
+ }
339
+ /**
340
+ * The non-TTY `editor` fallback — read lines until EOF (the readline `close`), join them, and fall
341
+ * back to the default when empty. A piped stream has no ctrl-d keypress, so end-of-input is the
342
+ * natural terminator.
343
+ *
344
+ * @remarks
345
+ * Single-pass by necessity: `#lines` drains the whole stream to EOF in one read, so there is no
346
+ * second block to re-prompt for (re-reading an exhausted stream returns nothing forever). Validation
347
+ * is still applied; on a validation FAILURE the best-effort block is returned rather than spinning
348
+ * on the consumed stream — the EOF analogue of the raw-mode editor's re-edit, which a piped stream
349
+ * cannot offer.
350
+ */
351
+ async #editorFallback(options) {
352
+ const paint = options.styler ?? (0, _orkestrel_console.createStyler)();
353
+ this.#output.write(`${paint.cyan("?")} ${paint.bold(options.message)} ${paint.dim("(EOF to finish)")}\n`);
354
+ const text = await this.#lines();
355
+ return text.length > 0 ? text : options.default ?? "";
356
+ }
357
+ /**
358
+ * Ask one readline question on the resolved streams and resolve the typed (un-trimmed) line plus
359
+ * whether the stream ENDED. EOF (the readline `close`) before `rl.question`'s callback fires
360
+ * resolves instead of hanging — a piped stream commonly ends WITHOUT a trailing newline (or is
361
+ * empty), and the `question` callback only fires on a NEWLINE-terminated line, so without this the
362
+ * prompt would wait forever. The trailing unterminated line is still recovered: readline emits it
363
+ * as a `'line'` event just before `'close'`, so the last seen line (or `''` for a truly empty
364
+ * stream) is returned with `ended: true`. The `ended` flag lets the fallback loops settle rather
365
+ * than re-prompt an exhausted stream (which would SPIN). Settling is one-shot (a `close` after a
366
+ * delivered line is ignored, so a normal newline-terminated line reports `ended: false`).
367
+ */
368
+ #question(prompt, masked = false) {
369
+ const rl = (0, node_readline.createInterface)(this.#readline(masked));
370
+ return new Promise((resolve) => {
371
+ let settled = false;
372
+ let last = "";
373
+ const settle = (answer, ended) => {
374
+ if (settled) return;
375
+ settled = true;
376
+ rl.close();
377
+ resolve({
378
+ answer,
379
+ ended
380
+ });
381
+ };
382
+ rl.on("line", (line) => {
383
+ last = line;
384
+ });
385
+ rl.question(prompt, (answer) => settle(answer, false));
386
+ rl.on("close", () => settle(last, true));
387
+ });
388
+ }
389
+ /** Read every line from the input until EOF and resolve them joined by newlines (the editor fallback's reader). */
390
+ #lines() {
391
+ const rl = (0, node_readline.createInterface)(this.#readline());
392
+ const collected = [];
393
+ return new Promise((resolve) => {
394
+ rl.on("line", (line) => collected.push(line));
395
+ rl.on("close", () => resolve(collected.join("\n")));
396
+ });
397
+ }
398
+ /**
399
+ * Narrow the resolved streams to the `node:readline` `createInterface` boundary (§14, never an
400
+ * `as`). The non-TTY fallback only runs on a real piped `process.stdin` (or a `PassThrough` a test
401
+ * injects), both genuine readables; a minimal non-readable fake reaching here means the fallback
402
+ * was driven with a stream it cannot use, which fails loudly rather than silently.
403
+ */
404
+ #readline(masked = false) {
405
+ const input = this.#input;
406
+ const output = this.#output;
407
+ if (!isReadable(input)) throw new Error("Terminal fallback requires a readable input stream");
408
+ return {
409
+ input,
410
+ output: isWritable(output) ? output : void 0,
411
+ ...masked ? { terminal: false } : {}
412
+ };
413
+ }
414
+ };
415
+ //#endregion
416
+ //#region src/server/factories.ts
417
+ /**
418
+ * Create the interactive terminal prompt {@link TerminalInterface} (T-c) — the local-TTY arm of the
419
+ * prompt tri-surface, the env-symmetric sibling of the core headless `createPrompt` broker and the
420
+ * SSE `createPromptClient` bridge. A `Terminal` answers each prompt LOCALLY at this machine's
421
+ * keyboard: it reads raw-mode stdin, drives the pure core `*Reduce` reducers, renders each `view` in
422
+ * place, and resolves on submit / rejects with a {@link import('@src/core').TerminalError} (`CANCEL`)
423
+ * on ctrl-c. It is the ONLY impure part of the prompt stack.
424
+ *
425
+ * @param options - See {@link TerminalOptions}
426
+ * @returns A {@link TerminalInterface} — the six async prompt forms (`input` / `password` / `confirm`
427
+ * / `select` / `checkbox` / `editor`) driven over the resolved streams
428
+ *
429
+ * @remarks
430
+ * - **Drives the pure reducers.** Each prompt builds its initial state (`create*State`), enters raw
431
+ * mode ONCE, and feeds each keypress through `parseKey` → the reducer → an in-place re-render; the
432
+ * driver owns no prompt logic itself (state / view / validation / cancel all come from the core).
433
+ * - **Raw-mode leak-free.** Raw mode is entered exactly once per prompt and ALWAYS cleaned up — on
434
+ * submit, on cancel, and on a throw — leaving no raw mode and no leaked `'data'` listener.
435
+ * - **Injectable + guard-narrowed.** `options.input` / `options.output` default to `process.stdin` /
436
+ * `process.stdout` but accept ANY {@link import('./types.js').InputStreamInterface} /
437
+ * {@link import('./types.js').OutputStreamInterface}, resolved through their §14 guards (never an
438
+ * `as`), so a test drives every prompt with a fake TTY that emits scripted key chunks and records
439
+ * the rendered output — and asserts the resolved value, cancel-on-ctrl-c, and no leaked raw mode.
440
+ * - **Non-TTY fallback.** When `input` is not a TTY (piped), raw mode is unavailable, so the prompts
441
+ * fall back to `node:readline` line input (still validating); `select` / `checkbox` present a
442
+ * numbered list, and `editor` reads lines until EOF.
443
+ *
444
+ * @example
445
+ * ```ts
446
+ * import { createTerminal } from '@src/server'
447
+ *
448
+ * const terminal = createTerminal()
449
+ * const name = await terminal.input({ message: 'Your name' })
450
+ * const proceed = await terminal.confirm({ message: 'Continue?', default: true })
451
+ * ```
452
+ */
453
+ function createTerminal(options) {
454
+ return new Terminal(options);
455
+ }
456
+ //#endregion
457
+ exports.CARRIAGE_RETURN = CARRIAGE_RETURN;
458
+ exports.CLEAR_DOWN = CLEAR_DOWN;
459
+ exports.CSI = CSI;
460
+ exports.CSI_UP = CSI_UP;
461
+ exports.CURSOR_HIDE = CURSOR_HIDE;
462
+ exports.CURSOR_SHOW = CURSOR_SHOW;
463
+ exports.ESCAPE = ESCAPE;
464
+ exports.FALLBACK_CHECKBOX_HINT = FALLBACK_CHECKBOX_HINT;
465
+ exports.FALLBACK_SELECT_HINT = FALLBACK_SELECT_HINT;
466
+ exports.LINE_FEED = LINE_FEED;
467
+ exports.Terminal = Terminal;
468
+ exports.createTerminal = createTerminal;
469
+ exports.isInputStream = isInputStream;
470
+ exports.isOutputStream = isOutputStream;
471
+ exports.isRawCapable = isRawCapable;
472
+ exports.isReadable = isReadable;
473
+ exports.isWritable = isWritable;
474
+ exports.lineCount = lineCount;
475
+ exports.moveUp = moveUp;
476
+ exports.redrawPrefix = redrawPrefix;
477
+
478
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["#input","#output","#drive","#lineFallback","#listFallback","#editorFallback","#render","#enterRaw","#question","#lines","#readline"],"sources":["../../../src/server/constants.ts","../../../src/server/helpers.ts","../../../src/server/Terminal.ts","../../../src/server/factories.ts"],"sourcesContent":["// Server-terminals constants (the T-c branch) — the cursor / line-clear ANSI control sequences the\n// interactive `Terminal` driver writes to redraw a prompt view IN PLACE, plus the readline-fallback\n// defaults. UPPER_SNAKE, every member exported (AGENTS §5). Sequences are built from a named ESC\n// byte via `String.fromCharCode` so no raw control character appears in source (the core\n// terminals / console-module idiom).\n\n/** The Escape byte (ESC, U+001B) — the lead byte of every CSI cursor-control sequence below. */\nexport const ESCAPE = String.fromCharCode(27)\n\n/** The Control Sequence Introducer (`ESC[`) — the prefix of every cursor / erase sequence. */\nexport const CSI = `${ESCAPE}[`\n\n/**\n * The cursor-UP sequence TEMPLATE (`ESC[{count}A`) — {@link import('./helpers.js').moveUp}\n * interpolates `{count}` with the number of lines to climb (the `{count}` placeholder idiom the core\n * terminals' `RULE_MESSAGES` uses). Kept as a template so the count stays out of the constant.\n */\nexport const CSI_UP = `${CSI}{count}A`\n\n/**\n * Hide the cursor (`ESC[?25l`) — written before the driver starts redrawing a prompt so the cursor\n * does not flicker across the view during an in-place re-render; paired with {@link CURSOR_SHOW}.\n */\nexport const CURSOR_HIDE = `${CSI}?25l`\n\n/** Show the cursor (`ESC[?25h`) — restores the cursor after a prompt resolves / cancels (the {@link CURSOR_HIDE} pair). */\nexport const CURSOR_SHOW = `${CSI}?25h`\n\n/**\n * Erase from the cursor down to the end of the screen (`ESC[J`) — wipes the WHOLE previous (possibly\n * multi-line `select` / `checkbox`) view in one write before the new view is rendered, so a redraw\n * never leaves orphaned rows below.\n */\nexport const CLEAR_DOWN = `${CSI}J`\n\n/** A carriage return (`\\r`, U+000D) — returns the cursor to column 0 so a redraw starts at the line's left edge. */\nexport const CARRIAGE_RETURN = String.fromCharCode(13)\n\n/** A line feed (`\\n`, U+000A) — the line terminator the driver writes after the final committed prompt view. */\nexport const LINE_FEED = String.fromCharCode(10)\n\n/**\n * The numbered-list prompt the non-TTY {@link import('./Terminal.js').Terminal} `select` / `checkbox`\n * fallback appends — a piped (non-terminal) stream cannot navigate with arrow keys, so the choices are\n * printed numbered and the user types the number(s) on a single readline line.\n */\nexport const FALLBACK_SELECT_HINT = 'Enter a number'\n\n/** The comma-separated multi-select hint the non-TTY `checkbox` fallback shows (the user types one or more numbers). */\nexport const FALLBACK_CHECKBOX_HINT = 'Enter numbers separated by commas'\n","// Pure helpers for the T-c server-terminals branch (AGENTS §5 — every function here is exported and\n// unit-tested). Total utilities: the two stream-boundary guards (narrow `process.stdin` /\n// `process.stdout` / any injected stream without `as`, §14), the raw-mode capability probe, and the\n// pure cursor-math the interactive `Terminal` driver uses to redraw a prompt view IN PLACE (count a\n// view's lines, build the cursor-up sequence, and assemble the whole reposition-and-clear prefix) —\n// so the impure driver only feeds bytes into the reducers and writes the strings these helpers build.\n\nimport type { InputStreamInterface, OutputStreamInterface } from './types.js'\nimport { CARRIAGE_RETURN, CLEAR_DOWN, CSI_UP } from './constants.js'\n\n/**\n * Whether `value` is a usable {@link InputStreamInterface} — a record with callable `on` / `off`\n * `'data'` subscription methods. A total type guard (AGENTS §14): it NEVER throws and returns `false`\n * for anything off-shape, so it narrows the one unavoidable input boundary (the real `process.stdin`,\n * or a fake TTY a test injects) to the exact slice the driver reads — no `as`.\n *\n * @remarks\n * Only `on` / `off` are required (the irreducible event seam); `setRawMode` / `resume` / `pause` /\n * `isTTY` are optional on {@link InputStreamInterface}, so their absence does not disqualify a stream\n * — a piped, non-TTY stream is still a valid input, just one the driver reads through the readline\n * fallback rather than raw mode.\n *\n * @param value - Any value crossing the boundary (a process stream, an injected fake, `unknown`)\n * @returns `true` when `value` has callable `on` and `off`\n */\nexport function isInputStream(value: unknown): value is InputStreamInterface {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'on' in value &&\n\t\ttypeof value.on === 'function' &&\n\t\t'off' in value &&\n\t\ttypeof value.off === 'function'\n\t)\n}\n\n/**\n * Whether `value` is a usable {@link OutputStreamInterface} — a record with a callable `write`. A\n * total type guard (AGENTS §14): it NEVER throws and returns `false` for anything off-shape, so it\n * narrows the output boundary (the real `process.stdout`, or a recording fake a test injects) to the\n * one method the driver writes through — no `as`.\n *\n * @param value - Any value crossing the boundary (a process stream, an injected fake, `unknown`)\n * @returns `true` when `value` has a callable `write`\n */\nexport function isOutputStream(value: unknown): value is OutputStreamInterface {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'write' in value &&\n\t\ttypeof value.write === 'function'\n\t)\n}\n\n/**\n * Whether `value` is a Node {@link NodeJS.ReadableStream} — a total structural guard (AGENTS §14)\n * checking for the callable `read` / `pipe` / `on` that `node:readline`'s `createInterface` requires\n * as its `input`. The non-TTY fallback narrows the resolved input stream through this before handing\n * it to readline (never an `as`), so a real piped `process.stdin` (or a `PassThrough` a test injects)\n * crosses into the readline boundary honestly. Never throws; returns `false` for a minimal fake that\n * isn't a full readable.\n *\n * @param value - The resolved input stream (or any value crossing the boundary)\n * @returns `true` when `value` has the readable methods readline needs\n */\nexport function isReadable(value: unknown): value is NodeJS.ReadableStream {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'read' in value &&\n\t\ttypeof value.read === 'function' &&\n\t\t'pipe' in value &&\n\t\ttypeof value.pipe === 'function'\n\t)\n}\n\n/**\n * Whether `value` is a Node {@link NodeJS.WritableStream} — a total structural guard (AGENTS §14)\n * checking for the callable `write` / `end` that `node:readline`'s `createInterface` accepts as its\n * `output`. Paired with {@link isReadable} so the non-TTY fallback narrows BOTH streams to the\n * readline boundary without an `as`. Never throws.\n *\n * @param value - The resolved output stream (or any value crossing the boundary)\n * @returns `true` when `value` has the writable methods readline needs\n */\nexport function isWritable(value: unknown): value is NodeJS.WritableStream {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'write' in value &&\n\t\ttypeof value.write === 'function' &&\n\t\t'end' in value &&\n\t\ttypeof value.end === 'function'\n\t)\n}\n\n/**\n * Whether an input stream can be driven in RAW mode — it both reports `isTTY === true` AND exposes a\n * callable `setRawMode`. The {@link import('./Terminal.js').Terminal} probes this to choose its path:\n * `true` ⇒ the interactive raw-mode prompts (arrow-key navigation, live re-render); `false` ⇒ the\n * `node:readline` line-input fallback (a piped / non-terminal stream cannot enter raw mode). Total —\n * never throws.\n *\n * @param input - The resolved {@link InputStreamInterface}\n * @returns `true` when the stream is a TTY with `setRawMode`\n */\nexport function isRawCapable(input: InputStreamInterface): boolean {\n\treturn input.isTTY === true && typeof input.setRawMode === 'function'\n}\n\n/**\n * The number of terminal LINES a rendered prompt `view` occupies — one more than its newline count\n * (a view with no newline is a single line; N newlines span N+1 lines). The basis of the in-place\n * re-render: the driver records the line count of the view it just wrote so the next redraw knows how\n * far up to move the cursor before overwriting. Total; an empty string is one (empty) line.\n *\n * @param view - The rendered (possibly multi-line, possibly ANSI-styled) view string\n * @returns The number of lines the view spans (always at least 1)\n */\nexport function lineCount(view: string): number {\n\tlet lines = 1\n\tfor (const character of view) {\n\t\tif (character === '\\n') lines += 1\n\t}\n\treturn lines\n}\n\n/**\n * The cursor-UP control sequence that moves the cursor up `count` lines (`ESC[{count}A`) — or the\n * empty string when `count` is zero or negative (no movement needed, and `ESC[0A` is a wasted write).\n * The pure step the in-place re-render uses to climb back over the previous view before clearing it.\n * Total.\n *\n * @param count - How many lines to move the cursor up\n * @returns The `ESC[{count}A` sequence, or `''` when `count <= 0`\n */\nexport function moveUp(count: number): string {\n\tif (count <= 0) return ''\n\treturn `${CSI_UP.replace('{count}', String(count))}`\n}\n\n/**\n * The full reposition-and-clear prefix to write BEFORE re-rendering a prompt view in place — given\n * the line count of the PREVIOUS view, it moves the cursor up over those lines, returns it to column\n * 0, and erases everything from there to the end of the screen, so the next view is drawn on a clean\n * region (no orphaned rows from a taller previous view). Pure; the driver writes this immediately\n * followed by the new view.\n *\n * @remarks\n * For the FIRST render `previousLines` is `1` (the cursor sits on the line the prompt opened on) so\n * the prefix is just a carriage return + clear-down — the prompt draws from the current line. For a\n * subsequent render it climbs `previousLines - 1` lines (the cursor is on the LAST line of the prior\n * view) before clearing. Keeping the math here (not in the driver) makes the re-render unit-testable\n * without a real terminal.\n *\n * @param previousLines - The line count of the view currently on screen (from {@link lineCount})\n * @returns The control-sequence prefix to write before the new view\n */\nexport function redrawPrefix(previousLines: number): string {\n\treturn `${moveUp(previousLines - 1)}${CARRIAGE_RETURN}${CLEAR_DOWN}`\n}\n","import type {\n\tCheckboxOptions,\n\tConfirmOptions,\n\tEditorOptions,\n\tInputOptions,\n\tKeyEvent,\n\tPasswordOptions,\n\tPromptStep,\n\tSelectOptions,\n} from '@src/core'\nimport type { StylerInterface } from '@orkestrel/console'\nimport type {\n\tInputStreamInterface,\n\tOutputStreamInterface,\n\tTerminalInterface,\n\tTerminalOptions,\n} from './types.js'\nimport {\n\tcreateCheckboxState,\n\tcreateConfirmState,\n\tcreateEditorState,\n\tcreateInputState,\n\tcreatePasswordState,\n\tcreateSelectState,\n\tcheckboxReduce,\n\tconfirmReduce,\n\teditorReduce,\n\tinputReduce,\n\tparseKey,\n\tpasswordReduce,\n\tresolveValidation,\n\tselectReduce,\n\tTerminalError,\n} from '@src/core'\nimport { createStyler } from '@orkestrel/console'\nimport { createInterface } from 'node:readline'\nimport { stdin, stdout } from 'node:process'\nimport {\n\tCURSOR_HIDE,\n\tCURSOR_SHOW,\n\tFALLBACK_CHECKBOX_HINT,\n\tFALLBACK_SELECT_HINT,\n\tLINE_FEED,\n} from './constants.js'\nimport {\n\tisInputStream,\n\tisOutputStream,\n\tisRawCapable,\n\tisReadable,\n\tisWritable,\n\tlineCount,\n\tredrawPrefix,\n} from './helpers.js'\n\n/**\n * The interactive terminal prompt driver (T-c) — the third {@link TerminalInterface} surface (beside\n * the core headless `Prompt` broker and the SSE `PromptClient` bridge), and the ONLY impure part of\n * the prompt stack. It reads the TTY and DRIVES the pure core `*Reduce` reducers: it feeds raw-mode\n * stdin bytes through `parseKey` into the matching reducer, renders the returned `view` in place, and\n * resolves on a `submit` step / rejects with a {@link TerminalError} (`CANCEL`) on ctrl-c. It owns no\n * prompt logic of its own — state, view, validation, and the cancel signal all come from the pure\n * core; this class owns ONLY the cursor + raw-mode + in-place re-render mechanics.\n *\n * @remarks\n * See {@link TerminalInterface} for the behavioral contract (raw-mode leak-freedom, the in-place\n * re-render, the non-TTY readline fallback, event-free).\n */\nexport class Terminal implements TerminalInterface {\n\treadonly #input: InputStreamInterface\n\treadonly #output: OutputStreamInterface\n\n\tconstructor(options?: TerminalOptions) {\n\t\t// Resolve each stream through its guard (§14): a present, well-shaped injected stream is used as\n\t\t// is; otherwise the real process stream — no `as`, and an `undefined` option falls through.\n\t\tthis.#input = isInputStream(options?.input) ? options.input : stdin\n\t\tthis.#output = isOutputStream(options?.output) ? options.output : stdout\n\t}\n\n\t// === Prompt forms (PromptFormInterface)\n\n\tinput(options: InputOptions): Promise<string> {\n\t\tconst state = createInputState(options)\n\t\tif (isRawCapable(this.#input)) return this.#drive(state, inputReduce)\n\t\treturn this.#lineFallback(\n\t\t\toptions.message,\n\t\t\toptions.styler,\n\t\t\t(answer) => {\n\t\t\t\tconst value = answer.length > 0 ? answer : (options.default ?? '')\n\t\t\t\treturn resolveValidation(options.validate)(value) === true ? { value } : undefined\n\t\t\t},\n\t\t\t// EOF: settle the entered line or the default — a piped stream can't be re-prompted.\n\t\t\t(answer) => (answer.length > 0 ? answer : (options.default ?? '')),\n\t\t)\n\t}\n\n\tpassword(options: PasswordOptions): Promise<string> {\n\t\tconst state = createPasswordState(options)\n\t\tif (isRawCapable(this.#input)) return this.#drive(state, passwordReduce)\n\t\treturn this.#lineFallback(\n\t\t\toptions.message,\n\t\t\toptions.styler,\n\t\t\t(answer) =>\n\t\t\t\tresolveValidation(options.validate)(answer) === true ? { value: answer } : undefined,\n\t\t\t// EOF: settle the entered secret (or '') — a piped stream can't be re-prompted.\n\t\t\t(answer) => answer,\n\t\t\t// A degraded TTY (isTTY but no setRawMode) must never echo the secret being typed.\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tconfirm(options: ConfirmOptions): Promise<boolean> {\n\t\tconst state = createConfirmState(options)\n\t\tif (isRawCapable(this.#input)) return this.#drive(state, confirmReduce)\n\t\treturn this.#lineFallback(\n\t\t\toptions.message,\n\t\t\toptions.styler,\n\t\t\t(answer) => {\n\t\t\t\tconst normalized = answer.trim().toLowerCase()\n\t\t\t\tif (normalized.length === 0) return { value: options.default ?? false }\n\t\t\t\tif (normalized === 'y' || normalized === 'yes') return { value: true }\n\t\t\t\tif (normalized === 'n' || normalized === 'no') return { value: false }\n\t\t\t\treturn undefined\n\t\t\t},\n\t\t\t// EOF: settle the default — a piped stream can't be re-prompted for a y/n.\n\t\t\t() => options.default ?? false,\n\t\t)\n\t}\n\n\tselect(options: SelectOptions): Promise<string> {\n\t\tconst state = createSelectState(options)\n\t\tif (isRawCapable(this.#input)) return this.#drive(state, selectReduce)\n\t\treturn this.#listFallback(\n\t\t\toptions.message,\n\t\t\toptions.styler,\n\t\t\tstate.choices,\n\t\t\tFALLBACK_SELECT_HINT,\n\t\t\t(line) => {\n\t\t\t\tconst index = Number.parseInt(line.trim(), 10) - 1\n\t\t\t\tconst choice = state.choices[index]\n\t\t\t\treturn choice === undefined ? undefined : { value: choice.value }\n\t\t\t},\n\t\t\t// EOF: no choice was picked — settle the empty string (a piped stream can't be re-prompted).\n\t\t\t'',\n\t\t)\n\t}\n\n\tcheckbox(options: CheckboxOptions): Promise<readonly string[]> {\n\t\tconst state = createCheckboxState(options)\n\t\tif (isRawCapable(this.#input)) return this.#drive(state, checkboxReduce)\n\t\treturn this.#listFallback(\n\t\t\toptions.message,\n\t\t\toptions.styler,\n\t\t\tstate.choices,\n\t\t\tFALLBACK_CHECKBOX_HINT,\n\t\t\t(line) => {\n\t\t\t\tconst indices = line\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((part) => Number.parseInt(part.trim(), 10) - 1)\n\t\t\t\t\t.filter((index) => index >= 0 && index < state.choices.length)\n\t\t\t\tif (options.min !== undefined && indices.length < options.min) return undefined\n\t\t\t\tif (options.max !== undefined && indices.length > options.max) return undefined\n\t\t\t\tconst values = indices\n\t\t\t\t\t.map((index) => state.choices[index]?.value)\n\t\t\t\t\t.filter((value): value is string => value !== undefined)\n\t\t\t\treturn { value: values }\n\t\t\t},\n\t\t\t// EOF: nothing selected — settle the empty list (a piped stream can't be re-prompted).\n\t\t\t[],\n\t\t)\n\t}\n\n\teditor(options: EditorOptions): Promise<string> {\n\t\tconst state = createEditorState(options)\n\t\tif (isRawCapable(this.#input)) return this.#drive(state, editorReduce)\n\t\treturn this.#editorFallback(options)\n\t}\n\n\t// === The raw-mode kernel\n\n\t/**\n\t * The irreducible Node raw-mode primitive — the ONLY place raw mode is touched. Switches the input\n\t * into raw mode (each keypress delivered immediately, no echo), resumes its flow, and subscribes\n\t * `handler` to `'data'`; returns a cleanup closure that unsubscribes, leaves raw mode, and pauses\n\t * the stream. The closure is ALWAYS invoked (submit / cancel / throw), so raw mode and the listener\n\t * never leak.\n\t */\n\t#enterRaw(handler: (chunk: string | Uint8Array) => void): () => void {\n\t\tthis.#input.setRawMode?.(true)\n\t\tthis.#input.resume?.()\n\t\tthis.#input.on('data', handler)\n\t\treturn () => {\n\t\t\tthis.#input.off('data', handler)\n\t\t\tthis.#input.setRawMode?.(false)\n\t\t\tthis.#input.pause?.()\n\t\t}\n\t}\n\n\t/**\n\t * Drive ONE interactive prompt over raw-mode stdin — the generic engine all six TTY prompts share.\n\t * Renders the reducer's initial `view`, enters raw mode once, and on each keypress runs `parseKey`\n\t * → `reduce` → an in-place re-render; on `submit` it cleans up + resolves the reducer's `value`, on\n\t * `cancel` (ctrl-c) it cleans up + rejects a {@link TerminalError} (`CANCEL`). Raw mode is entered\n\t * exactly once and cleaned up on every exit path (submit / cancel / a throw inside a step), so no\n\t * raw mode and no `'data'` listener ever leak. The cursor is hidden for the duration and restored\n\t * on exit.\n\t */\n\t#drive<T, S>(initial: S, reduce: (state: S, key: KeyEvent) => PromptStep<T, S>): Promise<T> {\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tlet state = initial\n\t\t\t// Render the first view, tracking how many lines it spans so the next redraw climbs over them.\n\t\t\tthis.#output.write(CURSOR_HIDE)\n\t\t\tlet firstView: string\n\t\t\ttry {\n\t\t\t\tfirstView = reduce(state, parseKey('')).view\n\t\t\t\tthis.#output.write(firstView)\n\t\t\t} catch (error) {\n\t\t\t\t// Raw mode was never entered yet, but the cursor was hidden — restore it before rejecting.\n\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\treject(error)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlet lines = lineCount(firstView)\n\n\t\t\tconst handler = (chunk: string | Uint8Array): void => {\n\t\t\t\ttry {\n\t\t\t\t\tconst step = reduce(state, parseKey(chunk))\n\t\t\t\t\tstate = step.state\n\t\t\t\t\tif (step.status === 'active') {\n\t\t\t\t\t\tthis.#render(step.view, lines)\n\t\t\t\t\t\tlines = lineCount(step.view)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Terminal step (submit / cancel): paint the final committed view, then tear down.\n\t\t\t\t\tthis.#render(step.view, lines)\n\t\t\t\t\tcleanup()\n\t\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\t\tif (step.status === 'submit' && step.value !== undefined) resolve(step.value)\n\t\t\t\t\telse reject(new TerminalError('CANCEL', 'Prompt cancelled'))\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A throw inside the reducer/validator/styler: tear down raw mode + the listener,\n\t\t\t\t\t// restore the cursor exactly as the normal exit path does, then reject.\n\t\t\t\t\tcleanup()\n\t\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\t\treject(error)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst cleanup = this.#enterRaw(handler)\n\t\t})\n\t}\n\n\t/** Redraw a prompt view in place — climb over the previous view's `previousLines`, clear, and write the new view (the pure cursor-math is {@link redrawPrefix}). */\n\t#render(view: string, previousLines: number): void {\n\t\tthis.#output.write(`${redrawPrefix(previousLines)}${view}`)\n\t}\n\n\t// === Non-TTY fallbacks (node:readline line input)\n\n\t/**\n\t * Read a single line via `node:readline` and accept it through `take` — the non-TTY line-input\n\t * fallback shared by `input` / `password` / `confirm`. Re-prompts until `take` returns a value (so\n\t * validation still gates), writing the prompt header each round. A piped stream cannot enter raw\n\t * mode, so there is no masking / live edit — just a validated line read.\n\t *\n\t * @remarks\n\t * The re-prompt loop is bounded by end-of-input: once the stream reaches EOF (a piped stream that\n\t * ran out, or one with no trailing newline) it can never deliver another line, so re-prompting\n\t * would SPIN. On EOF the loop accepts the final line through `take` if it passes, else returns the\n\t * caller's `eof` fallback (the default / empty value) — the prompt always settles, never spins.\n\t */\n\tasync #lineFallback<T>(\n\t\tmessage: string,\n\t\tstyler: StylerInterface | undefined,\n\t\ttake: (answer: string) => { readonly value: T } | undefined,\n\t\teof: (answer: string) => T,\n\t\t// A degraded TTY (isTTY but no setRawMode) must never echo a masked answer — used by `password`.\n\t\tmasked = false,\n\t): Promise<T> {\n\t\tconst paint = styler ?? createStyler()\n\t\tfor (;;) {\n\t\t\tconst { answer, ended } = await this.#question(\n\t\t\t\t`${paint.cyan('?')} ${paint.bold(message)} `,\n\t\t\t\tmasked,\n\t\t\t)\n\t\t\tconst accepted = take(answer)\n\t\t\tif (accepted !== undefined) return accepted.value\n\t\t\tif (ended) return eof(answer)\n\t\t}\n\t}\n\n\t/**\n\t * Print a numbered choice list, then read one readline line and accept it through `take` — the\n\t * non-TTY fallback for `select` / `checkbox`. The list is rendered once; the user types the\n\t * number(s); `take` parses + gates the line, re-prompting until it returns a value.\n\t */\n\tasync #listFallback<T>(\n\t\tmessage: string,\n\t\tstyler: StylerInterface | undefined,\n\t\tchoices: readonly { readonly name: string }[],\n\t\thint: string,\n\t\ttake: (line: string) => { readonly value: T } | undefined,\n\t\teof: T,\n\t): Promise<T> {\n\t\tconst paint = styler ?? createStyler()\n\t\tlet list = `${paint.cyan('?')} ${paint.bold(message)}\\n`\n\t\tchoices.forEach((choice, index) => {\n\t\t\tlist += ` ${paint.dim(`${String(index + 1)})`)} ${choice.name}\\n`\n\t\t})\n\t\tthis.#output.write(list)\n\t\tfor (;;) {\n\t\t\tconst { answer, ended } = await this.#question(`${paint.dim(`${hint}:`)} `)\n\t\t\tconst accepted = take(answer)\n\t\t\tif (accepted !== undefined) return accepted.value\n\t\t\t// EOF on a piped stream — no further line can arrive, so settle the empty fallback rather\n\t\t\t// than spin re-prompting an exhausted stream (a select with no answer ⇒ '', checkbox ⇒ []).\n\t\t\tif (ended) return eof\n\t\t}\n\t}\n\n\t/**\n\t * The non-TTY `editor` fallback — read lines until EOF (the readline `close`), join them, and fall\n\t * back to the default when empty. A piped stream has no ctrl-d keypress, so end-of-input is the\n\t * natural terminator.\n\t *\n\t * @remarks\n\t * Single-pass by necessity: `#lines` drains the whole stream to EOF in one read, so there is no\n\t * second block to re-prompt for (re-reading an exhausted stream returns nothing forever). Validation\n\t * is still applied; on a validation FAILURE the best-effort block is returned rather than spinning\n\t * on the consumed stream — the EOF analogue of the raw-mode editor's re-edit, which a piped stream\n\t * cannot offer.\n\t */\n\tasync #editorFallback(options: EditorOptions): Promise<string> {\n\t\tconst paint = options.styler ?? createStyler()\n\t\tthis.#output.write(\n\t\t\t`${paint.cyan('?')} ${paint.bold(options.message)} ${paint.dim('(EOF to finish)')}\\n`,\n\t\t)\n\t\tconst text = await this.#lines()\n\t\treturn text.length > 0 ? text : (options.default ?? '')\n\t}\n\n\t/**\n\t * Ask one readline question on the resolved streams and resolve the typed (un-trimmed) line plus\n\t * whether the stream ENDED. EOF (the readline `close`) before `rl.question`'s callback fires\n\t * resolves instead of hanging — a piped stream commonly ends WITHOUT a trailing newline (or is\n\t * empty), and the `question` callback only fires on a NEWLINE-terminated line, so without this the\n\t * prompt would wait forever. The trailing unterminated line is still recovered: readline emits it\n\t * as a `'line'` event just before `'close'`, so the last seen line (or `''` for a truly empty\n\t * stream) is returned with `ended: true`. The `ended` flag lets the fallback loops settle rather\n\t * than re-prompt an exhausted stream (which would SPIN). Settling is one-shot (a `close` after a\n\t * delivered line is ignored, so a normal newline-terminated line reports `ended: false`).\n\t */\n\t#question(\n\t\tprompt: string,\n\t\t// A degraded TTY (isTTY but no setRawMode) must never echo a masked answer — used by `password`.\n\t\tmasked = false,\n\t): Promise<{ readonly answer: string; readonly ended: boolean }> {\n\t\tconst rl = createInterface(this.#readline(masked))\n\t\treturn new Promise<{ readonly answer: string; readonly ended: boolean }>((resolve) => {\n\t\t\tlet settled = false\n\t\t\tlet last = ''\n\t\t\tconst settle = (answer: string, ended: boolean): void => {\n\t\t\t\tif (settled) return\n\t\t\t\tsettled = true\n\t\t\t\trl.close()\n\t\t\t\tresolve({ answer, ended })\n\t\t\t}\n\t\t\t// Track the most recent line so an EOF-on-`close` can recover an unterminated final line.\n\t\t\trl.on('line', (line) => {\n\t\t\t\tlast = line\n\t\t\t})\n\t\t\trl.question(prompt, (answer) => settle(answer, false))\n\t\t\t// EOF before a completed question: settle the recovered partial line (or '') as ended.\n\t\t\trl.on('close', () => settle(last, true))\n\t\t})\n\t}\n\n\t/** Read every line from the input until EOF and resolve them joined by newlines (the editor fallback's reader). */\n\t#lines(): Promise<string> {\n\t\tconst rl = createInterface(this.#readline())\n\t\tconst collected: string[] = []\n\t\treturn new Promise<string>((resolve) => {\n\t\t\trl.on('line', (line) => collected.push(line))\n\t\t\trl.on('close', () => resolve(collected.join('\\n')))\n\t\t})\n\t}\n\n\t/**\n\t * Narrow the resolved streams to the `node:readline` `createInterface` boundary (§14, never an\n\t * `as`). The non-TTY fallback only runs on a real piped `process.stdin` (or a `PassThrough` a test\n\t * injects), both genuine readables; a minimal non-readable fake reaching here means the fallback\n\t * was driven with a stream it cannot use, which fails loudly rather than silently.\n\t */\n\t#readline(\n\t\t// A degraded TTY (isTTY but no setRawMode) must never echo a masked answer — used by `password`.\n\t\tmasked = false,\n\t): { input: NodeJS.ReadableStream; output?: NodeJS.WritableStream; terminal?: boolean } {\n\t\t// Bind to locals first — a guard narrows a local, not a `#private` field access.\n\t\tconst input = this.#input\n\t\tconst output = this.#output\n\t\tif (!isReadable(input)) throw new Error('Terminal fallback requires a readable input stream')\n\t\t// `terminal: false` disables readline's own echo/line-editing, so a masked (password) answer is\n\t\t// never rendered on a TTY that lacks `setRawMode` (the raw-mode `#drive` path already masks it).\n\t\treturn {\n\t\t\tinput,\n\t\t\toutput: isWritable(output) ? output : undefined,\n\t\t\t...(masked ? { terminal: false } : {}),\n\t\t}\n\t}\n}\n","import type { TerminalInterface, TerminalOptions } from './types.js'\nimport { Terminal } from './Terminal.js'\n\n/**\n * Create the interactive terminal prompt {@link TerminalInterface} (T-c) — the local-TTY arm of the\n * prompt tri-surface, the env-symmetric sibling of the core headless `createPrompt` broker and the\n * SSE `createPromptClient` bridge. A `Terminal` answers each prompt LOCALLY at this machine's\n * keyboard: it reads raw-mode stdin, drives the pure core `*Reduce` reducers, renders each `view` in\n * place, and resolves on submit / rejects with a {@link import('@src/core').TerminalError} (`CANCEL`)\n * on ctrl-c. It is the ONLY impure part of the prompt stack.\n *\n * @param options - See {@link TerminalOptions}\n * @returns A {@link TerminalInterface} — the six async prompt forms (`input` / `password` / `confirm`\n * / `select` / `checkbox` / `editor`) driven over the resolved streams\n *\n * @remarks\n * - **Drives the pure reducers.** Each prompt builds its initial state (`create*State`), enters raw\n * mode ONCE, and feeds each keypress through `parseKey` → the reducer → an in-place re-render; the\n * driver owns no prompt logic itself (state / view / validation / cancel all come from the core).\n * - **Raw-mode leak-free.** Raw mode is entered exactly once per prompt and ALWAYS cleaned up — on\n * submit, on cancel, and on a throw — leaving no raw mode and no leaked `'data'` listener.\n * - **Injectable + guard-narrowed.** `options.input` / `options.output` default to `process.stdin` /\n * `process.stdout` but accept ANY {@link import('./types.js').InputStreamInterface} /\n * {@link import('./types.js').OutputStreamInterface}, resolved through their §14 guards (never an\n * `as`), so a test drives every prompt with a fake TTY that emits scripted key chunks and records\n * the rendered output — and asserts the resolved value, cancel-on-ctrl-c, and no leaked raw mode.\n * - **Non-TTY fallback.** When `input` is not a TTY (piped), raw mode is unavailable, so the prompts\n * fall back to `node:readline` line input (still validating); `select` / `checkbox` present a\n * numbered list, and `editor` reads lines until EOF.\n *\n * @example\n * ```ts\n * import { createTerminal } from '@src/server'\n *\n * const terminal = createTerminal()\n * const name = await terminal.input({ message: 'Your name' })\n * const proceed = await terminal.confirm({ message: 'Continue?', default: true })\n * ```\n */\nexport function createTerminal(options?: TerminalOptions): TerminalInterface {\n\treturn new Terminal(options)\n}\n"],"mappings":";;;;;;;AAOA,IAAa,SAAS,OAAO,aAAa,EAAE;;AAG5C,IAAa,MAAM;;;;;;AAOnB,IAAa,SAAS,GAAG,IAAI;;;;;AAM7B,IAAa,cAAc,GAAG,IAAI;;AAGlC,IAAa,cAAc,GAAG,IAAI;;;;;;AAOlC,IAAa,aAAa,GAAG,IAAI;;AAGjC,IAAa,kBAAkB,OAAO,aAAa,EAAE;;AAGrD,IAAa,YAAY,OAAO,aAAa,EAAE;;;;;;AAO/C,IAAa,uBAAuB;;AAGpC,IAAa,yBAAyB;;;;;;;;;;;;;;;;;;ACxBtC,SAAgB,cAAc,OAA+C;CAC5E,OACC,OAAO,UAAU,YACjB,UAAU,QACV,QAAQ,SACR,OAAO,MAAM,OAAO,cACpB,SAAS,SACT,OAAO,MAAM,QAAQ;AAEvB;;;;;;;;;;AAWA,SAAgB,eAAe,OAAgD;CAC9E,OACC,OAAO,UAAU,YACjB,UAAU,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