@orkestrel/terminal 0.0.8 → 0.0.9
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/README.md +51 -33
- package/dist/src/core/index.cjs +611 -943
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +522 -963
- package/dist/src/core/index.d.ts +522 -963
- package/dist/src/core/index.js +610 -916
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +556 -203
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +232 -129
- package/dist/src/server/index.d.ts +232 -129
- package/dist/src/server/index.js +541 -204
- package/dist/src/server/index.js.map +1 -1
- package/package.json +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#input","#output","#handlers","#drive","#lineFallback","#listFallback","#editorFallback","#createHandler","#enterRaw","#render","#leaveRaw","#question","#lines","#readline","#createQuestionSettler"],"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 rawCapable(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\tEditorState,\n\tInputOptions,\n\tKeyEvent,\n\tPasswordOptions,\n\tPromptStep,\n\tPromptTheme,\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\thintedHeader,\n\tinputReduce,\n\tparseKey,\n\tpasswordReduce,\n\tpromptHeader,\n\tresolveValidation,\n\tselectReduce,\n\tTerminalError,\n} from '@src/core'\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\tisReadable,\n\tisWritable,\n\tlineCount,\n\trawCapable,\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\treadonly #handlers = new Map<object, (chunk: string | Uint8Array) => void>()\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 (rawCapable(this.#input)) return this.#drive(state, inputReduce)\n\t\treturn this.#lineFallback(\n\t\t\toptions.message,\n\t\t\tstate.styler,\n\t\t\tstate.theme,\n\t\t\tundefined,\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 (rawCapable(this.#input)) return this.#drive(state, passwordReduce)\n\t\treturn this.#lineFallback(\n\t\t\toptions.message,\n\t\t\tstate.styler,\n\t\t\tstate.theme,\n\t\t\tundefined,\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 (rawCapable(this.#input)) return this.#drive(state, confirmReduce)\n\t\treturn this.#lineFallback(\n\t\t\toptions.message,\n\t\t\tstate.styler,\n\t\t\tstate.theme,\n\t\t\tstate.hint,\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 (rawCapable(this.#input)) return this.#drive(state, selectReduce)\n\t\treturn this.#listFallback(\n\t\t\toptions.message,\n\t\t\tstate.styler,\n\t\t\tstate.theme,\n\t\t\tstate.choices,\n\t\t\tstate.hint ?? FALLBACK_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 (rawCapable(this.#input)) return this.#drive(state, checkboxReduce)\n\t\treturn this.#listFallback(\n\t\t\toptions.message,\n\t\t\tstate.styler,\n\t\t\tstate.theme,\n\t\t\tstate.choices,\n\t\t\tstate.hint ?? FALLBACK_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 (rawCapable(this.#input)) return this.#drive(state, editorReduce)\n\t\treturn this.#editorFallback(state)\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'`. The paired {@link #leaveRaw} operation unsubscribes the exact handler,\n\t * leaves raw mode, and pauses the stream on submit, cancel, or throw.\n\t */\n\t#enterRaw(token: object, handler: (chunk: string | Uint8Array) => void): void {\n\t\tthis.#handlers.set(token, handler)\n\t\tthis.#input.setRawMode?.(true)\n\t\tthis.#input.resume?.()\n\t\tthis.#input.on('data', handler)\n\t}\n\n\t#leaveRaw(token: object): void {\n\t\tconst handler = this.#handlers.get(token)\n\t\tif (handler === undefined) return\n\t\tthis.#handlers.delete(token)\n\t\tthis.#input.off('data', handler)\n\t\tthis.#input.setRawMode?.(false)\n\t\tthis.#input.pause?.()\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\tconst 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\tconst token = {}\n\t\t\tconst handler = this.#createHandler(\n\t\t\t\ttoken,\n\t\t\t\tstate,\n\t\t\t\tlineCount(firstView),\n\t\t\t\treduce,\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t)\n\t\t\tthis.#enterRaw(token, handler)\n\t\t})\n\t}\n\n\t#createHandler<T, S>(\n\t\ttoken: object,\n\t\tinitial: S,\n\t\tinitialLines: number,\n\t\treduce: (state: S, key: KeyEvent) => PromptStep<T, S>,\n\t\tresolve: (value: T | PromiseLike<T>) => void,\n\t\treject: (reason?: unknown) => void,\n\t): (chunk: string | Uint8Array) => void {\n\t\tlet state = initial\n\t\tlet lines = initialLines\n\t\treturn (chunk) => {\n\t\t\ttry {\n\t\t\t\tconst step = reduce(state, parseKey(chunk))\n\t\t\t\tstate = step.state\n\t\t\t\tif (step.status === 'active') {\n\t\t\t\t\tthis.#render(step.view, lines)\n\t\t\t\t\tlines = lineCount(step.view)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Terminal step (submit / cancel): paint the final committed view, then tear down.\n\t\t\t\tthis.#render(step.view, lines)\n\t\t\t\tthis.#leaveRaw(token)\n\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\tif (step.status === 'cancel') reject(new TerminalError('CANCEL', 'Prompt cancelled'))\n\t\t\t\telse if (step.status === 'submit' && step.value !== undefined) resolve(step.value)\n\t\t\t\telse reject(new TerminalError('DRIVER', 'submit produced no value'))\n\t\t\t} catch (error) {\n\t\t\t\t// A throw inside the reducer/validator/styler: tear down raw mode + the listener,\n\t\t\t\t// restore the cursor exactly as the normal exit path does, then reject.\n\t\t\t\tthis.#leaveRaw(token)\n\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\treject(error)\n\t\t\t}\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,\n\t\ttheme: PromptTheme,\n\t\thint: string | 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\tfor (;;) {\n\t\t\tconst { answer, ended } = await this.#question(\n\t\t\t\t`${hintedHeader(styler, theme, message, hint)} `,\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. Each index is\n\t * painted by the `muted` role and each choice name by the `content` role.\n\t */\n\tasync #listFallback<T>(\n\t\tmessage: string,\n\t\tstyler: StylerInterface,\n\t\ttheme: PromptTheme,\n\t\tchoices: ReadonlyArray<{ 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\tlet list = `${promptHeader(styler, theme, message)}\\n`\n\t\tchoices.forEach((choice, index) => {\n\t\t\tlist += ` ${styler.render(theme.roles.muted, `${String(index + 1)})`)} ${styler.render(theme.roles.content, choice.name)}\\n`\n\t\t})\n\t\tthis.#output.write(list)\n\t\tfor (;;) {\n\t\t\tconst { answer, ended } = await this.#question(\n\t\t\t\t`${styler.render(theme.roles.hint, `${hint}:`)} `,\n\t\t\t)\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(state: EditorState): Promise<string> {\n\t\tthis.#output.write(\n\t\t\t`${hintedHeader(state.styler, state.theme, state.message, state.hint ?? '(EOF to finish)')}\\n`,\n\t\t)\n\t\tconst text = await this.#lines()\n\t\treturn text.length > 0 ? text : state.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 last = ''\n\t\t\tconst settle = this.#createQuestionSettler(rl, resolve)\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#createQuestionSettler(\n\t\trl: ReturnType<typeof createInterface>,\n\t\tresolve: (value: { readonly answer: string; readonly ended: boolean }) => void,\n\t): (answer: string, ended: boolean) => void {\n\t\tlet settled = false\n\t\treturn (answer, ended) => {\n\t\t\tif (settled) return\n\t\t\tsettled = true\n\t\t\trl.close()\n\t\t\tresolve({ answer, ended })\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))\n\t\t\tthrow new TerminalError('DRIVER', '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\t...(isWritable(output) ? { output } : {}),\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,UAA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CAQA,UAEC,SAAS,OAC8E;EAEvF,MAAM,QAAQ,KAAKb;EACnB,MAAM,SAAS,KAAKC;EACpB,IAAI,CAAC,WAAW,KAAK,GACpB,MAAM,IAAI,UAAA,cAAc,UAAU,oDAAoD;EAGvF,OAAO;GACN;GACA,GAAI,WAAW,MAAM,IAAI,EAAE,OAAO,IAAI,CAAC;GACvC,GAAI,SAAS,EAAE,UAAU,MAAM,IAAI,CAAC;EACrC;CACD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/ZA,SAAgB,eAAe,SAA8C;CAC5E,OAAO,IAAI,SAAS,OAAO;AAC5B"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#input","#output","#styler","#theme","#handlers","#queue","#report","#walk","#editable","#ended","#close","#group","#locked","#read","#bind","#password","#confirm","#editor","#select","#checkbox","#file","#text","#drive","#line","#prompt","#block","#unavailable","#list","#hint","#createHandler","#enterRaw","#interrupt","#render","#leaveRaw","#next","#reader","#taker","#interface","#readline","#accept","#finish"],"sources":["../../../src/server/constants.ts","../../../src/server/helpers.ts","../../../src/server/Terminal.ts","../../../src/server/factories.ts"],"sourcesContent":["// Server-terminals constants — the cursor and line-clear ANSI sequences the interactive `Terminal`\n// driver writes to redraw a field view IN PLACE, plus the copy the walk shows around those views:\n// the per-control format hints, the readline-fallback prompts, and the marks for a locked field and\n// an unavailable choice. UPPER_SNAKE, every member exported. Sequences are built from a named ESC\n// byte through `String.fromCharCode` so no raw control character appears in source (the core\n// terminals / console-module idiom).\n\nimport type { FieldControl } from '@orkestrel/form'\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 the `{count}` placeholder with the number of lines to climb. Kept as a template so\n * 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` fallback\n * appends — a piped (non-terminal) stream cannot navigate with arrow keys, so the choices are\n * printed numbered and the user types one number 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\n/** The hint the non-TTY `editor` fallback shows — a piped stream has no ctrl-d, so end of input finishes the block. */\nexport const FALLBACK_EDITOR_HINT = '(end of input finishes)'\n\n/** The hint the non-TTY `confirm` fallback shows — a piped stream sends a whole line, so the answer is typed rather than pressed. */\nexport const FALLBACK_CONFIRM_HINT = '(y/n)'\n\n/**\n * The format cue appended to a field's label for each control the walk reads as a line of text —\n * the terminal has no date picker, no color well, and no file chooser, so the accepted shape is\n * stated instead. A control with no entry needs none: `text` and `editor` accept any line,\n * `password` masks one, and `confirm`, `select`, and `checkbox` are answered by key rather than by\n * format. The form's own rules still decide whether the typed value is acceptable.\n */\nexport const CONTROL_HINTS: Readonly<Partial<Record<FieldControl, string>>> = Object.freeze({\n\tnumber: '(number)',\n\tdate: '(YYYY-MM-DD)',\n\ttime: '(HH:MM)',\n\tdatetime: '(YYYY-MM-DDTHH:MM)',\n\tcolor: '(#rrggbb)',\n\tfile: '(path)',\n})\n\n/** The instruction a `file` field with `multiple` shows before its entries — one path per line, and a blank line ends the list. */\nexport const FILE_HINT = 'One path per line, blank to finish'\n\n/** The lead on the line listing an open `select`'s offered values, which a typed answer may ignore. */\nexport const SUGGESTION_LEAD = 'Suggestions'\n\n/** The lead on the line listing the choices a `select` or `checkbox` shows but refuses, so a reader sees why one is missing from the list below. */\nexport const UNAVAILABLE_LEAD = 'Unavailable'\n\n/** The mark on a locked field's line — the walk renders its value and moves on, because the form refuses an edit there. */\nexport const LOCKED_MARK = '(locked)'\n\n/**\n * What a field is told when the walk read an answer the control cannot hold — a word typed into a\n * `number`, an off-list value typed into an open `select` whose choice is refused. The value binds\n * as absence and this message is invalidated onto the field, so the walk re-asks it with the reason\n * on screen.\n */\nexport const REFUSAL_MESSAGE = 'Enter a value this field accepts'\n","// Pure helpers for the server terminal driver — every function here is exported and unit-tested.\n// Three families, all total: the stream-boundary guards that narrow `process.stdin` /\n// `process.stdout` / any injected stream without an assertion; the cursor math the driver uses to\n// redraw a field view IN PLACE (count a view's lines, build the cursor-up sequence, assemble the\n// reposition-and-clear prefix); and the projections and line renderers the whole-form walk needs\n// that no reducer owns — a control read as text, a value shown read-only, the choices a field\n// actually offers, and the group, locked, suggestion, unavailable, and numbered-list lines. The\n// impure driver only feeds bytes into the reducers and writes the strings these helpers build.\n\nimport type { FieldChoice, FieldValue, FormField, TextField } from '@orkestrel/form'\nimport type { PromptTheme } from '@src/core'\nimport type { StylerInterface } from '@orkestrel/console'\nimport type { InputStreamInterface, OutputStreamInterface } from './types.js'\nimport {\n\tCARRIAGE_RETURN,\n\tCLEAR_DOWN,\n\tCONTROL_HINTS,\n\tCSI_UP,\n\tLOCKED_MARK,\n\tSUGGESTION_LEAD,\n\tUNAVAILABLE_LEAD,\n} 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 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 rawCapable(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\n/**\n * Project any field the walk reads as a LINE OF TEXT into the {@link TextField} the text reducer\n * takes — `text` itself, and the six controls a terminal has no widget for: `number`, `date`,\n * `time`, `datetime`, `color`, and one `file` entry. The label carries that control's format cue\n * from {@link CONTROL_HINTS}, and a declared `default` becomes the line a bare return submits. The\n * projection carries no rule, because the AUTHORITATIVE form still evaluates the answer this line\n * binds; it exists only so one reducer can render seven controls.\n *\n * @param field - The field being read\n * @returns The text field the reducer renders for it\n *\n * @example\n * ```ts\n * fieldToText({ control: 'date', name: 'born', label: 'Birthday' })\n * // { control: 'text', name: 'born', label: 'Birthday (YYYY-MM-DD)' }\n * ```\n */\nexport function fieldToText(field: FormField): TextField {\n\tconst label = field.label ?? field.name\n\tconst hint = CONTROL_HINTS[field.control]\n\tconst seed = 'default' in field ? field.default : undefined\n\tconst text = typeof seed === 'number' ? String(seed) : seed\n\treturn {\n\t\tcontrol: 'text',\n\t\tname: field.name,\n\t\tlabel: hint === undefined ? label : `${label} ${hint}`,\n\t\t...(typeof text === 'string' ? { default: text } : {}),\n\t}\n}\n\n/**\n * Project one held answer into the text a read-only line shows — a scalar as itself, a boolean as\n * `yes` / `no` (the word the confirm reducer commits), and a list joined by commas. Absence renders\n * as nothing, because a locked field nobody has answered has nothing to show.\n *\n * @param value - The answer the form holds for a field, or absence\n * @returns The text to render for it\n */\nexport function valueToText(value: FieldValue | undefined): string {\n\tif (value === undefined) return ''\n\tif (typeof value === 'string') return value\n\tif (typeof value === 'number') return String(value)\n\tif (typeof value === 'boolean') return value ? 'yes' : 'no'\n\treturn value.join(', ')\n}\n\n/**\n * The choices a `select` or `checkbox` field actually OFFERS — the form refuses a disabled choice's\n * value at every door, including a fill, so the walk never puts one in front of the cursor. Pair\n * with {@link disabledChoices} to tell the reader what was withheld.\n *\n * @param choices - The field's declared choices\n * @returns The choices the walk offers, in declared order\n */\nexport function enabledChoices(choices: readonly FieldChoice[]): readonly FieldChoice[] {\n\treturn choices.filter((choice) => choice.disabled !== true)\n}\n\n/**\n * The choices a `select` or `checkbox` field SHOWS but refuses — the complement of\n * {@link enabledChoices}, rendered by {@link unavailableLine} above the list so a reader sees why a\n * declared choice is missing from it.\n *\n * @param choices - The field's declared choices\n * @returns The refused choices, in declared order\n */\nexport function disabledChoices(choices: readonly FieldChoice[]): readonly FieldChoice[] {\n\treturn choices.filter((choice) => choice.disabled === true)\n}\n\n/** The section header the walk writes when it enters a new field group, painted by the `message` role. */\nexport function groupHeader(styler: StylerInterface, theme: PromptTheme, label: string): string {\n\treturn styler.render(theme.roles.message, label)\n}\n\n/**\n * The read-only line a LOCKED field renders — its label, the {@link LOCKED_MARK}, and the answer the\n * form already holds. The walk writes this instead of a prompt, because the field is still\n * validated and still submitted but must not be edited here.\n *\n * @param styler - The console styler that renders each role\n * @param theme - The resolved prompt theme\n * @param label - The field's label\n * @param value - The held answer, from {@link valueToText}\n * @returns The rendered line, with no trailing space when there is nothing to show\n */\nexport function lockedLine(\n\tstyler: StylerInterface,\n\ttheme: PromptTheme,\n\tlabel: string,\n\tvalue: string,\n): string {\n\tconst head = `${styler.render(theme.roles.muted, theme.icons.dot)} ${styler.render(theme.roles.message, label)} ${styler.render(theme.roles.hint, LOCKED_MARK)}`\n\treturn value.length === 0 ? head : `${head} ${styler.render(theme.roles.content, value)}`\n}\n\n/** The line listing an OPEN select's offered values above its text prompt — a suggestion list, because an open select admits an answer the list does not offer. */\nexport function suggestionLine(\n\tstyler: StylerInterface,\n\ttheme: PromptTheme,\n\tchoices: readonly FieldChoice[],\n): string {\n\tconst values = choices.map((choice) => choice.value).join(', ')\n\treturn styler.render(theme.roles.hint, `${SUGGESTION_LEAD}: ${values}`)\n}\n\n/** The line naming the choices a field shows but refuses, written above the list the walk drives. */\nexport function unavailableLine(\n\tstyler: StylerInterface,\n\ttheme: PromptTheme,\n\tchoices: readonly FieldChoice[],\n): string {\n\tconst labels = choices.map((choice) => choice.label).join(', ')\n\treturn styler.render(theme.roles.muted, `${UNAVAILABLE_LEAD}: ${labels}`)\n}\n\n/**\n * The numbered choice list the non-TTY fallback prints — a piped stream cannot navigate with arrow\n * keys, so each offered choice is printed with the number the reader types back. One line per\n * choice, with no trailing newline.\n *\n * @param styler - The console styler that renders each role\n * @param theme - The resolved prompt theme\n * @param choices - The choices the walk offers, from {@link enabledChoices}\n * @returns The rendered list\n */\nexport function numberedList(\n\tstyler: StylerInterface,\n\ttheme: PromptTheme,\n\tchoices: readonly FieldChoice[],\n): string {\n\treturn choices\n\t\t.map(\n\t\t\t(choice, index) =>\n\t\t\t\t` ${styler.render(theme.roles.muted, `${String(index + 1)})`)} ${styler.render(theme.roles.content, choice.label)}`,\n\t\t)\n\t\t.join('\\n')\n}\n","import type {\n\tFieldChoice,\n\tFieldError,\n\tFieldValue,\n\tFormField,\n\tFormInterface,\n\tFormValues,\n} from '@orkestrel/form'\nimport type {\n\tCheckboxField,\n\tConfirmField,\n\tEditorField,\n\tFileField,\n\tPasswordField,\n\tSelectField,\n} from '@orkestrel/form'\nimport type { KeyEvent, PromptStep, PromptTheme, TerminalInterface } from '@src/core'\nimport type { StylerInterface } from '@orkestrel/console'\nimport type { Interface } from 'node:readline'\nimport type { InputStreamInterface, OutputStreamInterface, TerminalOptions } from './types.js'\nimport {\n\tcheckboxReduce,\n\tconfirmReduce,\n\tcreateCheckboxState,\n\tcreateConfirmState,\n\tcreateEditorState,\n\tcreateInputState,\n\tcreatePasswordState,\n\tcreatePromptTheme,\n\tcreateSelectState,\n\teditorReduce,\n\terrorLine,\n\thintedHeader,\n\tinputReduce,\n\tparseKey,\n\tpasswordReduce,\n\tpromptHeader,\n\tsanitizeDisplayText,\n\tselectReduce,\n\tTerminalError,\n} from '@src/core'\nimport { matchesAnswer, parseValue } from '@orkestrel/form'\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_CONFIRM_HINT,\n\tFALLBACK_EDITOR_HINT,\n\tFALLBACK_SELECT_HINT,\n\tFILE_HINT,\n\tLINE_FEED,\n\tREFUSAL_MESSAGE,\n} from './constants.js'\nimport {\n\tdisabledChoices,\n\tenabledChoices,\n\tfieldToText,\n\tgroupHeader,\n\tisInputStream,\n\tisOutputStream,\n\tisReadable,\n\tlineCount,\n\tlockedLine,\n\tnumberedList,\n\trawCapable,\n\tredrawPrefix,\n\tsuggestionLine,\n\tunavailableLine,\n\tvalueToText,\n} from './helpers.js'\n\n/**\n * The interactive terminal form DRIVER — the {@link TerminalInterface} implementation for a human at\n * this machine's keyboard, and the only impure part of the terminal stack. {@link ask} walks one\n * form's fields in schema order, feeds raw-mode stdin bytes through `parseKey` into the matching\n * pure reducer, renders each returned view in place, and binds every answer through the form's own\n * `fill`. It owns no form logic: the schema, the rules, the values, and the settlement all belong to\n * the form it is given, and this class owns only raw mode, the cursor, and the re-render.\n *\n * @remarks\n * See {@link TerminalInterface} for the driving contract. The walk itself:\n *\n * - **Twelve controls, seven reducers.** `text`, `number`, `date`, `time`, `datetime`, `color`, and\n * each `file` entry are read as one line of text through {@link fieldToText}, which appends that\n * control's format cue to the label. `password`, `confirm`, `editor`, `select`, and `checkbox`\n * each drive their own reducer. An open `select` is a suggestion list plus a typed line, because\n * `open` means the answer need not come from the list.\n * - **The binding projects through `matchesAnswer`.** Every answer is filled as\n * `fill(name, matchesAnswer(value) ? value : undefined)` after `parseValue` has coerced it to the\n * control's own shape, so a bare return on a field with no default binds as ABSENCE and the\n * form's `required` rule refuses it. A typed answer the control cannot hold binds as absence and\n * invalidates the field, so the walk asks again with the reason on screen.\n * - **Visibility is honored.** A `hidden` field and a field currently in `form.disabled` are\n * skipped; a `locked` field renders read-only; entering a new group writes its label as a section\n * header.\n * - **Refusal re-asks.** After the walk the form is submitted. A refusal re-walks only the erroring\n * fields the walk can edit and submits again. When every erroring field is one the walk cannot\n * edit — hidden, locked, or disabled — the form is abandoned instead, because asking again could\n * not change the answer.\n * - **Raw-mode leak-free.** Raw mode is entered once per field and always cleaned up: on submit, on\n * cancel, on a throw, and when the form is abandoned under an active read.\n * - **Non-TTY fallback.** When `input` is not a TTY, the same walk runs over `node:readline` line\n * input: `select` and `checkbox` print a numbered list, and `editor` reads to end of input.\n */\nexport class Terminal implements TerminalInterface {\n\treadonly #input: InputStreamInterface\n\treadonly #output: OutputStreamInterface\n\treadonly #styler: StylerInterface\n\treadonly #theme: PromptTheme\n\treadonly #handlers = new Map<object, (chunk: string | Uint8Array) => void>()\n\treadonly #queue: string[] = []\n\t#interface: Interface | undefined\n\t#taker: ((line: string | undefined) => void) | undefined\n\t#ended = false\n\n\tconstructor(options?: TerminalOptions) {\n\t\t// Resolve each stream through its guard: a present, well-shaped injected stream is used as is;\n\t\t// otherwise the real process stream — no assertion, and an absent 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\tthis.#styler = createStyler()\n\t\tthis.#theme = createPromptTheme(options?.theme)\n\t}\n\n\t// === The contract\n\n\tasync ask(form: FormInterface): Promise<FormValues> {\n\t\ttry {\n\t\t\tthis.#report(form, form.errors)\n\t\t\tawait this.#walk(form, form.schema.fields)\n\t\t\tfor (;;) {\n\t\t\t\tif (form.status !== 'editing') return await form.answer\n\t\t\t\tconst result = form.submit()\n\t\t\t\tif (result.success) return await form.answer\n\t\t\t\tthis.#report(form, result.error)\n\t\t\t\tconst again = this.#editable(form, result.error)\n\t\t\t\t// Nothing the walk can edit, or an input stream that has already ended: asking again would\n\t\t\t\t// render the same fields and read the same answers forever, so abandon the form instead.\n\t\t\t\t// The failures are on screen either way, so the reader sees what could not be answered.\n\t\t\t\tif (again.length === 0 || this.#ended) {\n\t\t\t\t\tform.destroy()\n\t\t\t\t\treturn await form.answer\n\t\t\t\t}\n\t\t\t\tawait this.#walk(form, again)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#close()\n\t\t}\n\t}\n\n\t// === The walk\n\n\t/**\n\t * Ask `fields` in the order given, skipping what the walk must not touch and rendering what it\n\t * must not edit. Returns early the moment the form stops being editable, so an abandoned form\n\t * ends the walk between fields as well as under an active read.\n\t */\n\tasync #walk(form: FormInterface, fields: readonly FormField[]): Promise<void> {\n\t\tlet group: string | undefined\n\t\tfor (const field of fields) {\n\t\t\tif (form.status !== 'editing') return\n\t\t\tif (field.hidden === true) continue\n\t\t\tif (form.disabled.has(field.name)) continue\n\t\t\tif (field.group !== group) {\n\t\t\t\tgroup = field.group\n\t\t\t\tif (group !== undefined) this.#group(form, group)\n\t\t\t}\n\t\t\tif (field.locked === true) {\n\t\t\t\tthis.#locked(form, field)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst raw = await this.#read(form, field)\n\t\t\tif (form.status !== 'editing') return\n\t\t\tthis.#bind(form, field, raw)\n\t\t}\n\t}\n\n\t/** Write a group's label as a section header, resolving the schema's declared label and falling back to the group's own name. */\n\t#group(form: FormInterface, name: string): void {\n\t\tconst label = form.schema.groups?.find((group) => group.name === name)?.label ?? name\n\t\tthis.#output.write(\n\t\t\t`${LINE_FEED}${groupHeader(this.#styler, this.#theme, sanitizeDisplayText(label))}${LINE_FEED}`,\n\t\t)\n\t}\n\n\t/** Render a locked field read-only — its label, its mark, and the answer the form already holds. */\n\t#locked(form: FormInterface, field: FormField): void {\n\t\tconst line = lockedLine(\n\t\t\tthis.#styler,\n\t\t\tthis.#theme,\n\t\t\tsanitizeDisplayText(field.label ?? field.name),\n\t\t\tsanitizeDisplayText(valueToText(form.values[field.name])),\n\t\t)\n\t\tthis.#output.write(`${line}${LINE_FEED}`)\n\t}\n\n\t/** Read one field through the reducer its control names, resolving the raw answer the binding projects. */\n\t#read(form: FormInterface, field: FormField): Promise<FieldValue | undefined> {\n\t\tif (field.control === 'password') return this.#password(form, field)\n\t\tif (field.control === 'confirm') return this.#confirm(form, field)\n\t\tif (field.control === 'editor') return this.#editor(form, field)\n\t\tif (field.control === 'select') return this.#select(form, field)\n\t\tif (field.control === 'checkbox') return this.#checkbox(form, field)\n\t\tif (field.control === 'file') return this.#file(form, field)\n\t\treturn this.#text(form, field)\n\t}\n\n\t/**\n\t * Bind one raw answer to the form — the single binding, and the only place this driver writes a\n\t * value. `parseValue` coerces the raw answer to the control's own shape and `matchesAnswer`\n\t * projects a blank one to absence, which is what keeps `required` refusing a bare return. A raw\n\t * answer the control cannot hold binds as absence and invalidates the field, so the field comes\n\t * back on the next pass carrying the reason rather than vanishing silently.\n\t */\n\t#bind(form: FormInterface, field: FormField, raw: FieldValue | undefined): void {\n\t\tform.touch(field.name)\n\t\tconst value = raw === undefined ? undefined : parseValue(field, raw)\n\t\tform.fill(field.name, matchesAnswer(value) ? value : undefined)\n\t\tif (value === undefined && matchesAnswer(raw)) form.invalidate(field.name, REFUSAL_MESSAGE)\n\t}\n\n\t/** The erroring fields the walk can ask again — every field the walk skips or renders read-only is excluded, because a second pass could not change its answer. */\n\t#editable(form: FormInterface, errors: readonly FieldError[]): readonly FormField[] {\n\t\tconst fields: FormField[] = []\n\t\tfor (const error of errors) {\n\t\t\tconst field = form.field(error.field)\n\t\t\tif (field === undefined) continue\n\t\t\tif (field.hidden === true || field.locked === true) continue\n\t\t\tif (form.disabled.has(field.name)) continue\n\t\t\tif (fields.some((held) => held.name === field.name)) continue\n\t\t\tfields.push(field)\n\t\t}\n\t\treturn fields\n\t}\n\n\t/** Write every supplied failure against its field's label. */\n\t#report(form: FormInterface, errors: readonly FieldError[]): void {\n\t\tfor (const error of errors) {\n\t\t\tconst label = sanitizeDisplayText(form.field(error.field)?.label ?? error.field)\n\t\t\tconst message = sanitizeDisplayText(error.message)\n\t\t\tconst line = errorLine(this.#styler, this.#theme, `${label}: ${message}`)\n\t\t\tthis.#output.write(`${line}${LINE_FEED}`)\n\t\t}\n\t}\n\n\t// === The controls\n\n\t/** Read a field as one line of text — `text` itself and the six controls a terminal has no widget for. */\n\t#text(form: FormInterface, field: FormField): Promise<string> {\n\t\tconst state = createInputState(fieldToText(field), this.#styler, this.#theme)\n\t\tif (rawCapable(this.#input)) return this.#drive(form, state, inputReduce)\n\t\treturn this.#line(form, state.message, state.default)\n\t}\n\n\t/** Read a secret — masked live in raw mode, and read without echo through readline on a stream that cannot enter it. */\n\t#password(form: FormInterface, field: PasswordField): Promise<string> {\n\t\tconst state = createPasswordState(field, this.#styler, this.#theme)\n\t\tif (rawCapable(this.#input)) return this.#drive(form, state, passwordReduce)\n\t\treturn this.#prompt(form, promptHeader(this.#styler, this.#theme, state.message))\n\t}\n\n\t/**\n\t * Read a yes or no. The fallback accepts `y` / `yes` / `n` / `no` in any case and takes the\n\t * field's default for a bare line; anything else is returned as typed, so the binding refuses it\n\t * and the walk asks again rather than silently reading it as no.\n\t */\n\tasync #confirm(form: FormInterface, field: ConfirmField): Promise<FieldValue> {\n\t\tconst state = createConfirmState(field, this.#styler, this.#theme)\n\t\tif (rawCapable(this.#input)) return this.#drive(form, state, confirmReduce)\n\t\tconst header = hintedHeader(this.#styler, this.#theme, state.message, FALLBACK_CONFIRM_HINT)\n\t\tconst line = await this.#prompt(form, header)\n\t\tconst answer = line.trim().toLowerCase()\n\t\tif (answer.length === 0) return state.default\n\t\tif (answer === 'y' || answer === 'yes') return true\n\t\tif (answer === 'n' || answer === 'no') return false\n\t\treturn line.trim()\n\t}\n\n\t/** Read text over many lines — ctrl-d finishes in raw mode, and end of input finishes on a piped stream. */\n\t#editor(form: FormInterface, field: EditorField): Promise<string> {\n\t\tconst state = createEditorState(field, this.#styler, this.#theme)\n\t\tif (rawCapable(this.#input)) return this.#drive(form, state, editorReduce)\n\t\treturn this.#block(form, state.message, state.default)\n\t}\n\n\t/**\n\t * Read one choice. A disabled choice is named above the list and never offered, because the form\n\t * refuses its value at every door. An open select is a suggestion list plus a typed line, since\n\t * `open` admits an answer the list does not offer; a closed select with nothing left to offer\n\t * resolves absence and lets the form's own rules report it.\n\t */\n\tasync #select(form: FormInterface, field: SelectField): Promise<FieldValue | undefined> {\n\t\tconst choices = enabledChoices(field.choices)\n\t\tthis.#unavailable(field.choices)\n\t\tif (field.open === true) {\n\t\t\tif (choices.length > 0) {\n\t\t\t\tconst display = choices.map((choice) => ({\n\t\t\t\t\t...choice,\n\t\t\t\t\tvalue: sanitizeDisplayText(choice.value),\n\t\t\t\t}))\n\t\t\t\tthis.#output.write(`${suggestionLine(this.#styler, this.#theme, display)}${LINE_FEED}`)\n\t\t\t}\n\t\t\treturn this.#text(form, field)\n\t\t}\n\t\tif (choices.length === 0) return undefined\n\t\tconst state = createSelectState({ ...field, choices }, this.#styler, this.#theme)\n\t\tif (rawCapable(this.#input)) return this.#drive(form, state, selectReduce)\n\t\tthis.#list(state.message, choices)\n\t\tconst line = await this.#prompt(form, this.#hint(`${FALLBACK_SELECT_HINT}:`))\n\t\treturn choices[Number.parseInt(line.trim(), 10) - 1]?.value\n\t}\n\n\t/**\n\t * Read any number of choices. Disabled choices are named above the list and never offered, so a\n\t * box the form would refuse can never be ticked. An empty answer is an answered \"none of them\",\n\t * which is what `matchesAnswer` says an empty list means.\n\t */\n\tasync #checkbox(form: FormInterface, field: CheckboxField): Promise<FieldValue> {\n\t\tconst choices = enabledChoices(field.choices)\n\t\tthis.#unavailable(field.choices)\n\t\tconst state = createCheckboxState({ ...field, choices }, this.#styler, this.#theme)\n\t\tif (rawCapable(this.#input)) return this.#drive(form, state, checkboxReduce)\n\t\tthis.#list(state.message, choices)\n\t\tconst line = await this.#prompt(form, this.#hint(`${FALLBACK_CHECKBOX_HINT}:`))\n\t\treturn line\n\t\t\t.split(',')\n\t\t\t.map((part) => choices[Number.parseInt(part.trim(), 10) - 1]?.value)\n\t\t\t.filter((value): value is string => value !== undefined)\n\t}\n\n\t/**\n\t * Read file paths — names only, because bytes never enter a form. A `multiple` field collects one\n\t * path per line until a blank one, and a single field takes one. No path at all is absence rather\n\t * than an empty list, because the reader answered a blank line.\n\t */\n\tasync #file(form: FormInterface, field: FileField): Promise<FieldValue | undefined> {\n\t\tif (field.multiple === true) this.#output.write(`${this.#hint(FILE_HINT)}${LINE_FEED}`)\n\t\tconst paths: string[] = []\n\t\tfor (;;) {\n\t\t\tconst entry = await this.#text(form, field)\n\t\t\tif (entry.length === 0) break\n\t\t\tpaths.push(entry)\n\t\t\tif (field.multiple !== true || this.#ended) break\n\t\t}\n\t\treturn paths.length > 0 ? paths : undefined\n\t}\n\n\t/** Name the choices a field shows but refuses, above the list the walk drives. */\n\t#unavailable(choices: readonly FieldChoice[]): void {\n\t\tconst refused = disabledChoices(choices)\n\t\tif (refused.length === 0) return\n\t\tthis.#output.write(`${unavailableLine(this.#styler, this.#theme, refused)}${LINE_FEED}`)\n\t}\n\n\t/** Write a field's header above its numbered choice list — the non-TTY presentation of a choice field. */\n\t#list(message: string, choices: readonly FieldChoice[]): void {\n\t\tconst header = promptHeader(this.#styler, this.#theme, message)\n\t\tconst list = numberedList(this.#styler, this.#theme, choices)\n\t\tthis.#output.write(`${header}${LINE_FEED}${list}${LINE_FEED}`)\n\t}\n\n\t/** Paint one line of supplementary instruction through the `hint` role. */\n\t#hint(text: string): string {\n\t\treturn this.#styler.render(this.#theme.roles.hint, text)\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'`. The paired {@link #leaveRaw} operation unsubscribes the exact handler,\n\t * leaves raw mode, and pauses the stream on submit, cancel, abandon, or throw.\n\t */\n\t#enterRaw(token: object, handler: (chunk: string | Uint8Array) => void): void {\n\t\tthis.#handlers.set(token, handler)\n\t\tthis.#input.setRawMode?.(true)\n\t\tthis.#input.resume?.()\n\t\tthis.#input.on('data', handler)\n\t}\n\n\t#leaveRaw(token: object): void {\n\t\tconst handler = this.#handlers.get(token)\n\t\tif (handler === undefined) return\n\t\tthis.#handlers.delete(token)\n\t\tthis.#input.off('data', handler)\n\t\tthis.#input.setRawMode?.(false)\n\t\tthis.#input.pause?.()\n\t}\n\n\t/**\n\t * Drive ONE field over raw-mode stdin — the generic engine every interactive control shares.\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 and resolves the reducer's value, on\n\t * `cancel` (ctrl-c) it cleans up and rejects a {@link TerminalError} coded `CANCEL`. Abandoning\n\t * the form ends the read too, through the rejection of its own `answer`. Raw mode is entered\n\t * exactly once and cleaned up on every exit path, so no raw mode and no `'data'` listener ever\n\t * leaks. The cursor is hidden for the duration and restored on exit.\n\t */\n\t#drive<T, S>(\n\t\tform: FormInterface,\n\t\tinitial: S,\n\t\treduce: (state: S, key: KeyEvent) => PromptStep<T, S>,\n\t): Promise<T> {\n\t\treturn new Promise<T>((resolve, reject) => {\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(initial, 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\tconst token = {}\n\t\t\tconst handler = this.#createHandler(\n\t\t\t\ttoken,\n\t\t\t\tinitial,\n\t\t\t\tlineCount(firstView),\n\t\t\t\treduce,\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t)\n\t\t\tthis.#enterRaw(token, handler)\n\t\t\t// An abandoned form ends the read: its own `answer` rejects, so release the terminal and fail\n\t\t\t// this field with the form's error. A read that already finished holds no token and is a no-op.\n\t\t\tvoid form.answer.catch((error: unknown) => this.#interrupt(token, reject, error))\n\t\t})\n\t}\n\n\t#createHandler<T, S>(\n\t\ttoken: object,\n\t\tinitial: S,\n\t\tinitialLines: number,\n\t\treduce: (state: S, key: KeyEvent) => PromptStep<T, S>,\n\t\tresolve: (value: T | PromiseLike<T>) => void,\n\t\treject: (reason?: unknown) => void,\n\t): (chunk: string | Uint8Array) => void {\n\t\tlet state = initial\n\t\tlet lines = initialLines\n\t\treturn (chunk) => {\n\t\t\ttry {\n\t\t\t\tconst step = reduce(state, parseKey(chunk))\n\t\t\t\tstate = step.state\n\t\t\t\tif (step.status === 'active') {\n\t\t\t\t\tthis.#render(step.view, lines)\n\t\t\t\t\tlines = lineCount(step.view)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Terminal step (submit / cancel): paint the final committed view, then tear down.\n\t\t\t\tthis.#render(step.view, lines)\n\t\t\t\tthis.#leaveRaw(token)\n\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\tif (step.status === 'cancel') reject(new TerminalError('CANCEL', 'Prompt cancelled'))\n\t\t\t\telse if (step.status === 'submit' && step.value !== undefined) resolve(step.value)\n\t\t\t\telse reject(new TerminalError('DRIVER', 'submit produced no value'))\n\t\t\t} catch (error) {\n\t\t\t\t// A throw inside the reducer/styler: tear down raw mode + the listener, restore the cursor\n\t\t\t\t// exactly as the normal exit path does, then reject.\n\t\t\t\tthis.#leaveRaw(token)\n\t\t\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t}\n\t}\n\n\t/** End an active read that the form outlived — release raw mode exactly as a submit does, then fail the read with the form's own error. */\n\t#interrupt(token: object, reject: (reason?: unknown) => void, error: unknown): void {\n\t\tif (!this.#handlers.has(token)) return\n\t\tthis.#leaveRaw(token)\n\t\tthis.#output.write(`${CURSOR_SHOW}${LINE_FEED}`)\n\t\treject(error)\n\t}\n\n\t/** Redraw a field 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/** Read one line for a text-shaped field, taking the field's default when the line is bare. */\n\tasync #line(form: FormInterface, message: string, seed: string): Promise<string> {\n\t\tconst answer = await this.#prompt(form, promptHeader(this.#styler, this.#theme, message))\n\t\treturn answer.length > 0 ? answer : seed\n\t}\n\n\t/**\n\t * Read a whole block for an `editor` field — a piped stream has no ctrl-d keypress, so end of\n\t * input is the terminator. It drains every remaining line, which is why nothing after an `editor`\n\t * field can be asked on the same stream.\n\t */\n\tasync #block(form: FormInterface, message: string, seed: string): Promise<string> {\n\t\tconst header = hintedHeader(this.#styler, this.#theme, message, FALLBACK_EDITOR_HINT)\n\t\tthis.#output.write(`${header}${LINE_FEED}`)\n\t\tconst collected: string[] = []\n\t\tfor (;;) {\n\t\t\tconst line = await this.#next(form)\n\t\t\tif (line === undefined) break\n\t\t\tcollected.push(line)\n\t\t}\n\t\tconst text = collected.join('\\n')\n\t\treturn text.length > 0 ? text : seed\n\t}\n\n\t/** Write one field's header and read back the line the reader answers it with, or `''` once the stream has ended. */\n\tasync #prompt(form: FormInterface, header: string): Promise<string> {\n\t\tthis.#output.write(`${header} `)\n\t\tconst line = await this.#next(form)\n\t\treturn line ?? ''\n\t}\n\n\t/**\n\t * Take the next line the input carries — from the buffer when the reader has already read ahead,\n\t * and otherwise by waiting for one. It resolves ABSENCE once the stream has ended, so a walk over\n\t * an exhausted stream settles instead of waiting forever, and it rejects when the form is\n\t * abandoned, so an unanswerable read ends with the form rather than outliving it.\n\t */\n\t#next(form: FormInterface): Promise<string | undefined> {\n\t\tconst buffered = this.#queue.shift()\n\t\tif (buffered !== undefined) return Promise.resolve(buffered)\n\t\tif (this.#ended) return Promise.resolve(undefined)\n\t\tthis.#reader()\n\t\treturn new Promise<string | undefined>((resolve, reject) => {\n\t\t\tthis.#taker = resolve\n\t\t\tvoid form.answer.catch((error: unknown) => {\n\t\t\t\tif (this.#taker !== resolve) return\n\t\t\t\tthis.#taker = undefined\n\t\t\t\treject(error)\n\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * Open the walk's ONE readline interface, or keep the open one. A whole form is many questions\n\t * over one stream, and an interface reads ahead: a fresh interface per question would swallow\n\t * every line it read past the one it was asked for, so the walk holds a single reader and buffers\n\t * what arrives early. It is closed when the walk ends, so the process is free to exit.\n\t */\n\t#reader(): void {\n\t\tif (this.#interface !== undefined) return\n\t\tconst rl = createInterface(this.#readline())\n\t\trl.on('line', (line) => this.#accept(line))\n\t\trl.on('close', () => this.#finish())\n\t\tthis.#interface = rl\n\t}\n\n\t/** Hand a line to whoever is waiting for it, or buffer it for the next question. */\n\t#accept(line: string): void {\n\t\tconst taker = this.#taker\n\t\tif (taker === undefined) {\n\t\t\tthis.#queue.push(line)\n\t\t\treturn\n\t\t}\n\t\tthis.#taker = undefined\n\t\ttaker(line)\n\t}\n\n\t/** Record that no further line can arrive and release whoever was waiting for one. */\n\t#finish(): void {\n\t\tthis.#ended = true\n\t\tconst taker = this.#taker\n\t\tif (taker === undefined) return\n\t\tthis.#taker = undefined\n\t\ttaker(undefined)\n\t}\n\n\t/** Close the walk's reader and release a waiting question — the walk is over, so the stream must stop holding the process open. */\n\t#close(): void {\n\t\tconst taker = this.#taker\n\t\tthis.#taker = undefined\n\t\tif (taker !== undefined) taker(undefined)\n\t\tconst rl = this.#interface\n\t\tif (rl === undefined) return\n\t\tthis.#interface = undefined\n\t\t// Drop the close listener first: this close is the walk ending, not the stream ending, and\n\t\t// recording it as end of input would refuse the next walk its input.\n\t\trl.removeAllListeners('close')\n\t\trl.close()\n\t}\n\n\t/**\n\t * Narrow the resolved input to the `node:readline` `createInterface` boundary, never an assertion.\n\t * The fallback only runs on a real piped `process.stdin` (or a `PassThrough` a test injects), both\n\t * genuine readables; a minimal non-readable fake reaching here means the walk was driven with a\n\t * stream it cannot use, which fails loudly rather than silently. `terminal: false` leaves readline\n\t * as a line decoder and nothing else: the walk writes every prompt itself, through the same output\n\t * every other line goes to, so nothing is written twice and a secret is never echoed.\n\t */\n\t#readline(): { input: NodeJS.ReadableStream; terminal: boolean } {\n\t\t// Bind to a local first — a guard narrows a local, not a `#private` field access.\n\t\tconst input = this.#input\n\t\tif (!isReadable(input))\n\t\t\tthrow new TerminalError('DRIVER', 'Terminal fallback requires a readable input stream')\n\t\treturn { input, terminal: false }\n\t}\n}\n","import type { TerminalInterface } from '@src/core'\nimport type { TerminalOptions } from './types.js'\nimport { Terminal } from './Terminal.js'\n\n/**\n * Create the interactive terminal form driver — the local-keyboard arm of the terminal trio, beside\n * the core headless `createPrompt` broker and the SSE `createPromptClient` bridge. Where the broker\n * PARKS a live form until somebody elsewhere answers it, a `Terminal` answers one HERE: it walks the\n * form's fields in schema order, drives each control's pure reducer over raw-mode stdin, binds every\n * answer through the form's own `fill`, and submits. It is the only impure part of the terminal\n * stack.\n *\n * @param options - See {@link TerminalOptions}\n * @returns A {@link TerminalInterface} whose `ask` drives one whole form over the resolved streams\n *\n * @remarks\n * - **The form is the unit.** `ask` takes the caller's live form and returns its settled values. The\n * returned promise is that form's own `answer`, so a caller holding the form can await either one.\n * - **Every control renders.** Seven controls are read as a line of text with their format cue,\n * `password` masks, `confirm` takes a key, `editor` takes a block, `select` and `checkbox` drive a\n * list, and an open `select` accepts a value its list does not offer.\n * - **The form decides.** A blank answer binds as absence, the form evaluates, and a refusal\n * re-walks only the fields the walk can still edit.\n * - **Injectable and guard-narrowed.** `input` and `output` default to `process.stdin` and\n * `process.stdout` but accept any stream of the declared minimal shape, resolved through their\n * guards rather than an assertion, so a test drives a whole form with a fake TTY that emits\n * scripted key chunks and records every rendered byte.\n * - **Non-TTY fallback.** A piped stream cannot enter raw mode, so the same walk runs over\n * `node:readline` line input.\n *\n * @example\n * ```ts\n * import { createForm } from '@orkestrel/form'\n * import { createTerminal } from '@orkestrel/terminal/server'\n *\n * const terminal = createTerminal()\n * const values = await terminal.ask(\n * \tcreateForm({\n * \t\tlabel: 'Sign up',\n * \t\tfields: [\n * \t\t\t{ control: 'text', name: 'email', label: 'Email', rule: { required: true, email: true } },\n * \t\t\t{ control: 'confirm', name: 'terms', label: 'I accept the terms' },\n * \t\t],\n * \t}),\n * )\n * ```\n */\nexport function createTerminal(options?: TerminalOptions): TerminalInterface {\n\treturn new Terminal(options)\n}\n"],"mappings":";;;;;;;;AAUA,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;;AAGtC,IAAa,uBAAuB;;AAGpC,IAAa,wBAAwB;;;;;;;;AASrC,IAAa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