import { StyleFn } from "@crustjs/style"; import { TerminalIO, TerminalIO as TerminalIO$1, TerminalInput, TerminalInput as TerminalInput$1, TerminalOutput, withTerminalIO } from "@crustjs/utils/terminal"; import { StandardSchema } from "@crustjs/utils/schema"; /** * Style slots for all prompt elements. * * Each slot is a `StyleFn` — a `(text: string) => string` function that * applies ANSI styling. The theme controls the visual appearance of every * prompt component. * * @example * ```ts * const theme: PromptTheme = { * prefix: cyan, * message: bold, * placeholder: dim, * // ... * }; * ``` */ interface PromptTheme { /** Prefix glyph before the prompt message (e.g., "?" or "◆") */ readonly prefix: StyleFn; /** The prompt message text */ readonly message: StyleFn; /** Placeholder text shown when input is empty */ readonly placeholder: StyleFn; /** Cursor indicator in selection lists */ readonly cursor: StyleFn; /** Selected / active item styling */ readonly selected: StyleFn; /** Unselected / inactive item styling */ readonly unselected: StyleFn; /** Validation error messages */ readonly error: StyleFn; /** Success / confirmed value styling */ readonly success: StyleFn; /** Hint text (e.g., keybinding hints, choice hints) */ readonly hint: StyleFn; /** Matched characters in fuzzy filter results */ readonly filterMatch: StyleFn; } /** * Partial version of `PromptTheme` for user overrides. * Users only need to specify the slots they want to customize. */ type PartialPromptTheme = Partial; /** * A choice item for select, multiselect, and filter prompts. * * Accepts either a plain string (where `label === value`, so the string * must itself be a `T`) or an object with explicit label, value, and * optional hint. Non-string `T` (e.g. `number`) therefore only admits * object choices; a literal union `T` only admits strings in that union. * * @example * ```ts * // String choices * const colors: Choice[] = ["red", "green", "blue"]; * * // Object choices with typed values * const ports: Choice[] = [ * { label: "HTTP", value: 80 }, * { label: "HTTPS", value: 443, hint: "recommended" }, * ]; * ``` */ type Choice = (T & string) | { readonly label: string; readonly value: T; readonly hint?: string; }; /** * Extract the value union from a choices tuple: a plain string choice is its * own value (see `normalizeChoices`), an object choice contributes its * `value`. With the prompts' `const C` generics, a literal choices tuple * narrows the prompt's return type to the union of its values * (e.g. `["dev", "prod"]` → `"dev" | "prod"`); a widened * `readonly string[]` stays `string`. */ type ChoiceValue[]> = C[number] extends (infer E) ? E extends { readonly value: infer V; } ? V : E : never; /** * @internal Rejects a literal non-empty choices tuple. Fallback overloads use * it so a `default` or `initial` outside literal choices fails instead of * widening the result. Arrays have no explicit `"0"` property, so this * structural constraint also accepts unresolved generic array types. */ type NotChoiceTuple = { readonly "0"?: C extends readonly [unknown, ...unknown[]] ? never : C[number]; }; /** * Validation function for prompt values. * * Throw an `Error` to reject the input — the error's `message` is rendered * inline below the prompt. Return `void` (or `Promise`) when the value * is valid. May be synchronous or asynchronous. * * This matches the throw-on-fail contract used by `@crustjs/store`'s * hand-written `FieldDef.validate` callbacks. * * @example * ```ts * const validateEmail: ValidateFn = (value) => { * if (!value.includes("@")) { * throw new Error("Must be a valid email address"); * } * }; * ``` */ type ValidateFn = (value: T) => void | Promise; /** * Mutually exclusive validation options shared by text prompts: a Standard * Schema, a throw-on-failure `validate` function, or neither — never both. */ type SchemaOrValidate = { /** Standard Schema that owns validation, transformation, defaults, and optionality. */ readonly schema: StandardSchema; readonly validate?: never; } | { readonly schema?: never; /** Throw-on-failure validation function. */ readonly validate: ValidateFn; } | { readonly schema?: never; readonly validate?: never; }; /** * Structured keypress event parsed from raw terminal input. */ interface KeypressEvent { /** The character string for printable keys, or empty string for special keys */ readonly char: string; /** Key name (e.g., "return", "backspace", "up", "down", "left", "right", "tab") */ readonly name: string; /** Whether Ctrl was held */ readonly ctrl: boolean; /** Whether Meta/Alt was held */ readonly meta: boolean; /** Whether Shift was held */ readonly shift: boolean; } /** * Symbol used internally to discriminate submit results from state updates. * Using a symbol prevents collisions with user-defined state types. */ declare const SUBMIT: unique symbol; /** * A submit action wrapping the final value. */ interface SubmitResult { readonly [SUBMIT]: T; } /** * Create a submit result to resolve the prompt with the given value. * * @param value - The value to resolve the prompt with * @returns A submit action object * * @example * ```ts * handleKey: (key, state) => { * if (key.name === "return") return submit(state.value); * return { ...state, value: state.value + key.char }; * } * ``` */ declare function submit(value: T): SubmitResult; /** * Result of a keypress handler. * - Return updated state to continue the prompt * - Return `submit(value)` to resolve the prompt with a value */ type HandleKeyResult = S | SubmitResult; /** * Configuration for `runPrompt` — each prompt provides these functions * to define its behavior. */ interface PromptConfig { /** Render the current state to a string (may contain newlines) */ readonly render: (state: S, theme: PromptTheme) => string; /** Handle a keypress event — return new state or `submit(value)` to resolve */ readonly handleKey: (key: KeypressEvent, state: S) => HandleKeyResult | Promise>; /** Initial state for the prompt */ readonly initialState: S; /** Optional partial theme; merged onto `defaultTheme` styles detected from the output stream. */ readonly theme?: PartialPromptTheme; /** * Optional: render the final submitted state. * Called after submit with the final state and submitted value. * If not provided, the last render output is left on screen. */ readonly renderSubmitted?: (state: S, value: T, theme: PromptTheme) => string; } /** * Error thrown when a prompt requires an interactive TTY but none is available. */ declare class NonInteractiveError extends Error { constructor(message?: string); } /** * Check whether the resolved prompt input is an interactive TTY. * @returns `true` if the input is a TTY, `false` otherwise */ declare function isTTY(input?: Pick): boolean; /** * Check that the resolved prompt input is an interactive TTY. * @throws {NonInteractiveError} when the input is not a TTY */ declare function assertTTY(input?: Pick): void; /** * Run an interactive prompt with the given configuration. * * Manages the full terminal lifecycle: * 1. Asserts the resolved input and output are TTYs * 2. Enables raw mode and hides cursor * 3. Renders initial state * 4. Listens for keypress events, delegating to `handleKey` * 5. Re-renders on state changes * 6. On submit, renders final state, cleans up, and resolves * * Input and output resolve from explicit IO, the ambient terminal scope, * then `process.stdin` / `process.stderr`, keeping stdout clean by default. * The `signal` resolves from explicit IO, then the ambient scope, which inside a * Crust command is the invocation's signal. When it aborts, the prompt restores * the terminal and rejects with `signal.reason`. * * @param config - Prompt configuration (render, handleKey, initialState, theme) * @param io - Optional input/output streams and cancellation signal, resolved per field. * @returns Promise resolving to the user's submitted value * @throws {NonInteractiveError} when the resolved input or output is not a TTY * @throws `signal.reason` when the signal is or becomes aborted * * @example * ```ts * const value = await runPrompt({ * initialState: { value: "" }, * render: (state, theme) => `${theme.prefix("?")} Enter value: ${state.value}`, * handleKey: (key, state) => { * if (key.name === "return") return submit(state.value); * return { ...state, value: state.value + key.char }; * }, * }); * ``` */ declare function runPrompt(config: PromptConfig, io?: TerminalIO): Promise; export { PartialPromptTheme as _, SubmitResult as a, ValidateFn as b, TerminalOutput as c, runPrompt as d, submit as f, NotChoiceTuple as g, ChoiceValue as h, PromptConfig as i, assertTTY as l, Choice as m, KeypressEvent as n, TerminalIO$1 as o, withTerminalIO as p, NonInteractiveError as r, TerminalInput$1 as s, HandleKeyResult as t, isTTY as u, PromptTheme as v, SchemaOrValidate as y };