hacksh 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -6
- package/dist/{command-t16M3-AZ.d.ts → command-D12G9f2b.d.ts} +32 -8
- package/dist/index.d.ts +2 -2
- package/dist/index.js +163 -18
- package/dist/index.js.map +1 -1
- package/dist/{pretty-Db7-kATM.js → pretty-BykhfUqM.js} +130 -34
- package/dist/pretty-BykhfUqM.js.map +1 -0
- package/dist/printer-api.d.ts +2 -2
- package/dist/printer-api.js +1 -1
- package/package.json +3 -1
- package/dist/pretty-Db7-kATM.js.map +0 -1
package/README.md
CHANGED
|
@@ -528,7 +528,7 @@ finishes. A printer failure rejects the invocation without changing a successful
|
|
|
528
528
|
|
|
529
529
|
### Interactive input
|
|
530
530
|
|
|
531
|
-
Every `run` context has a `prompt` with `select`, `confirm`, and `text` methods. Interactive input
|
|
531
|
+
Every `run` context has a `prompt` with `select`, `autocomplete`, `confirm`, and `text` methods. Interactive input
|
|
532
532
|
is separate from `logger`: prompts share the invocation's selected printer, serialized output queue,
|
|
533
533
|
terminal lock, output mode, and abort signal.
|
|
534
534
|
|
|
@@ -562,15 +562,57 @@ uses `initialValue` when supplied and otherwise means no. Text displays its plac
|
|
|
562
562
|
using it as input, supports editing, and repeats the prompt only when `validate` returns a nonempty
|
|
563
563
|
message; `""` means valid. Backspace removes one Unicode code point. Input pasted after a selection
|
|
564
564
|
or confirmation is retained for the next sequential prompt instead of being discarded.
|
|
565
|
-
The built-in prompt API
|
|
566
|
-
multiselect prompt.
|
|
565
|
+
The built-in prompt API does not provide a multiselect prompt.
|
|
567
566
|
|
|
568
|
-
|
|
567
|
+
Use `autocomplete` for a searchable single choice:
|
|
568
|
+
|
|
569
|
+
```ts
|
|
570
|
+
const environment = await prompt.autocomplete({
|
|
571
|
+
message: "Environment",
|
|
572
|
+
placeholder: "Type to filter…",
|
|
573
|
+
options: [
|
|
574
|
+
{ value: "production", label: "Production", priority: 20 },
|
|
575
|
+
{ value: "staging", label: "Staging", hint: "safe default", priority: 10 },
|
|
576
|
+
],
|
|
577
|
+
sortBy: (item) => item.priority,
|
|
578
|
+
}); // "production" | "staging"; displays Staging before Production
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
Autocomplete filters labels (falling back to values) by case-insensitive substring,
|
|
582
|
+
preserving the configured option order rather than ranking matches. An empty query
|
|
583
|
+
shows all options, initially with none selected. Down enters selection at the first
|
|
584
|
+
match; Up/Down move without wrapping. Up at the first match or Escape returns to
|
|
585
|
+
editing. Typing or Backspace while selecting edits the query and returns to input.
|
|
586
|
+
Enter submits only a selected match; it does nothing while editing or with no matches.
|
|
587
|
+
Backspace removes one grapheme cluster. Escape while editing and Ctrl-C cancel.
|
|
588
|
+
The placeholder is display-only, reappears when the query becomes empty, and remains
|
|
589
|
+
until the terminal delivers committed input; OS IME composition is not observable.
|
|
590
|
+
The pretty printer anchors the real cursor at the input end, including wrapped input.
|
|
591
|
+
|
|
592
|
+
Both `select` and `autocomplete` accept `sortBy: (item) => string | number`. The
|
|
593
|
+
callback receives the complete inferred option item, including custom fields such
|
|
594
|
+
as `priority`; the prompt still returns only its `value`, preserving literal types.
|
|
595
|
+
Without `sortBy`, options retain their definition order. With it, keys are computed
|
|
596
|
+
once per option at prompt startup and sorted ascending, stably: equal keys retain
|
|
597
|
+
definition order, and the original array is never reordered. Autocomplete filtering
|
|
598
|
+
preserves this sorted order without recomputing keys. `initialValue` on select
|
|
599
|
+
chooses a value in the sorted list without changing that order.
|
|
600
|
+
|
|
601
|
+
Numeric keys use numeric order; strings use locale-independent UTF-16 lexical
|
|
602
|
+
order, not locale-aware collation or numeric-string ordering. All keys in one
|
|
603
|
+
prompt must have the same type. Invalid keys (including `NaN`) or mixed types
|
|
604
|
+
produce `HackshPromptError` with reason `invalid-options`; a thrown callback
|
|
605
|
+
produces `input-error` with the original error as `cause`.
|
|
606
|
+
Explicit option types take the whole item type, for example
|
|
607
|
+
`SelectOptions<{ value: "staging" | "production"; priority: number }>`.
|
|
608
|
+
|
|
609
|
+
Input prompts are allowed only when the resolved mode is interactive: pretty output outside CI with TTY
|
|
569
610
|
stdin and stdout. JSON, CI, and non-TTY invocations throw `HackshPromptError` immediately even if a
|
|
570
611
|
default is available. Its `reason` and `prompt` fields identify why input failed and the prompt's
|
|
571
|
-
`kind`, `message`, and select `choices`. Reasons distinguish `non-interactive`, `cancelled`,
|
|
612
|
+
`kind`, `message`, and select/autocomplete `choices`. Reasons distinguish `non-interactive`, `cancelled`,
|
|
572
613
|
`aborted`, `eof`, `overlapping`, `invalid-options`, `input-error`, and `printer-error`. Ctrl-C and
|
|
573
|
-
Escape cancel
|
|
614
|
+
Escape cancel (except Escape from autocomplete selection, which returns to editing);
|
|
615
|
+
`runMain` reports cancellation and exits with status 130. A prompt that starts or is
|
|
574
616
|
waiting after the invocation's `signal` aborts fails with `aborted` and the signal's reason as its
|
|
575
617
|
`cause`. Only one prompt may be active in an invocation. Input listeners and raw terminal mode are
|
|
576
618
|
restored after every outcome.
|
|
@@ -584,6 +626,37 @@ Physical rows are calculated from explicit newlines, ANSI-free Unicode display w
|
|
|
584
626
|
`stdout.columns`, including terminal wrapping. When a custom output writer does not expose a
|
|
585
627
|
positive `columns` value, the renderer conservatively counts explicit lines only.
|
|
586
628
|
|
|
629
|
+
### Waiting for work
|
|
630
|
+
|
|
631
|
+
Use `prompt.wait` to display a spinner in the left rail while a callback runs:
|
|
632
|
+
|
|
633
|
+
```ts
|
|
634
|
+
const data = await prompt.wait(() => fetchData(), { message: "Fetching data" });
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
The message is optional and defaults to `待機中`. The callback may return a value or a
|
|
638
|
+
promise; `wait` infers and returns its result, and propagates its thrown error unchanged.
|
|
639
|
+
The spinner animates only in interactive pretty mode. Non-TTY and CI invocations still
|
|
640
|
+
run the callback: pretty output prints a static message, while JSON emits `active` and
|
|
641
|
+
`closed` prompt events with `kind: "wait"`, without animation frames.
|
|
642
|
+
|
|
643
|
+
Logger and output events remain visible during the wait. On success or failure, the
|
|
644
|
+
animated row is replaced by the plain rail; `wait` does not print a success message.
|
|
645
|
+
With `unicode: false`, the spinner and rail use ASCII. Only one prompt or wait may be
|
|
646
|
+
active per invocation. Nested waits, input prompts, and terminal-owning external
|
|
647
|
+
commands are rejected with `overlapping`; captured `exec` calls remain available.
|
|
648
|
+
|
|
649
|
+
Wait does not read stdin or enable raw mode. An invocation abort stops the animation
|
|
650
|
+
and closes the display, but still awaits the callback and retains the terminal lock
|
|
651
|
+
until it settles. Pass the command context's `signal` to cancellable work. If the
|
|
652
|
+
callback rejects, its error takes precedence; otherwise an aborted wait rejects with
|
|
653
|
+
`HackshPromptError` (`aborted`). Printer failures similarly close the display and
|
|
654
|
+
reject with `printer-error` once the callback settles.
|
|
655
|
+
|
|
656
|
+
Custom printers receive `WaitPromptState` through ordinary prompt events. `frame` is
|
|
657
|
+
present for animated waits (including their closing event), and absent for static
|
|
658
|
+
waits.
|
|
659
|
+
|
|
587
660
|
### Cancellation and exit status
|
|
588
661
|
|
|
589
662
|
Every `run` context has a `signal`, an `AbortSignal` for that invocation. `exec` calls and prompts
|
|
@@ -878,6 +951,17 @@ await showUsage(main, {
|
|
|
878
951
|
| `vp run ready` | Run check, test, and build |
|
|
879
952
|
| `pnpm test:packed` | Test the tarball with Node 22.18, host Node, and Deno |
|
|
880
953
|
|
|
954
|
+
The autocomplete API has PTY tests in `src/autocomplete-pty.test.ts`.
|
|
955
|
+
Run them with `pnpm test run src/autocomplete-pty.test.ts`. They launch
|
|
956
|
+
`src/fixtures/autocomplete-pty-cli.ts`, a CLI using the public `prompt.autocomplete`
|
|
957
|
+
API, and interpret its output with a headless terminal, checking visible choices,
|
|
958
|
+
placeholder transitions, cursor coordinates, and submission/cancellation cleanup.
|
|
959
|
+
For manual terminal verification, run `node src/fixtures/autocomplete-pty-cli.ts`.
|
|
960
|
+
Expected screens use indented multiline strings; ANSI handling stays in
|
|
961
|
+
`src/test-support/terminal.ts`. OS IME composition windows are outside this suite.
|
|
962
|
+
The development-only `node-pty` dependency requires Python and a C/C++ build
|
|
963
|
+
toolchain (Xcode Command Line Tools on macOS).
|
|
964
|
+
|
|
881
965
|
The packed-consumer test must execute its Node consumer with exactly Node 22.18.0. Run pnpm itself
|
|
882
966
|
under that version, or supply an absolute executable path explicitly:
|
|
883
967
|
|
|
@@ -91,7 +91,7 @@ declare class HackshValidationError extends HackshUsageError {
|
|
|
91
91
|
readonly issues: ReadonlyArray<HackshIssue>;
|
|
92
92
|
constructor(command: AnyCommandDef, issues: ReadonlyArray<HackshIssue>);
|
|
93
93
|
}
|
|
94
|
-
type PromptKind = "select" | "confirm" | "text";
|
|
94
|
+
type PromptKind = "select" | "autocomplete" | "confirm" | "text" | "wait";
|
|
95
95
|
type HackshPromptErrorReason = "non-interactive" | "cancelled" | "aborted" | "eof" | "overlapping" | "invalid-options" | "input-error" | "printer-error";
|
|
96
96
|
interface PromptErrorDetails {
|
|
97
97
|
kind: PromptKind;
|
|
@@ -277,7 +277,20 @@ interface TextPromptState extends PromptStateBase {
|
|
|
277
277
|
value: string;
|
|
278
278
|
placeholder?: string;
|
|
279
279
|
}
|
|
280
|
-
|
|
280
|
+
interface AutocompletePromptState extends PromptStateBase {
|
|
281
|
+
kind: "autocomplete";
|
|
282
|
+
query: string;
|
|
283
|
+
placeholder?: string;
|
|
284
|
+
phase: "input" | "select";
|
|
285
|
+
choices: readonly PromptChoiceState[];
|
|
286
|
+
value?: string;
|
|
287
|
+
}
|
|
288
|
+
/** Waiting for callback completion; frame is present only for animated output. */
|
|
289
|
+
interface WaitPromptState extends PromptStateBase {
|
|
290
|
+
kind: "wait";
|
|
291
|
+
frame?: number;
|
|
292
|
+
}
|
|
293
|
+
type PromptState = SelectPromptState | ConfirmPromptState | TextPromptState | AutocompletePromptState | WaitPromptState;
|
|
281
294
|
interface PromptPrintEvent {
|
|
282
295
|
type: "prompt";
|
|
283
296
|
prompt: PromptState;
|
|
@@ -352,10 +365,16 @@ interface SelectOption<T extends string> {
|
|
|
352
365
|
label?: string;
|
|
353
366
|
hint?: string;
|
|
354
367
|
}
|
|
355
|
-
interface
|
|
368
|
+
interface ChoiceOptions<TItem extends SelectOption<string>> {
|
|
356
369
|
message: string;
|
|
357
|
-
options: readonly
|
|
358
|
-
|
|
370
|
+
options: readonly TItem[];
|
|
371
|
+
sortBy?: (item: NoInfer<TItem>) => string | number;
|
|
372
|
+
}
|
|
373
|
+
interface SelectOptions<TItem extends SelectOption<string>> extends ChoiceOptions<TItem> {
|
|
374
|
+
initialValue?: NoInfer<TItem["value"]>;
|
|
375
|
+
}
|
|
376
|
+
interface AutocompleteOptions<TItem extends SelectOption<string>> extends ChoiceOptions<TItem> {
|
|
377
|
+
placeholder?: string;
|
|
359
378
|
}
|
|
360
379
|
interface ConfirmOptions {
|
|
361
380
|
message: string;
|
|
@@ -366,10 +385,15 @@ interface TextOptions {
|
|
|
366
385
|
placeholder?: string;
|
|
367
386
|
validate?(value: string): string | undefined;
|
|
368
387
|
}
|
|
388
|
+
interface WaitOptions {
|
|
389
|
+
message?: string;
|
|
390
|
+
}
|
|
369
391
|
interface Prompter {
|
|
370
|
-
select<const
|
|
392
|
+
select<const TItem extends SelectOption<string>>(options: SelectOptions<TItem>): Promise<TItem["value"]>;
|
|
393
|
+
autocomplete<const TItem extends SelectOption<string>>(options: AutocompleteOptions<TItem>): Promise<TItem["value"]>;
|
|
371
394
|
confirm(options: ConfirmOptions): Promise<boolean>;
|
|
372
395
|
text(options: TextOptions): Promise<string>;
|
|
396
|
+
wait<T>(work: () => T | Promise<T>, options?: WaitOptions): Promise<T>;
|
|
373
397
|
}
|
|
374
398
|
//#endregion
|
|
375
399
|
//#region src/schema.d.ts
|
|
@@ -416,5 +440,5 @@ interface CommandDef<S extends ArgsSchema = EmptyArgs, R = unknown, Children ext
|
|
|
416
440
|
type AnyCommandDef = CommandDef<ArgsSchema>;
|
|
417
441
|
declare function defineCommand<S extends ArgsSchema = EmptyArgs, R = never, Children extends Record<string, AnyCommandDef> = {}>(def: CommandDef<S, R, Children>): NoInfer<CommandDef<S, R, Children>>;
|
|
418
442
|
//#endregion
|
|
419
|
-
export {
|
|
420
|
-
//# sourceMappingURL=command-
|
|
443
|
+
export { LogProperties as $, PromptState as A, WaitPromptState as B, OutputPrintEvent as C, ExecSuccess as Ct, Printer as D, PrintStream as E, TerminalInput as F, UsageCommandSummary as G, resolveOutputMode as H, TerminalOutput as I, renderUsage as J, UsageOptionSummary as K, TextPromptState as L, ResolveOutputModeOptions as M, SelectPromptState as N, PromptChoiceState as O, StreamColors as P, LogLevel as Q, UsagePrintEvent as R, OutputPreference as S, ExecSkipped as St, PrintEvent as T, ShowUsageOptions as U, createJsonPrinter as V, UsageArgumentSummary as W, summarizeUsage as X, showUsage as Y, LogKind as Z, ExecPrintEvent as _, ExecFailure as _t, ArgsSchema as a, HackshExecError as at, OutputFormat as b, ExecResult as bt, Prompter as c, HackshPromptError as ct, TextOptions as d, HackshValidationError as dt, LogRecord as et, WaitOptions as f, PromptErrorDetails as ft, ErrorPrintEvent as g, ExecCommand as gt, ConfirmPromptState as h, Exec as ht, defineCommand as i, HackshErrorSummary as it, PromptStatus as j, PromptPrintEvent as k, SelectOption as l, HackshPromptErrorReason as lt, AutocompletePromptState as m, ValidationIssueSummary as mt, CommandContext as n, HackshError as nt, AutocompleteOptions as o, HackshExitError as ot, Output as p, PromptKind as pt, UsageSummary as q, CommandDef as r, HackshErrorKind as rt, ConfirmOptions as s, HackshIssue as st, AnyCommandDef as t, Logger as tt, SelectOptions as u, HackshUsageError as ut, JsonPrinterOptions as v, ExecFailureReason as vt, OutputWriter as w, OutputMode as x, ExecReturn as xt, LogPrintEvent as y, ExecOptions as yt, VersionPrintEvent as z };
|
|
444
|
+
//# sourceMappingURL=command-D12G9f2b.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ct as ExecSuccess, D as Printer, F as TerminalInput, I as TerminalOutput, J as renderUsage, S as OutputPreference, St as ExecSkipped, U as ShowUsageOptions, X as summarizeUsage, Y as showUsage, _t as ExecFailure, a as ArgsSchema, at as HackshExecError, bt as ExecResult, c as Prompter, ct as HackshPromptError, d as TextOptions, dt as HackshValidationError, f as WaitOptions, ft as PromptErrorDetails, gt as ExecCommand, ht as Exec, i as defineCommand, l as SelectOption, lt as HackshPromptErrorReason, n as CommandContext, nt as HackshError, o as AutocompleteOptions, ot as HackshExitError, p as Output, pt as PromptKind, r as CommandDef, s as ConfirmOptions, st as HackshIssue, t as AnyCommandDef, tt as Logger, u as SelectOptions, ut as HackshUsageError, vt as ExecFailureReason, xt as ExecReturn, yt as ExecOptions } from "./command-D12G9f2b.js";
|
|
2
2
|
import { output } from "zod/v4/core";
|
|
3
3
|
//#region src/parser.d.ts
|
|
4
4
|
/**
|
|
@@ -39,5 +39,5 @@ interface RunMainOptions extends OutputOptions {
|
|
|
39
39
|
}
|
|
40
40
|
declare function runMain<S extends ArgsSchema>(command: CommandDef<S>, options?: RunMainOptions): Promise<void>;
|
|
41
41
|
//#endregion
|
|
42
|
-
export { type CommandContext, type CommandDef, type ConfirmOptions, type Exec, type ExecCommand, type ExecFailure, type ExecFailureReason, type ExecOptions, type ExecResult, type ExecReturn, type ExecSkipped, type ExecSuccess, HackshError, HackshExecError, HackshExitError, type HackshIssue, HackshPromptError, type HackshPromptErrorReason, HackshUsageError, HackshValidationError, type Logger, type Output, type OutputOptions, type PromptErrorDetails, type PromptKind, type Prompter, type RunCommandOptions, type RunMainOptions, type SelectOption, type SelectOptions, type ShowUsageOptions, type TextOptions, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage, summarizeUsage };
|
|
42
|
+
export { type AutocompleteOptions, type CommandContext, type CommandDef, type ConfirmOptions, type Exec, type ExecCommand, type ExecFailure, type ExecFailureReason, type ExecOptions, type ExecResult, type ExecReturn, type ExecSkipped, type ExecSuccess, HackshError, HackshExecError, HackshExitError, type HackshIssue, HackshPromptError, type HackshPromptErrorReason, HackshUsageError, HackshValidationError, type Logger, type Output, type OutputOptions, type PromptErrorDetails, type PromptKind, type Prompter, type RunCommandOptions, type RunMainOptions, type SelectOption, type SelectOptions, type ShowUsageOptions, type TextOptions, type WaitOptions, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage, summarizeUsage };
|
|
43
43
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as createExec, c as HackshExitError, d as HackshValidationError, f as summarizeError, i as resolveOutputMode, l as HackshPromptError, n as createJsonPrinter, o as HackshError, p as summarizeErrors, r as createPrintQueue, s as HackshExecError, t as createPrettyPrinter, u as HackshUsageError } from "./pretty-
|
|
1
|
+
import { a as createExec, c as HackshExitError, d as HackshValidationError, f as summarizeError, i as resolveOutputMode, l as HackshPromptError, n as createJsonPrinter, o as HackshError, p as summarizeErrors, r as createPrintQueue, s as HackshExecError, t as createPrettyPrinter, u as HackshUsageError } from "./pretty-BykhfUqM.js";
|
|
2
2
|
import { globalRegistry, safeParseAsync } from "zod/v4/core";
|
|
3
3
|
import { parseArgs as parseArgs$1 } from "node:util";
|
|
4
4
|
import { readFile, realpath } from "node:fs/promises";
|
|
@@ -619,6 +619,44 @@ function promptError(reason, prompt, message, cause) {
|
|
|
619
619
|
function validateMessage(kind, message, choices) {
|
|
620
620
|
if (typeof message !== "string" || message.length === 0) throw promptError("invalid-options", details$1(kind, message, choices), `Invalid ${kind} prompt: message must be a non-empty string`);
|
|
621
621
|
}
|
|
622
|
+
function validateChoices(kind, options) {
|
|
623
|
+
const choices = Array.isArray(options?.options) ? options.options.map((option) => typeof option === "object" && option !== null && typeof option.value === "string" ? option.value : "[Invalid choice]") : [];
|
|
624
|
+
const prompt = details$1(kind, options?.message, choices);
|
|
625
|
+
validateMessage(kind, options?.message, choices);
|
|
626
|
+
if (!Array.isArray(options.options) || options.options.length === 0) throw promptError("invalid-options", prompt, `A ${kind} prompt requires at least one choice`);
|
|
627
|
+
const seen = /* @__PURE__ */ new Set();
|
|
628
|
+
for (const option of options.options) {
|
|
629
|
+
if (typeof option !== "object" || option === null || typeof option.value !== "string" || option.value.length === 0 || option.label !== void 0 && typeof option.label !== "string" || option.hint !== void 0 && typeof option.hint !== "string") throw promptError("invalid-options", prompt, `${kind === "select" ? "Select" : "Autocomplete"} choices must have valid string values`);
|
|
630
|
+
if (seen.has(option.value)) throw promptError("invalid-options", prompt, `Duplicate ${kind} choice: ${option.value}`);
|
|
631
|
+
seen.add(option.value);
|
|
632
|
+
}
|
|
633
|
+
return prompt;
|
|
634
|
+
}
|
|
635
|
+
function sortedChoices(options, prompt) {
|
|
636
|
+
const { sortBy } = options;
|
|
637
|
+
if (sortBy === void 0) return options.options;
|
|
638
|
+
if (typeof sortBy !== "function") throw promptError("invalid-options", prompt, "sortBy must be a function");
|
|
639
|
+
let keyType;
|
|
640
|
+
const keyed = options.options.map((item) => {
|
|
641
|
+
let key;
|
|
642
|
+
try {
|
|
643
|
+
key = sortBy(item);
|
|
644
|
+
} catch (cause) {
|
|
645
|
+
throw promptError("input-error", prompt, "Choice sort key could not be computed", cause);
|
|
646
|
+
}
|
|
647
|
+
if (typeof key !== "string" && (typeof key !== "number" || Number.isNaN(key))) throw promptError("invalid-options", prompt, "sortBy must return a string or a non-NaN number");
|
|
648
|
+
const type = typeof key;
|
|
649
|
+
if (keyType !== void 0 && keyType !== type) throw promptError("invalid-options", prompt, "sortBy keys must all have the same type");
|
|
650
|
+
keyType = type;
|
|
651
|
+
return {
|
|
652
|
+
item,
|
|
653
|
+
key
|
|
654
|
+
};
|
|
655
|
+
});
|
|
656
|
+
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
657
|
+
return keyed.map(({ item }) => item);
|
|
658
|
+
}
|
|
659
|
+
const graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
622
660
|
function asInput(value, prompt) {
|
|
623
661
|
if (typeof value !== "object" || value === null || typeof Reflect.get(value, "on") !== "function" || typeof Reflect.get(value, "removeListener") !== "function" || typeof Reflect.get(value, "resume") !== "function" || typeof Reflect.get(value, "pause") !== "function") throw promptError("input-error", prompt, "Interactive input is not a readable stream");
|
|
624
662
|
return value;
|
|
@@ -647,7 +685,7 @@ var PromptController = class {
|
|
|
647
685
|
throw promptError("printer-error", prompt, "The prompt could not be displayed", cause);
|
|
648
686
|
}
|
|
649
687
|
}
|
|
650
|
-
async #run(prompt, initial, accept, update, submitted, closed) {
|
|
688
|
+
async #run(prompt, initial, accept, update, submitted, closed, cancelOnEscape = () => true) {
|
|
651
689
|
if (!this.#interactive) throw promptError("non-interactive", prompt, `Cannot request ${prompt.kind} input in non-interactive mode: ${prompt.message}`);
|
|
652
690
|
if (this.#signal.aborted) throw promptError("aborted", prompt, "Prompt aborted", this.#signal.reason);
|
|
653
691
|
const input = asInput(this.#inputValue, prompt);
|
|
@@ -689,7 +727,7 @@ var PromptController = class {
|
|
|
689
727
|
};
|
|
690
728
|
const handleKeypress = async (character, key = {}) => {
|
|
691
729
|
if (settled) return;
|
|
692
|
-
if (key.ctrl && key.name === "c" || key.name === "escape") {
|
|
730
|
+
if (key.ctrl && key.name === "c" || key.name === "escape" && cancelOnEscape()) {
|
|
693
731
|
fail("cancelled", "Prompt cancelled");
|
|
694
732
|
return;
|
|
695
733
|
}
|
|
@@ -796,37 +834,144 @@ var PromptController = class {
|
|
|
796
834
|
this.#terminal.release();
|
|
797
835
|
}
|
|
798
836
|
}
|
|
799
|
-
async
|
|
800
|
-
const
|
|
801
|
-
const prompt = details$1("
|
|
802
|
-
validateMessage("
|
|
803
|
-
if (
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
837
|
+
async wait(work, options) {
|
|
838
|
+
const message = options?.message === void 0 ? "待機中" : options.message;
|
|
839
|
+
const prompt = details$1("wait", message);
|
|
840
|
+
validateMessage("wait", message);
|
|
841
|
+
if (typeof work !== "function") throw promptError("invalid-options", prompt, "Wait work must be a function");
|
|
842
|
+
if (this.#signal.aborted) throw promptError("aborted", prompt, "Prompt aborted", this.#signal.reason);
|
|
843
|
+
if (!this.#terminal.acquire("prompt")) throw promptError("overlapping", prompt, this.#terminal.owner === "exec" ? "A command is using the terminal" : "Another prompt is already active");
|
|
844
|
+
let frame = 0;
|
|
845
|
+
let stopped = false;
|
|
846
|
+
let timer;
|
|
847
|
+
let rendering = Promise.resolve();
|
|
848
|
+
let closing;
|
|
849
|
+
let failure;
|
|
850
|
+
const state = (status) => ({
|
|
851
|
+
kind: "wait",
|
|
852
|
+
message,
|
|
853
|
+
status,
|
|
854
|
+
...this.#interactive ? { frame } : {}
|
|
855
|
+
});
|
|
856
|
+
const recordFailure = (error) => {
|
|
857
|
+
failure ??= error;
|
|
858
|
+
};
|
|
859
|
+
const close = () => {
|
|
860
|
+
stopped = true;
|
|
861
|
+
clearTimeout(timer);
|
|
862
|
+
timer = void 0;
|
|
863
|
+
closing ??= rendering.then(() => this.#print(state("closed"), prompt)).catch(recordFailure);
|
|
864
|
+
return closing;
|
|
865
|
+
};
|
|
866
|
+
const tick = () => {
|
|
867
|
+
timer = void 0;
|
|
868
|
+
frame += 1;
|
|
869
|
+
rendering = rendering.then(() => this.#print(state("active"), prompt)).then(() => {
|
|
870
|
+
if (!stopped) timer = setTimeout(tick, 80);
|
|
871
|
+
}, (error) => {
|
|
872
|
+
recordFailure(error);
|
|
873
|
+
close();
|
|
874
|
+
});
|
|
875
|
+
};
|
|
876
|
+
const onAbort = () => {
|
|
877
|
+
recordFailure(promptError("aborted", prompt, "Prompt aborted", this.#signal.reason));
|
|
878
|
+
close();
|
|
879
|
+
};
|
|
880
|
+
let outcome;
|
|
881
|
+
try {
|
|
882
|
+
rendering = rendering.then(() => this.#print(state("active"), prompt)).catch(recordFailure);
|
|
883
|
+
this.#signal.addEventListener("abort", onAbort, { once: true });
|
|
884
|
+
if (this.#signal.aborted) onAbort();
|
|
885
|
+
await rendering;
|
|
886
|
+
if (failure !== void 0) throw failure;
|
|
887
|
+
if (this.#interactive) timer = setTimeout(tick, 80);
|
|
888
|
+
outcome = {
|
|
889
|
+
ok: true,
|
|
890
|
+
value: await work()
|
|
891
|
+
};
|
|
892
|
+
} catch (error) {
|
|
893
|
+
outcome = {
|
|
894
|
+
ok: false,
|
|
895
|
+
error
|
|
896
|
+
};
|
|
897
|
+
} finally {
|
|
898
|
+
try {
|
|
899
|
+
await close();
|
|
900
|
+
} finally {
|
|
901
|
+
this.#signal.removeEventListener("abort", onAbort);
|
|
902
|
+
this.#terminal.release();
|
|
903
|
+
}
|
|
809
904
|
}
|
|
810
|
-
|
|
905
|
+
if (!outcome.ok) throw outcome.error;
|
|
906
|
+
if (failure !== void 0) throw failure;
|
|
907
|
+
return outcome.value;
|
|
908
|
+
}
|
|
909
|
+
async select(options) {
|
|
910
|
+
const prompt = validateChoices("select", options);
|
|
911
|
+
const choices = sortedChoices(options, prompt);
|
|
912
|
+
let selected = options.initialValue === void 0 ? 0 : choices.findIndex(({ value }) => value === options.initialValue);
|
|
811
913
|
if (selected < 0) throw promptError("invalid-options", prompt, `Unknown initial select value: ${String(options.initialValue)}`);
|
|
812
914
|
const state = (status = "active") => ({
|
|
813
915
|
kind: "select",
|
|
814
916
|
message: options.message,
|
|
815
917
|
status,
|
|
816
|
-
value:
|
|
817
|
-
choices:
|
|
918
|
+
value: choices[selected].value,
|
|
919
|
+
choices: choices.map(({ value, label, hint }, index) => ({
|
|
818
920
|
value,
|
|
819
921
|
label: label ?? value,
|
|
820
922
|
...hint === void 0 ? {} : { hint },
|
|
821
923
|
selected: index === selected
|
|
822
924
|
}))
|
|
823
925
|
});
|
|
824
|
-
return await this.#run(prompt, state(), (_character, key) => key.name === "return" || key.name === "enter" ?
|
|
926
|
+
return await this.#run(prompt, state(), (_character, key) => key.name === "return" || key.name === "enter" ? choices[selected].value : void 0, (_character, key) => {
|
|
825
927
|
if (key.name !== "up" && key.name !== "down") return void 0;
|
|
826
|
-
selected = (selected + (key.name === "up" ? -1 : 1) +
|
|
928
|
+
selected = (selected + (key.name === "up" ? -1 : 1) + choices.length) % choices.length;
|
|
827
929
|
return state();
|
|
828
930
|
}, () => state("submitted"), () => state("closed"));
|
|
829
931
|
}
|
|
932
|
+
async autocomplete(options) {
|
|
933
|
+
const prompt = validateChoices("autocomplete", options);
|
|
934
|
+
if (options.placeholder !== void 0 && typeof options.placeholder !== "string") throw promptError("invalid-options", prompt, "Autocomplete placeholder must be a string");
|
|
935
|
+
const choices = sortedChoices(options, prompt);
|
|
936
|
+
let query = "";
|
|
937
|
+
let selected = -1;
|
|
938
|
+
let filtered = choices;
|
|
939
|
+
const state = (status = "active") => ({
|
|
940
|
+
kind: "autocomplete",
|
|
941
|
+
message: options.message,
|
|
942
|
+
status,
|
|
943
|
+
query,
|
|
944
|
+
phase: selected < 0 ? "input" : "select",
|
|
945
|
+
...options.placeholder === void 0 ? {} : { placeholder: options.placeholder },
|
|
946
|
+
...selected < 0 ? {} : { value: filtered[selected].value },
|
|
947
|
+
choices: filtered.map(({ value, label, hint }, index) => ({
|
|
948
|
+
value,
|
|
949
|
+
label: label ?? value,
|
|
950
|
+
...hint === void 0 ? {} : { hint },
|
|
951
|
+
selected: index === selected
|
|
952
|
+
}))
|
|
953
|
+
});
|
|
954
|
+
return await this.#run(prompt, state(), (_character, key) => selected >= 0 && (key.name === "return" || key.name === "enter") ? filtered[selected].value : void 0, (character, key) => {
|
|
955
|
+
if (key.name === "down") {
|
|
956
|
+
if (selected >= filtered.length - 1) return void 0;
|
|
957
|
+
selected += 1;
|
|
958
|
+
} else if (key.name === "up") {
|
|
959
|
+
if (selected < 0) return void 0;
|
|
960
|
+
selected -= 1;
|
|
961
|
+
} else if (key.name === "escape") selected = -1;
|
|
962
|
+
else {
|
|
963
|
+
if (key.name === "backspace") {
|
|
964
|
+
const last = graphemeSegmenter.segment(query).containing(query.length - 1);
|
|
965
|
+
query = last === void 0 ? "" : query.slice(0, last.index);
|
|
966
|
+
} else if (!key.ctrl && !key.meta && character.length > 0 && !/\p{Cc}/u.test(character)) query += character;
|
|
967
|
+
else return void 0;
|
|
968
|
+
selected = -1;
|
|
969
|
+
const search = query.toLowerCase();
|
|
970
|
+
filtered = search.length === 0 ? choices : choices.filter(({ value, label }) => (label ?? value).toLowerCase().includes(search));
|
|
971
|
+
}
|
|
972
|
+
return state();
|
|
973
|
+
}, () => state("submitted"), () => state("closed"), () => selected < 0);
|
|
974
|
+
}
|
|
830
975
|
async confirm(options) {
|
|
831
976
|
const prompt = details$1("confirm", options?.message);
|
|
832
977
|
validateMessage("confirm", options?.message);
|