@inquirer/core 11.1.6 → 11.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ export { isUpKey, isDownKey, isSpaceKey, isBackspaceKey, isTabKey, isNumberKey, isEnterKey, isShiftKey, type KeypressEvent, type Keybinding, } from './lib/key.ts';
2
+ export * from './lib/errors.ts';
3
+ export { usePrefix } from './lib/use-prefix.ts';
4
+ export { useState } from './lib/use-state.ts';
5
+ export { useEffect } from './lib/use-effect.ts';
6
+ export { useMemo } from './lib/use-memo.ts';
7
+ export { useRef } from './lib/use-ref.ts';
8
+ export { useKeypress } from './lib/use-keypress.ts';
9
+ export { makeTheme } from './lib/make-theme.ts';
10
+ export type { Theme, Status } from './lib/theme.ts';
11
+ export { usePagination } from './lib/pagination/use-pagination.ts';
12
+ export { createPrompt } from './lib/create-prompt.ts';
13
+ export { Separator } from './lib/Separator.ts';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { isUpKey, isDownKey, isSpaceKey, isBackspaceKey, isTabKey, isNumberKey, isEnterKey, isShiftKey, } from "./lib/key.js";
2
+ export * from "./lib/errors.js";
3
+ export { usePrefix } from "./lib/use-prefix.js";
4
+ export { useState } from "./lib/use-state.js";
5
+ export { useEffect } from "./lib/use-effect.js";
6
+ export { useMemo } from "./lib/use-memo.js";
7
+ export { useRef } from "./lib/use-ref.js";
8
+ export { useKeypress } from "./lib/use-keypress.js";
9
+ export { makeTheme } from "./lib/make-theme.js";
10
+ export { usePagination } from "./lib/pagination/use-pagination.js";
11
+ export { createPrompt } from "./lib/create-prompt.js";
12
+ export { Separator } from "./lib/Separator.js";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Separator object
3
+ * Used to space/separate choices group
4
+ */
5
+ export declare class Separator {
6
+ readonly separator: string;
7
+ readonly type: string;
8
+ constructor(separator?: string);
9
+ static isSeparator(choice: unknown): choice is Separator;
10
+ }
@@ -0,0 +1,21 @@
1
+ import { styleText } from 'node:util';
2
+ import figures from '@inquirer/figures';
3
+ /**
4
+ * Separator object
5
+ * Used to space/separate choices group
6
+ */
7
+ export class Separator {
8
+ separator = styleText('dim', Array.from({ length: 15 }).join(figures.line));
9
+ type = 'separator';
10
+ constructor(separator) {
11
+ if (separator) {
12
+ this.separator = separator;
13
+ }
14
+ }
15
+ static isSeparator(choice) {
16
+ return Boolean(choice &&
17
+ typeof choice === 'object' &&
18
+ 'type' in choice &&
19
+ choice.type === 'separator');
20
+ }
21
+ }
@@ -0,0 +1,4 @@
1
+ import { type Prompt, type Prettify } from '@inquirer/type';
2
+ type ViewFunction<Value, Config> = (config: Prettify<Config>, done: (value: Value) => void) => string | [string, string | undefined];
3
+ export declare function createPrompt<Value, Config>(view: ViewFunction<Value, Config>): Prompt<Value, Config>;
4
+ export {};
@@ -0,0 +1,143 @@
1
+ import * as readline from 'node:readline';
2
+ import { AsyncResource } from 'node:async_hooks';
3
+ import MuteStream from 'mute-stream';
4
+ import { onExit as onSignalExit } from 'signal-exit';
5
+ import ScreenManager from "./screen-manager.js";
6
+ import { PromisePolyfill } from "./promise-polyfill.js";
7
+ import { withHooks, effectScheduler } from "./hook-engine.js";
8
+ import { AbortPromptError, CancelPromptError, ExitPromptError } from "./errors.js";
9
+ // Capture the real setImmediate at module load time so it works even when test
10
+ // frameworks mock timers with vi.useFakeTimers() or similar.
11
+ const nativeSetImmediate = globalThis.setImmediate;
12
+ function getCallSites() {
13
+ // eslint-disable-next-line @typescript-eslint/unbound-method
14
+ const _prepareStackTrace = Error.prepareStackTrace;
15
+ let result = [];
16
+ try {
17
+ Error.prepareStackTrace = (_, callSites) => {
18
+ const callSitesWithoutCurrent = callSites.slice(1);
19
+ result = callSitesWithoutCurrent;
20
+ return callSitesWithoutCurrent;
21
+ };
22
+ // oxlint-disable-next-line no-unused-expressions
23
+ new Error().stack;
24
+ }
25
+ catch {
26
+ // An error will occur if the Node flag --frozen-intrinsics is used.
27
+ // https://nodejs.org/api/cli.html#--frozen-intrinsics
28
+ return result;
29
+ }
30
+ Error.prepareStackTrace = _prepareStackTrace;
31
+ return result;
32
+ }
33
+ export function createPrompt(view) {
34
+ const callSites = getCallSites();
35
+ const prompt = (config, context = {}) => {
36
+ // Default `input` to stdin
37
+ const { input = process.stdin, signal } = context;
38
+ const cleanups = new Set();
39
+ // Add mute capabilities to the output
40
+ const output = new MuteStream();
41
+ output.pipe(context.output ?? process.stdout);
42
+ // Pre-mute the output so that readline doesn't echo stale keystrokes
43
+ // to the terminal before the first render. ScreenManager will unmute/mute
44
+ // the output around each render call as needed.
45
+ output.mute();
46
+ const rl = readline.createInterface({
47
+ terminal: true,
48
+ input,
49
+ output,
50
+ });
51
+ const screen = new ScreenManager(rl);
52
+ const { promise, resolve, reject } = PromisePolyfill.withResolver();
53
+ const cancel = () => reject(new CancelPromptError());
54
+ if (signal) {
55
+ const abort = () => reject(new AbortPromptError({ cause: signal.reason }));
56
+ if (signal.aborted) {
57
+ abort();
58
+ return Object.assign(promise, { cancel });
59
+ }
60
+ signal.addEventListener('abort', abort);
61
+ cleanups.add(() => signal.removeEventListener('abort', abort));
62
+ }
63
+ cleanups.add(onSignalExit((code, signal) => {
64
+ reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
65
+ }));
66
+ // SIGINT must be explicitly handled by the prompt so the ExitPromptError can be handled.
67
+ // Otherwise, the prompt will stop and in some scenarios never resolve.
68
+ // Ref issue #1741
69
+ const sigint = () => reject(new ExitPromptError(`User force closed the prompt with SIGINT`));
70
+ rl.on('SIGINT', sigint);
71
+ cleanups.add(() => rl.removeListener('SIGINT', sigint));
72
+ return withHooks(rl, (cycle) => {
73
+ // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
74
+ // triggers after the process is done (which happens after timeouts are done triggering.)
75
+ // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
76
+ const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll());
77
+ rl.on('close', hooksCleanup);
78
+ cleanups.add(() => rl.removeListener('close', hooksCleanup));
79
+ const startCycle = () => {
80
+ // Re-renders only happen when the state change; but the readline cursor could
81
+ // change position and that also requires a re-render (and a manual one because
82
+ // we mute the streams). We set the listener after the initial workLoop to avoid
83
+ // a double render if render triggered by a state change sets the cursor to the
84
+ // right position.
85
+ const checkCursorPos = () => screen.checkCursorPos();
86
+ rl.input.on('keypress', checkCursorPos);
87
+ cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
88
+ cycle(() => {
89
+ try {
90
+ const nextView = view(config, (value) => {
91
+ setImmediate(() => resolve(value));
92
+ });
93
+ // Typescript won't allow this, but not all users rely on typescript.
94
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
95
+ if (nextView === undefined) {
96
+ const callerFilename = callSites[1]?.getFileName();
97
+ throw new Error(`Prompt functions must return a string.\n at ${callerFilename}`);
98
+ }
99
+ const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
100
+ screen.render(content, bottomContent);
101
+ effectScheduler.run();
102
+ }
103
+ catch (error) {
104
+ reject(error);
105
+ }
106
+ });
107
+ };
108
+ // Proper Readable streams (like process.stdin) may have OS-level buffered
109
+ // data that arrives in the poll phase when readline resumes the stream.
110
+ // Deferring the first render by one setImmediate tick (check phase, after
111
+ // poll) lets that stale data flow through readline harmlessly—no keypress
112
+ // handlers are registered yet and the output is muted, so the stale
113
+ // keystrokes are silently discarded.
114
+ // Old-style streams (like MuteStream) have no such buffering, so the
115
+ // render cycle starts immediately.
116
+ //
117
+ // @see https://github.com/SBoudrias/Inquirer.js/issues/1303
118
+ if ('readableFlowing' in input) {
119
+ nativeSetImmediate(startCycle);
120
+ }
121
+ else {
122
+ startCycle();
123
+ }
124
+ return Object.assign(promise
125
+ .then((answer) => {
126
+ effectScheduler.clearAll();
127
+ return answer;
128
+ }, (error) => {
129
+ effectScheduler.clearAll();
130
+ throw error;
131
+ })
132
+ // Wait for the promise to settle, then cleanup.
133
+ .finally(() => {
134
+ cleanups.forEach((cleanup) => cleanup());
135
+ screen.done({ clearContent: Boolean(context.clearPromptOnDone) });
136
+ output.end();
137
+ })
138
+ // Once cleanup is done, let the expose promise resolve/reject to the internal one.
139
+ .then(() => promise), { cancel });
140
+ });
141
+ };
142
+ return prompt;
143
+ }
@@ -0,0 +1,20 @@
1
+ export declare class AbortPromptError extends Error {
2
+ name: string;
3
+ message: string;
4
+ constructor(options?: {
5
+ cause?: unknown;
6
+ });
7
+ }
8
+ export declare class CancelPromptError extends Error {
9
+ name: string;
10
+ message: string;
11
+ }
12
+ export declare class ExitPromptError extends Error {
13
+ name: string;
14
+ }
15
+ export declare class HookError extends Error {
16
+ name: string;
17
+ }
18
+ export declare class ValidationError extends Error {
19
+ name: string;
20
+ }
@@ -0,0 +1,21 @@
1
+ export class AbortPromptError extends Error {
2
+ name = 'AbortPromptError';
3
+ message = 'Prompt was aborted';
4
+ constructor(options) {
5
+ super();
6
+ this.cause = options?.cause;
7
+ }
8
+ }
9
+ export class CancelPromptError extends Error {
10
+ name = 'CancelPromptError';
11
+ message = 'Prompt was canceled';
12
+ }
13
+ export class ExitPromptError extends Error {
14
+ name = 'ExitPromptError';
15
+ }
16
+ export class HookError extends Error {
17
+ name = 'HookError';
18
+ }
19
+ export class ValidationError extends Error {
20
+ name = 'ValidationError';
21
+ }
@@ -0,0 +1,23 @@
1
+ import type { InquirerReadline } from '@inquirer/type';
2
+ export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
3
+ export declare function readline(): InquirerReadline;
4
+ export declare function withUpdates<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R;
5
+ type SetPointer<Value> = {
6
+ get(): Value;
7
+ set(value: Value): void;
8
+ initialized: true;
9
+ };
10
+ type UnsetPointer<Value> = {
11
+ get(): void;
12
+ set(value: Value): void;
13
+ initialized: false;
14
+ };
15
+ type Pointer<Value> = SetPointer<Value> | UnsetPointer<Value>;
16
+ export declare function withPointer<Value, ReturnValue>(cb: (pointer: Pointer<Value>) => ReturnValue): ReturnValue;
17
+ export declare function handleChange(): void;
18
+ export declare const effectScheduler: {
19
+ queue(cb: (readline: InquirerReadline) => void | (() => void)): void;
20
+ run(): void;
21
+ clearAll(): void;
22
+ };
23
+ export {};
@@ -0,0 +1,110 @@
1
+ /* eslint @typescript-eslint/no-explicit-any: ["off"] */
2
+ import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
3
+ import { HookError, ValidationError } from "./errors.js";
4
+ const hookStorage = new AsyncLocalStorage();
5
+ function createStore(rl) {
6
+ const store = {
7
+ rl,
8
+ hooks: [],
9
+ hooksCleanup: [],
10
+ hooksEffect: [],
11
+ index: 0,
12
+ handleChange() { },
13
+ };
14
+ return store;
15
+ }
16
+ // Run callback in with the hook engine setup.
17
+ export function withHooks(rl, cb) {
18
+ const store = createStore(rl);
19
+ return hookStorage.run(store, () => {
20
+ function cycle(render) {
21
+ store.handleChange = () => {
22
+ store.index = 0;
23
+ render();
24
+ };
25
+ store.handleChange();
26
+ }
27
+ return cb(cycle);
28
+ });
29
+ }
30
+ // Safe getStore utility that'll return the store or throw if undefined.
31
+ function getStore() {
32
+ const store = hookStorage.getStore();
33
+ if (!store) {
34
+ throw new HookError('[Inquirer] Hook functions can only be called from within a prompt');
35
+ }
36
+ return store;
37
+ }
38
+ export function readline() {
39
+ return getStore().rl;
40
+ }
41
+ // Merge state updates happening within the callback function to avoid multiple renders.
42
+ export function withUpdates(fn) {
43
+ const wrapped = (...args) => {
44
+ const store = getStore();
45
+ let shouldUpdate = false;
46
+ const oldHandleChange = store.handleChange;
47
+ store.handleChange = () => {
48
+ shouldUpdate = true;
49
+ };
50
+ const returnValue = fn(...args);
51
+ if (shouldUpdate) {
52
+ oldHandleChange();
53
+ }
54
+ store.handleChange = oldHandleChange;
55
+ return returnValue;
56
+ };
57
+ return AsyncResource.bind(wrapped);
58
+ }
59
+ export function withPointer(cb) {
60
+ const store = getStore();
61
+ const { index } = store;
62
+ const pointer = {
63
+ get() {
64
+ return store.hooks[index];
65
+ },
66
+ set(value) {
67
+ store.hooks[index] = value;
68
+ },
69
+ initialized: index in store.hooks,
70
+ };
71
+ const returnValue = cb(pointer);
72
+ store.index++;
73
+ return returnValue;
74
+ }
75
+ export function handleChange() {
76
+ getStore().handleChange();
77
+ }
78
+ export const effectScheduler = {
79
+ queue(cb) {
80
+ const store = getStore();
81
+ const { index } = store;
82
+ store.hooksEffect.push(() => {
83
+ store.hooksCleanup[index]?.();
84
+ const cleanFn = cb(readline());
85
+ if (cleanFn != null && typeof cleanFn !== 'function') {
86
+ throw new ValidationError('useEffect return value must be a cleanup function or nothing.');
87
+ }
88
+ store.hooksCleanup[index] = cleanFn;
89
+ });
90
+ },
91
+ run() {
92
+ const store = getStore();
93
+ withUpdates(() => {
94
+ store.hooksEffect.forEach((effect) => {
95
+ effect();
96
+ });
97
+ // Warning: Clean the hooks before exiting the `withUpdates` block.
98
+ // Failure to do so means an updates would hit the same effects again.
99
+ store.hooksEffect.length = 0;
100
+ })();
101
+ },
102
+ clearAll() {
103
+ const store = getStore();
104
+ store.hooksCleanup.forEach((cleanFn) => {
105
+ cleanFn?.();
106
+ });
107
+ store.hooksEffect.length = 0;
108
+ store.hooksCleanup.length = 0;
109
+ },
110
+ };
@@ -0,0 +1,14 @@
1
+ export type KeypressEvent = {
2
+ name: string;
3
+ ctrl: boolean;
4
+ shift: boolean;
5
+ };
6
+ export type Keybinding = 'emacs' | 'vim';
7
+ export declare const isUpKey: (key: KeypressEvent, keybindings?: ReadonlyArray<Keybinding>) => boolean;
8
+ export declare const isDownKey: (key: KeypressEvent, keybindings?: ReadonlyArray<Keybinding>) => boolean;
9
+ export declare const isSpaceKey: (key: KeypressEvent) => boolean;
10
+ export declare const isBackspaceKey: (key: KeypressEvent) => boolean;
11
+ export declare const isTabKey: (key: KeypressEvent) => boolean;
12
+ export declare const isNumberKey: (key: KeypressEvent) => boolean;
13
+ export declare const isEnterKey: (key: KeypressEvent) => boolean;
14
+ export declare const isShiftKey: (key: KeypressEvent) => boolean;
@@ -0,0 +1,20 @@
1
+ export const isUpKey = (key, keybindings = []) =>
2
+ // The up key
3
+ key.name === 'up' ||
4
+ // Vim keybinding: hjkl keys map to left/down/up/right
5
+ (keybindings.includes('vim') && key.name === 'k') ||
6
+ // Emacs keybinding: Ctrl+P means "previous" in Emacs navigation conventions
7
+ (keybindings.includes('emacs') && key.ctrl && key.name === 'p');
8
+ export const isDownKey = (key, keybindings = []) =>
9
+ // The down key
10
+ key.name === 'down' ||
11
+ // Vim keybinding: hjkl keys map to left/down/up/right
12
+ (keybindings.includes('vim') && key.name === 'j') ||
13
+ // Emacs keybinding: Ctrl+N means "next" in Emacs navigation conventions
14
+ (keybindings.includes('emacs') && key.ctrl && key.name === 'n');
15
+ export const isSpaceKey = (key) => key.name === 'space';
16
+ export const isBackspaceKey = (key) => key.name === 'backspace';
17
+ export const isTabKey = (key) => key.name === 'tab';
18
+ export const isNumberKey = (key) => '1234567890'.includes(key.name);
19
+ export const isEnterKey = (key) => key.name === 'enter' || key.name === 'return';
20
+ export const isShiftKey = (key) => key.shift;
@@ -0,0 +1,3 @@
1
+ import type { Prettify, PartialDeep } from '@inquirer/type';
2
+ import { type Theme } from './theme.ts';
3
+ export declare function makeTheme<SpecificTheme extends object>(...themes: ReadonlyArray<undefined | PartialDeep<Theme<SpecificTheme>>>): Prettify<Theme<SpecificTheme>>;
@@ -0,0 +1,30 @@
1
+ import { defaultTheme } from "./theme.js";
2
+ function isPlainObject(value) {
3
+ if (typeof value !== 'object' || value === null)
4
+ return false;
5
+ let proto = value;
6
+ while (Object.getPrototypeOf(proto) !== null) {
7
+ proto = Object.getPrototypeOf(proto);
8
+ }
9
+ return Object.getPrototypeOf(value) === proto;
10
+ }
11
+ function deepMerge(...objects) {
12
+ const output = {};
13
+ for (const obj of objects) {
14
+ for (const [key, value] of Object.entries(obj)) {
15
+ const prevValue = output[key];
16
+ output[key] =
17
+ isPlainObject(prevValue) && isPlainObject(value)
18
+ ? deepMerge(prevValue, value)
19
+ : value;
20
+ }
21
+ }
22
+ return output;
23
+ }
24
+ export function makeTheme(...themes) {
25
+ const themesToMerge = [
26
+ defaultTheme,
27
+ ...themes.filter((theme) => theme != null),
28
+ ];
29
+ return deepMerge(...themesToMerge);
30
+ }
@@ -0,0 +1,16 @@
1
+ import type { Prettify } from '@inquirer/type';
2
+ export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
3
+ items: ReadonlyArray<T>;
4
+ /** The index of the active item. */
5
+ active: number;
6
+ /** Renders an item as part of a page. */
7
+ renderItem: (layout: Prettify<{
8
+ item: T;
9
+ index: number;
10
+ isActive: boolean;
11
+ }>) => string;
12
+ /** The size of the page. */
13
+ pageSize: number;
14
+ /** Allows creating an infinitely looping list. `true` if unspecified. */
15
+ loop?: boolean;
16
+ }): string;
@@ -0,0 +1,121 @@
1
+ import { useRef } from "../use-ref.js";
2
+ import { readlineWidth, breakLines } from "../utils.js";
3
+ function usePointerPosition({ active, renderedItems, pageSize, loop, }) {
4
+ const state = useRef({
5
+ lastPointer: active,
6
+ lastActive: undefined,
7
+ });
8
+ const { lastPointer, lastActive } = state.current;
9
+ const middle = Math.floor(pageSize / 2);
10
+ const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
11
+ const defaultPointerPosition = renderedItems
12
+ .slice(0, active)
13
+ .reduce((acc, item) => acc + item.length, 0);
14
+ let pointer = defaultPointerPosition;
15
+ if (renderedLength > pageSize) {
16
+ if (loop) {
17
+ /**
18
+ * Creates the next position for the pointer considering an infinitely
19
+ * looping list of items to be rendered on the page.
20
+ *
21
+ * The goal is to progressively move the cursor to the middle position as the user move down, and then keep
22
+ * the cursor there. When the user move up, maintain the cursor position.
23
+ */
24
+ // By default, keep the cursor position as-is.
25
+ pointer = lastPointer;
26
+ if (
27
+ // First render, skip this logic.
28
+ lastActive != null &&
29
+ // Only move the pointer down when the user moves down.
30
+ lastActive < active &&
31
+ // Check user didn't move up across page boundary.
32
+ active - lastActive < pageSize) {
33
+ pointer = Math.min(
34
+ // Furthest allowed position for the pointer is the middle of the list
35
+ middle, Math.abs(active - lastActive) === 1
36
+ ? Math.min(
37
+ // Move the pointer at most the height of the last active item.
38
+ lastPointer + (renderedItems[lastActive]?.length ?? 0),
39
+ // If the user moved by one item, move the pointer to the natural position of the active item as
40
+ // long as it doesn't move the cursor up.
41
+ Math.max(defaultPointerPosition, lastPointer))
42
+ : // Otherwise, move the pointer down by the difference between the active and last active item.
43
+ lastPointer + active - lastActive);
44
+ }
45
+ }
46
+ else {
47
+ /**
48
+ * Creates the next position for the pointer considering a finite list of
49
+ * items to be rendered on a page.
50
+ *
51
+ * The goal is to keep the pointer in the middle of the page whenever possible, until
52
+ * we reach the bounds of the list (top or bottom). In which case, the cursor moves progressively
53
+ * to the bottom or top of the list.
54
+ */
55
+ const spaceUnderActive = renderedItems
56
+ .slice(active)
57
+ .reduce((acc, item) => acc + item.length, 0);
58
+ pointer =
59
+ spaceUnderActive < pageSize - middle
60
+ ? // If the active item is near the end of the list, progressively move the cursor towards the end.
61
+ pageSize - spaceUnderActive
62
+ : // Otherwise, progressively move the pointer to the middle of the list.
63
+ Math.min(defaultPointerPosition, middle);
64
+ }
65
+ }
66
+ // Save state for the next render
67
+ state.current.lastPointer = pointer;
68
+ state.current.lastActive = active;
69
+ return pointer;
70
+ }
71
+ export function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
72
+ const width = readlineWidth();
73
+ const bound = (num) => ((num % items.length) + items.length) % items.length;
74
+ const renderedItems = items.map((item, index) => {
75
+ if (item == null)
76
+ return [];
77
+ return breakLines(renderItem({ item, index, isActive: index === active }), width).split('\n');
78
+ });
79
+ const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
80
+ const renderItemAtIndex = (index) => renderedItems[index] ?? [];
81
+ const pointer = usePointerPosition({ active, renderedItems, pageSize, loop });
82
+ // Render the active item to decide the position.
83
+ // If the active item fits under the pointer, we render it there.
84
+ // Otherwise, we need to render it to fit at the bottom of the page; moving the pointer up.
85
+ const activeItem = renderItemAtIndex(active).slice(0, pageSize);
86
+ const activeItemPosition = pointer + activeItem.length <= pageSize ? pointer : pageSize - activeItem.length;
87
+ // Create an array of lines for the page, and add the lines of the active item into the page
88
+ const pageBuffer = Array.from({ length: pageSize });
89
+ pageBuffer.splice(activeItemPosition, activeItem.length, ...activeItem);
90
+ // Store to prevent rendering the same item twice
91
+ const itemVisited = new Set([active]);
92
+ // Fill the page under the active item
93
+ let bufferPointer = activeItemPosition + activeItem.length;
94
+ let itemPointer = bound(active + 1);
95
+ while (bufferPointer < pageSize &&
96
+ !itemVisited.has(itemPointer) &&
97
+ (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer > active)) {
98
+ const lines = renderItemAtIndex(itemPointer);
99
+ const linesToAdd = lines.slice(0, pageSize - bufferPointer);
100
+ pageBuffer.splice(bufferPointer, linesToAdd.length, ...linesToAdd);
101
+ // Move pointers for next iteration
102
+ itemVisited.add(itemPointer);
103
+ bufferPointer += linesToAdd.length;
104
+ itemPointer = bound(itemPointer + 1);
105
+ }
106
+ // Fill the page over the active item
107
+ bufferPointer = activeItemPosition - 1;
108
+ itemPointer = bound(active - 1);
109
+ while (bufferPointer >= 0 &&
110
+ !itemVisited.has(itemPointer) &&
111
+ (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer < active)) {
112
+ const lines = renderItemAtIndex(itemPointer);
113
+ const linesToAdd = lines.slice(Math.max(0, lines.length - bufferPointer - 1));
114
+ pageBuffer.splice(bufferPointer - linesToAdd.length + 1, linesToAdd.length, ...linesToAdd);
115
+ // Move pointers for next iteration
116
+ itemVisited.add(itemPointer);
117
+ bufferPointer -= linesToAdd.length;
118
+ itemPointer = bound(itemPointer - 1);
119
+ }
120
+ return pageBuffer.filter((line) => typeof line === 'string').join('\n');
121
+ }
@@ -0,0 +1,7 @@
1
+ export declare class PromisePolyfill<T> extends Promise<T> {
2
+ static withResolver<T>(): {
3
+ promise: Promise<T>;
4
+ resolve: (value: T) => void;
5
+ reject: (error: unknown) => void;
6
+ };
7
+ }
@@ -0,0 +1,14 @@
1
+ // TODO: Remove this class once Node 22 becomes the minimum supported version.
2
+ export class PromisePolyfill extends Promise {
3
+ // Available starting from Node 22
4
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
5
+ static withResolver() {
6
+ let resolve;
7
+ let reject;
8
+ const promise = new Promise((res, rej) => {
9
+ resolve = res;
10
+ reject = rej;
11
+ });
12
+ return { promise, resolve: resolve, reject: reject };
13
+ }
14
+ }
@@ -0,0 +1,14 @@
1
+ import type { InquirerReadline } from '@inquirer/type';
2
+ export default class ScreenManager {
3
+ private height;
4
+ private extraLinesUnderPrompt;
5
+ private cursorPos;
6
+ private readonly rl;
7
+ constructor(rl: InquirerReadline);
8
+ write(content: string): void;
9
+ render(content: string, bottomContent?: string): void;
10
+ checkCursorPos(): void;
11
+ done({ clearContent }: {
12
+ clearContent: boolean;
13
+ }): void;
14
+ }
@@ -0,0 +1,79 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ import { breakLines, readlineWidth } from "./utils.js";
3
+ import { cursorDown, cursorUp, cursorTo, cursorShow, eraseLines } from '@inquirer/ansi';
4
+ const height = (content) => content.split('\n').length;
5
+ const lastLine = (content) => content.split('\n').pop() ?? '';
6
+ export default class ScreenManager {
7
+ // These variables are keeping information to allow correct prompt re-rendering
8
+ height = 0;
9
+ extraLinesUnderPrompt = 0;
10
+ cursorPos;
11
+ rl;
12
+ constructor(rl) {
13
+ this.rl = rl;
14
+ this.cursorPos = rl.getCursorPos();
15
+ }
16
+ write(content) {
17
+ this.rl.output.unmute();
18
+ this.rl.output.write(content);
19
+ this.rl.output.mute();
20
+ }
21
+ render(content, bottomContent = '') {
22
+ // Write message to screen and setPrompt to control backspace
23
+ const promptLine = lastLine(content);
24
+ const rawPromptLine = stripVTControlCharacters(promptLine);
25
+ // Remove the rl.line from our prompt. We can't rely on the content of
26
+ // rl.line (mainly because of the password prompt), so just rely on it's
27
+ // length.
28
+ let prompt = rawPromptLine;
29
+ if (this.rl.line.length > 0) {
30
+ prompt = prompt.slice(0, -this.rl.line.length);
31
+ }
32
+ this.rl.setPrompt(prompt);
33
+ // SetPrompt will change cursor position, now we can get correct value
34
+ this.cursorPos = this.rl.getCursorPos();
35
+ const width = readlineWidth();
36
+ content = breakLines(content, width);
37
+ bottomContent = breakLines(bottomContent, width);
38
+ // Manually insert an extra line if we're at the end of the line.
39
+ // This prevent the cursor from appearing at the beginning of the
40
+ // current line.
41
+ if (rawPromptLine.length % width === 0) {
42
+ content += '\n';
43
+ }
44
+ let output = content + (bottomContent ? '\n' + bottomContent : '');
45
+ /**
46
+ * Re-adjust the cursor at the correct position.
47
+ */
48
+ // We need to consider parts of the prompt under the cursor as part of the bottom
49
+ // content in order to correctly cleanup and re-render.
50
+ const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows;
51
+ const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
52
+ // Return cursor to the input position (on top of the bottomContent)
53
+ if (bottomContentHeight > 0)
54
+ output += cursorUp(bottomContentHeight);
55
+ // Return cursor to the initial left offset.
56
+ output += cursorTo(this.cursorPos.cols);
57
+ /**
58
+ * Render and store state for future re-rendering
59
+ */
60
+ this.write(cursorDown(this.extraLinesUnderPrompt) + eraseLines(this.height) + output);
61
+ this.extraLinesUnderPrompt = bottomContentHeight;
62
+ this.height = height(output);
63
+ }
64
+ checkCursorPos() {
65
+ const cursorPos = this.rl.getCursorPos();
66
+ if (cursorPos.cols !== this.cursorPos.cols) {
67
+ this.write(cursorTo(cursorPos.cols));
68
+ this.cursorPos = cursorPos;
69
+ }
70
+ }
71
+ done({ clearContent }) {
72
+ this.rl.setPrompt('');
73
+ let output = cursorDown(this.extraLinesUnderPrompt);
74
+ output += clearContent ? eraseLines(this.height) : '\n';
75
+ output += cursorShow;
76
+ this.write(output);
77
+ this.rl.close();
78
+ }
79
+ }
@@ -0,0 +1,155 @@
1
+ import type { Prettify } from '@inquirer/type';
2
+ /**
3
+ * Union type representing the possible statuses of a prompt.
4
+ *
5
+ * - `'loading'`: The prompt is currently loading.
6
+ * - `'idle'`: The prompt is loaded and currently waiting for the user to
7
+ * submit an answer.
8
+ * - `'done'`: The user has submitted an answer and the prompt is finished.
9
+ * - `string`: Any other string: The prompt is in a custom state.
10
+ */
11
+ export type Status = 'loading' | 'idle' | 'done' | (string & {});
12
+ type DefaultTheme = {
13
+ /**
14
+ * Prefix to prepend to the message. If a function is provided, it will be
15
+ * called with the current status of the prompt, and the return value will be
16
+ * used as the prefix.
17
+ *
18
+ * @remarks
19
+ * If `status === 'loading'`, this property is ignored and the spinner (styled
20
+ * by the `spinner` property) will be displayed instead.
21
+ *
22
+ * @defaultValue
23
+ * ```ts
24
+ * // import { styleText } from 'node:util';
25
+ * (status) => status === 'done' ? styleText('green', '✔') : styleText('blue', '?')
26
+ * ```
27
+ */
28
+ prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
29
+ /**
30
+ * Configuration for the spinner that is displayed when the prompt is in the
31
+ * `'loading'` state.
32
+ *
33
+ * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
34
+ */
35
+ spinner: {
36
+ /**
37
+ * The time interval between frames, in milliseconds.
38
+ *
39
+ * @defaultValue
40
+ * ```ts
41
+ * 80
42
+ * ```
43
+ */
44
+ interval: number;
45
+ /**
46
+ * A list of frames to show for the spinner.
47
+ *
48
+ * @defaultValue
49
+ * ```ts
50
+ * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
51
+ * ```
52
+ */
53
+ frames: string[];
54
+ };
55
+ /**
56
+ * Object containing functions to style different parts of the prompt.
57
+ */
58
+ style: {
59
+ /**
60
+ * Style to apply to the user's answer once it has been submitted.
61
+ *
62
+ * @param text - The user's answer.
63
+ * @returns The styled answer.
64
+ *
65
+ * @defaultValue
66
+ * ```ts
67
+ * // import { styleText } from 'node:util';
68
+ * (text) => styleText('cyan', text)
69
+ * ```
70
+ */
71
+ answer: (text: string) => string;
72
+ /**
73
+ * Style to apply to the message displayed to the user.
74
+ *
75
+ * @param text - The message to style.
76
+ * @param status - The current status of the prompt.
77
+ * @returns The styled message.
78
+ *
79
+ * @defaultValue
80
+ * ```ts
81
+ * // import { styleText } from 'node:util';
82
+ * (text, status) => styleText('bold', text)
83
+ * ```
84
+ */
85
+ message: (text: string, status: Status) => string;
86
+ /**
87
+ * Style to apply to error messages.
88
+ *
89
+ * @param text - The error message.
90
+ * @returns The styled error message.
91
+ *
92
+ * @defaultValue
93
+ * ```ts
94
+ * // import { styleText } from 'node:util';
95
+ * (text) => styleText('red', `> ${text}`)
96
+ * ```
97
+ */
98
+ error: (text: string) => string;
99
+ /**
100
+ * Style to apply to the default answer when one is provided.
101
+ *
102
+ * @param text - The default answer.
103
+ * @returns The styled default answer.
104
+ *
105
+ * @defaultValue
106
+ * ```ts
107
+ * // import { styleText } from 'node:util';
108
+ * (text) => styleText('dim', `(${text})`)
109
+ * ```
110
+ */
111
+ defaultAnswer: (text: string) => string;
112
+ /**
113
+ * Style to apply to help text.
114
+ *
115
+ * @param text - The help text.
116
+ * @returns The styled help text.
117
+ *
118
+ * @defaultValue
119
+ * ```ts
120
+ * // import { styleText } from 'node:util';
121
+ * (text) => styleText('dim', text)
122
+ * ```
123
+ */
124
+ help: (text: string) => string;
125
+ /**
126
+ * Style to apply to highlighted text.
127
+ *
128
+ * @param text - The text to highlight.
129
+ * @returns The highlighted text.
130
+ *
131
+ * @defaultValue
132
+ * ```ts
133
+ * // import { styleText } from 'node:util';
134
+ * (text) => styleText('cyan', text)
135
+ * ```
136
+ */
137
+ highlight: (text: string) => string;
138
+ /**
139
+ * Style to apply to keyboard keys referred to in help texts.
140
+ *
141
+ * @param text - The key to style.
142
+ * @returns The styled key.
143
+ *
144
+ * @defaultValue
145
+ * ```ts
146
+ * // import { styleText } from 'node:util';
147
+ * (text) => styleText('cyan', styleText('bold', `<${text}>`))
148
+ * ```
149
+ */
150
+ key: (text: string) => string;
151
+ };
152
+ };
153
+ export type Theme<Extension extends object = object> = Prettify<Extension & DefaultTheme>;
154
+ export declare const defaultTheme: DefaultTheme;
155
+ export {};
@@ -0,0 +1,21 @@
1
+ import { styleText } from 'node:util';
2
+ import figures from '@inquirer/figures';
3
+ export const defaultTheme = {
4
+ prefix: {
5
+ idle: styleText('blue', '?'),
6
+ done: styleText('green', figures.tick),
7
+ },
8
+ spinner: {
9
+ interval: 80,
10
+ frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => styleText('yellow', frame)),
11
+ },
12
+ style: {
13
+ answer: (text) => styleText('cyan', text),
14
+ message: (text) => styleText('bold', text),
15
+ error: (text) => styleText('red', `> ${text}`),
16
+ defaultAnswer: (text) => styleText('dim', `(${text})`),
17
+ help: (text) => styleText('dim', text),
18
+ highlight: (text) => styleText('cyan', text),
19
+ key: (text) => styleText('cyan', styleText('bold', `<${text}>`)),
20
+ },
21
+ };
@@ -0,0 +1,2 @@
1
+ import type { InquirerReadline } from '@inquirer/type';
2
+ export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: ReadonlyArray<unknown>): void;
@@ -0,0 +1,11 @@
1
+ import { withPointer, effectScheduler } from "./hook-engine.js";
2
+ export function useEffect(cb, depArray) {
3
+ withPointer((pointer) => {
4
+ const oldDeps = pointer.get();
5
+ const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
6
+ if (hasChanged) {
7
+ effectScheduler.queue(cb);
8
+ }
9
+ pointer.set(depArray);
10
+ });
11
+ }
@@ -0,0 +1,3 @@
1
+ import { type InquirerReadline } from '@inquirer/type';
2
+ import { type KeypressEvent } from './key.ts';
3
+ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void | Promise<void>): void;
@@ -0,0 +1,20 @@
1
+ import { useRef } from "./use-ref.js";
2
+ import { useEffect } from "./use-effect.js";
3
+ import { withUpdates } from "./hook-engine.js";
4
+ export function useKeypress(userHandler) {
5
+ const signal = useRef(userHandler);
6
+ signal.current = userHandler;
7
+ useEffect((rl) => {
8
+ let ignore = false;
9
+ const handler = withUpdates((_input, event) => {
10
+ if (ignore)
11
+ return;
12
+ void signal.current(event, rl);
13
+ });
14
+ rl.input.on('keypress', handler);
15
+ return () => {
16
+ ignore = true;
17
+ rl.input.removeListener('keypress', handler);
18
+ };
19
+ }, []);
20
+ }
@@ -0,0 +1 @@
1
+ export declare function useMemo<Value>(fn: () => Value, dependencies: ReadonlyArray<unknown>): Value;
@@ -0,0 +1,14 @@
1
+ import { withPointer } from "./hook-engine.js";
2
+ export function useMemo(fn, dependencies) {
3
+ return withPointer((pointer) => {
4
+ const prev = pointer.get();
5
+ if (!prev ||
6
+ prev.dependencies.length !== dependencies.length ||
7
+ prev.dependencies.some((dep, i) => dep !== dependencies[i])) {
8
+ const value = fn();
9
+ pointer.set({ value, dependencies });
10
+ return value;
11
+ }
12
+ return prev.value;
13
+ });
14
+ }
@@ -0,0 +1,5 @@
1
+ import type { Theme, Status } from './theme.ts';
2
+ export declare function usePrefix({ status, theme, }: {
3
+ status?: Status;
4
+ theme?: Theme;
5
+ }): string;
@@ -0,0 +1,35 @@
1
+ import { useState } from "./use-state.js";
2
+ import { useEffect } from "./use-effect.js";
3
+ import { makeTheme } from "./make-theme.js";
4
+ export function usePrefix({ status = 'idle', theme, }) {
5
+ const [showLoader, setShowLoader] = useState(false);
6
+ const [tick, setTick] = useState(0);
7
+ const { prefix, spinner } = makeTheme(theme);
8
+ useEffect(() => {
9
+ if (status === 'loading') {
10
+ let tickInterval;
11
+ let inc = -1;
12
+ // Delay displaying spinner by 300ms, to avoid flickering
13
+ const delayTimeout = setTimeout(() => {
14
+ setShowLoader(true);
15
+ tickInterval = setInterval(() => {
16
+ inc = inc + 1;
17
+ setTick(inc % spinner.frames.length);
18
+ }, spinner.interval);
19
+ }, 300);
20
+ return () => {
21
+ clearTimeout(delayTimeout);
22
+ clearInterval(tickInterval);
23
+ };
24
+ }
25
+ else {
26
+ setShowLoader(false);
27
+ }
28
+ }, [status]);
29
+ if (showLoader) {
30
+ return spinner.frames[tick];
31
+ }
32
+ // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
33
+ const iconName = status === 'loading' ? 'idle' : status;
34
+ return typeof prefix === 'string' ? prefix : (prefix[iconName] ?? prefix['idle']);
35
+ }
@@ -0,0 +1,6 @@
1
+ export declare function useRef<Value>(val: Value): {
2
+ current: Value;
3
+ };
4
+ export declare function useRef<Value>(val?: Value): {
5
+ current: Value | undefined;
6
+ };
@@ -0,0 +1,4 @@
1
+ import { useState } from "./use-state.js";
2
+ export function useRef(val) {
3
+ return useState({ current: val })[0];
4
+ }
@@ -0,0 +1,4 @@
1
+ type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
+ export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
+ export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
4
+ export {};
@@ -0,0 +1,20 @@
1
+ import { AsyncResource } from 'node:async_hooks';
2
+ import { withPointer, handleChange } from "./hook-engine.js";
3
+ export function useState(defaultValue) {
4
+ return withPointer((pointer) => {
5
+ const setState = AsyncResource.bind(function setState(newValue) {
6
+ // Noop if the value is still the same.
7
+ if (pointer.get() !== newValue) {
8
+ pointer.set(newValue);
9
+ // Trigger re-render
10
+ handleChange();
11
+ }
12
+ });
13
+ if (pointer.initialized) {
14
+ return [pointer.get(), setState];
15
+ }
16
+ const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
17
+ pointer.set(value);
18
+ return [value, setState];
19
+ });
20
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Force line returns at specific width. This function is ANSI code friendly and it'll
3
+ * ignore invisible codes during width calculation.
4
+ * @param {string} content
5
+ * @param {number} width
6
+ * @return {string}
7
+ */
8
+ export declare function breakLines(content: string, width: number): string;
9
+ /**
10
+ * Returns the width of the active readline, or 80 as default value.
11
+ * @returns {number}
12
+ */
13
+ export declare function readlineWidth(): number;
@@ -0,0 +1,25 @@
1
+ import cliWidth from 'cli-width';
2
+ import { wrapAnsi } from 'fast-wrap-ansi';
3
+ import { readline } from "./hook-engine.js";
4
+ /**
5
+ * Force line returns at specific width. This function is ANSI code friendly and it'll
6
+ * ignore invisible codes during width calculation.
7
+ * @param {string} content
8
+ * @param {number} width
9
+ * @return {string}
10
+ */
11
+ export function breakLines(content, width) {
12
+ return content
13
+ .split('\n')
14
+ .flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true })
15
+ .split('\n')
16
+ .map((str) => str.trimEnd()))
17
+ .join('\n');
18
+ }
19
+ /**
20
+ * Returns the width of the active readline, or 80 as default value.
21
+ * @returns {number}
22
+ */
23
+ export function readlineWidth() {
24
+ return cliWidth({ defaultWidth: 80, output: readline().output });
25
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "11.1.6",
3
+ "version": "11.1.7",
4
4
  "description": "Core Inquirer prompt API",
5
5
  "keywords": [
6
6
  "answer",
@@ -67,9 +67,9 @@
67
67
  "tsc": "tsc"
68
68
  },
69
69
  "dependencies": {
70
- "@inquirer/ansi": "^2.0.3",
71
- "@inquirer/figures": "^2.0.3",
72
- "@inquirer/type": "^4.0.3",
70
+ "@inquirer/ansi": "^2.0.4",
71
+ "@inquirer/figures": "^2.0.4",
72
+ "@inquirer/type": "^4.0.4",
73
73
  "cli-width": "^4.1.0",
74
74
  "fast-wrap-ansi": "^0.2.0",
75
75
  "mute-stream": "^3.0.0",
@@ -93,5 +93,5 @@
93
93
  },
94
94
  "main": "./dist/index.js",
95
95
  "types": "./dist/index.d.ts",
96
- "gitHead": "1ce03199b82b4a5fb6f7c97ce374c6da5087444f"
96
+ "gitHead": "b218fcc4afe888a58957aa78c9a032f9bd2d60cb"
97
97
  }