@inquirer/core 9.0.10 → 9.2.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 CHANGED
@@ -154,7 +154,7 @@ All default prompts, and most custom ones, uses a prefix at the beginning of the
154
154
 
155
155
  ```ts
156
156
  const input = createPrompt((config, done) => {
157
- const prefix = usePrefix({ isLoading });
157
+ const prefix = usePrefix({ status });
158
158
 
159
159
  return `${prefix} My question`;
160
160
  });
@@ -265,7 +265,7 @@ type PromptConfig = {
265
265
  export default createPrompt<string, PromptConfig>((config, done) => {
266
266
  const theme = makeTheme(config.theme);
267
267
 
268
- const prefix = usePrefix({ isLoading, theme });
268
+ const prefix = usePrefix({ status, theme });
269
269
 
270
270
  return `${prefix} ${theme.style.highlight('hello')}`;
271
271
  });
@@ -290,7 +290,7 @@ type PromptConfig = {
290
290
  export default createPrompt<string, PromptConfig>((config, done) => {
291
291
  const theme = makeTheme(promptTheme, config.theme);
292
292
 
293
- const prefix = usePrefix({ isLoading, theme });
293
+ const prefix = usePrefix({ status, theme });
294
294
 
295
295
  return `${prefix} ${theme.icon}`;
296
296
  });
@@ -300,14 +300,14 @@ The [default theme keys cover](https://github.com/SBoudrias/Inquirer.js/blob/the
300
300
 
301
301
  ```ts
302
302
  type DefaultTheme = {
303
- prefix: string;
303
+ prefix: string | { idle: string; done: string };
304
304
  spinner: {
305
305
  interval: number;
306
306
  frames: string[];
307
307
  };
308
308
  style: {
309
309
  answer: (text: string) => string;
310
- message: (text: string) => string;
310
+ message: (text: string, status: 'idle' | 'done' | 'loading') => string;
311
311
  error: (text: string) => string;
312
312
  defaultAnswer: (text: string) => string;
313
313
  help: (text: string) => string;
@@ -338,11 +338,12 @@ import {
338
338
  useKeypress,
339
339
  isEnterKey,
340
340
  usePrefix,
341
+ type Status,
341
342
  } from '@inquirer/core';
342
343
 
343
344
  const confirm = createPrompt<boolean, { message: string; default?: boolean }>(
344
345
  (config, done) => {
345
- const [status, setStatus] = useState('pending');
346
+ const [status, setStatus] = useState<Status>('idle');
346
347
  const [value, setValue] = useState('');
347
348
  const prefix = usePrefix({});
348
349
 
@@ -29,7 +29,10 @@ class Separator {
29
29
  }
30
30
  }
31
31
  static isSeparator(choice) {
32
- return Boolean(choice && choice.type === 'separator');
32
+ return Boolean(choice &&
33
+ typeof choice === 'object' &&
34
+ 'type' in choice &&
35
+ choice.type === 'separator');
33
36
  }
34
37
  }
35
38
  exports.Separator = Separator;
@@ -29,89 +29,86 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.createPrompt = createPrompt;
30
30
  const readline = __importStar(require("node:readline"));
31
31
  const node_async_hooks_1 = require("node:async_hooks");
32
- const type_1 = require("@inquirer/type");
33
32
  const mute_stream_1 = __importDefault(require("mute-stream"));
34
33
  const signal_exit_1 = require("signal-exit");
35
34
  const screen_manager_mjs_1 = __importDefault(require('./screen-manager.js'));
35
+ const promise_polyfill_mjs_1 = require('./promise-polyfill.js');
36
36
  const hook_engine_mjs_1 = require('./hook-engine.js');
37
37
  const errors_mjs_1 = require('./errors.js');
38
38
  function createPrompt(view) {
39
- const prompt = (config, context) => {
40
- var _a, _b;
39
+ const prompt = (config, context = {}) => {
40
+ var _a;
41
41
  // Default `input` to stdin
42
- const input = (_a = context === null || context === void 0 ? void 0 : context.input) !== null && _a !== void 0 ? _a : process.stdin;
42
+ const { input = process.stdin, signal } = context;
43
+ const cleanups = new Set();
43
44
  // Add mute capabilities to the output
44
45
  const output = new mute_stream_1.default();
45
- output.pipe((_b = context === null || context === void 0 ? void 0 : context.output) !== null && _b !== void 0 ? _b : process.stdout);
46
+ output.pipe((_a = context.output) !== null && _a !== void 0 ? _a : process.stdout);
46
47
  const rl = readline.createInterface({
47
48
  terminal: true,
48
49
  input,
49
50
  output,
50
51
  });
51
52
  const screen = new screen_manager_mjs_1.default(rl);
52
- let cancel = () => { };
53
- const answer = new type_1.CancelablePromise((resolve, reject) => {
54
- (0, hook_engine_mjs_1.withHooks)(rl, (cycle) => {
55
- function checkCursorPos() {
56
- screen.checkCursorPos();
57
- }
58
- const removeExitListener = (0, signal_exit_1.onExit)((code, signal) => {
59
- onExit();
60
- reject(new errors_mjs_1.ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
61
- });
62
- const hooksCleanup = node_async_hooks_1.AsyncResource.bind(() => {
63
- try {
64
- hook_engine_mjs_1.effectScheduler.clearAll();
65
- }
66
- catch (error) {
67
- reject(error);
68
- }
69
- });
70
- function onExit() {
71
- hooksCleanup();
72
- screen.done({ clearContent: Boolean(context === null || context === void 0 ? void 0 : context.clearPromptOnDone) });
73
- removeExitListener();
74
- rl.input.removeListener('keypress', checkCursorPos);
75
- rl.removeListener('close', hooksCleanup);
76
- output.end();
77
- }
78
- cancel = () => {
79
- onExit();
80
- reject(new errors_mjs_1.CancelPromptError());
81
- };
82
- function done(value) {
83
- // Delay execution to let time to the hookCleanup functions to registers.
84
- setImmediate(() => {
85
- onExit();
86
- // Finally we resolve our promise
87
- resolve(value);
53
+ const { promise, resolve, reject } = promise_polyfill_mjs_1.PromisePolyfill.withResolver();
54
+ /** @deprecated pass an AbortSignal in the context options instead. See {@link https://github.com/SBoudrias/Inquirer.js#canceling-prompt} */
55
+ const cancel = () => reject(new errors_mjs_1.CancelPromptError());
56
+ if (signal) {
57
+ const abort = () => reject(new errors_mjs_1.AbortPromptError({ cause: signal.reason }));
58
+ if (signal.aborted) {
59
+ abort();
60
+ return Object.assign(promise, { cancel });
61
+ }
62
+ signal.addEventListener('abort', abort);
63
+ cleanups.add(() => signal.removeEventListener('abort', abort));
64
+ }
65
+ cleanups.add((0, signal_exit_1.onExit)((code, signal) => {
66
+ reject(new errors_mjs_1.ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
67
+ }));
68
+ // Re-renders only happen when the state change; but the readline cursor could change position
69
+ // and that also requires a re-render (and a manual one because we mute the streams).
70
+ // We set the listener after the initial workLoop to avoid a double render if render triggered
71
+ // by a state change sets the cursor to the right position.
72
+ const checkCursorPos = () => screen.checkCursorPos();
73
+ rl.input.on('keypress', checkCursorPos);
74
+ cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
75
+ return (0, hook_engine_mjs_1.withHooks)(rl, (cycle) => {
76
+ // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
77
+ // triggers after the process is done (which happens after timeouts are done triggering.)
78
+ // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
79
+ const hooksCleanup = node_async_hooks_1.AsyncResource.bind(() => hook_engine_mjs_1.effectScheduler.clearAll());
80
+ rl.on('close', hooksCleanup);
81
+ cleanups.add(() => rl.removeListener('close', hooksCleanup));
82
+ cycle(() => {
83
+ try {
84
+ const nextView = view(config, (value) => {
85
+ setImmediate(() => resolve(value));
88
86
  });
87
+ const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
88
+ screen.render(content, bottomContent);
89
+ hook_engine_mjs_1.effectScheduler.run();
90
+ }
91
+ catch (error) {
92
+ reject(error);
89
93
  }
90
- cycle(() => {
91
- try {
92
- const nextView = view(config, done);
93
- const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
94
- screen.render(content, bottomContent);
95
- hook_engine_mjs_1.effectScheduler.run();
96
- }
97
- catch (error) {
98
- onExit();
99
- reject(error);
100
- }
101
- });
102
- // Re-renders only happen when the state change; but the readline cursor could change position
103
- // and that also requires a re-render (and a manual one because we mute the streams).
104
- // We set the listener after the initial workLoop to avoid a double render if render triggered
105
- // by a state change sets the cursor to the right position.
106
- rl.input.on('keypress', checkCursorPos);
107
- // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
108
- // triggers after the process is done (which happens after timeouts are done triggering.)
109
- // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
110
- rl.on('close', hooksCleanup);
111
94
  });
95
+ return Object.assign(promise
96
+ .then((answer) => {
97
+ hook_engine_mjs_1.effectScheduler.clearAll();
98
+ return answer;
99
+ }, (error) => {
100
+ hook_engine_mjs_1.effectScheduler.clearAll();
101
+ throw error;
102
+ })
103
+ // Wait for the promise to settle, then cleanup.
104
+ .finally(() => {
105
+ cleanups.forEach((cleanup) => cleanup());
106
+ screen.done({ clearContent: Boolean(context === null || context === void 0 ? void 0 : context.clearPromptOnDone) });
107
+ output.end();
108
+ })
109
+ // Once cleanup is done, let the expose promise resolve/reject to the internal one.
110
+ .then(() => promise), { cancel });
112
111
  });
113
- answer.cancel = cancel;
114
- return answer;
115
112
  };
116
113
  return prompt;
117
114
  }
@@ -1,6 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ValidationError = exports.HookError = exports.ExitPromptError = exports.CancelPromptError = void 0;
3
+ exports.ValidationError = exports.HookError = exports.ExitPromptError = exports.CancelPromptError = exports.AbortPromptError = void 0;
4
+ class AbortPromptError extends Error {
5
+ constructor(options) {
6
+ super();
7
+ Object.defineProperty(this, "name", {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value: 'AbortPromptError'
12
+ });
13
+ Object.defineProperty(this, "message", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: 'Prompt was aborted'
18
+ });
19
+ this.cause = options === null || options === void 0 ? void 0 : options.cause;
20
+ }
21
+ }
22
+ exports.AbortPromptError = AbortPromptError;
4
23
  class CancelPromptError extends Error {
5
24
  constructor() {
6
25
  super(...arguments);
@@ -32,7 +32,7 @@ function withHooks(rl, cb) {
32
32
  };
33
33
  store.handleChange();
34
34
  }
35
- cb(cycle);
35
+ return cb(cycle);
36
36
  });
37
37
  }
38
38
  // Safe getStore utility that'll return the store or throw if undefined.
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PromisePolyfill = void 0;
4
+ // TODO: Remove this class once Node 22 becomes the minimum supported version.
5
+ class PromisePolyfill extends Promise {
6
+ // Available starting from Node 22
7
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
8
+ static withResolver() {
9
+ let resolve;
10
+ let reject;
11
+ const promise = new Promise((res, rej) => {
12
+ resolve = res;
13
+ reject = rej;
14
+ });
15
+ return { promise, resolve: resolve, reject: reject };
16
+ }
17
+ }
18
+ exports.PromisePolyfill = PromisePolyfill;
@@ -5,12 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.defaultTheme = void 0;
7
7
  const yoctocolors_cjs_1 = __importDefault(require("yoctocolors-cjs"));
8
- const cli_spinners_1 = __importDefault(require("cli-spinners"));
8
+ const figures_1 = __importDefault(require("@inquirer/figures"));
9
9
  exports.defaultTheme = {
10
- prefix: yoctocolors_cjs_1.default.green('?'),
10
+ prefix: {
11
+ idle: yoctocolors_cjs_1.default.blue('?'),
12
+ // TODO: use figure
13
+ done: yoctocolors_cjs_1.default.green(figures_1.default.tick),
14
+ },
11
15
  spinner: {
12
- interval: cli_spinners_1.default.dots.interval,
13
- frames: cli_spinners_1.default.dots.frames.map((frame) => yoctocolors_cjs_1.default.yellow(frame)),
16
+ interval: 80,
17
+ frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => yoctocolors_cjs_1.default.yellow(frame)),
14
18
  },
15
19
  style: {
16
20
  answer: yoctocolors_cjs_1.default.cyan,
@@ -5,12 +5,12 @@ const node_async_hooks_1 = require("node:async_hooks");
5
5
  const use_state_mjs_1 = require('./use-state.js');
6
6
  const use_effect_mjs_1 = require('./use-effect.js');
7
7
  const make_theme_mjs_1 = require('./make-theme.js');
8
- function usePrefix({ isLoading = false, theme, }) {
8
+ function usePrefix({ status = 'idle', theme, }) {
9
9
  const [showLoader, setShowLoader] = (0, use_state_mjs_1.useState)(false);
10
10
  const [tick, setTick] = (0, use_state_mjs_1.useState)(0);
11
11
  const { prefix, spinner } = (0, make_theme_mjs_1.makeTheme)(theme);
12
12
  (0, use_effect_mjs_1.useEffect)(() => {
13
- if (isLoading) {
13
+ if (status === 'loading') {
14
14
  let tickInterval;
15
15
  let inc = -1;
16
16
  // Delay displaying spinner by 300ms, to avoid flickering
@@ -29,9 +29,11 @@ function usePrefix({ isLoading = false, theme, }) {
29
29
  else {
30
30
  setShowLoader(false);
31
31
  }
32
- }, [isLoading]);
32
+ }, [status]);
33
33
  if (showLoader) {
34
34
  return spinner.frames[tick];
35
35
  }
36
- return prefix;
36
+ // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
37
+ const iconName = status === 'loading' ? 'idle' : status;
38
+ return typeof prefix === 'string' ? prefix : prefix[iconName];
37
39
  }
@@ -7,7 +7,7 @@ export { useMemo } from './lib/use-memo.js';
7
7
  export { useRef } from './lib/use-ref.js';
8
8
  export { useKeypress } from './lib/use-keypress.js';
9
9
  export { makeTheme } from './lib/make-theme.js';
10
- export type { Theme } from './lib/theme.js';
10
+ export type { Theme, Status } from './lib/theme.js';
11
11
  export { usePagination } from './lib/pagination/use-pagination.js';
12
12
  export { createPrompt } from './lib/create-prompt.js';
13
13
  export { Separator } from './lib/Separator.js';
@@ -6,5 +6,5 @@ export declare class Separator {
6
6
  readonly separator: string;
7
7
  readonly type = "separator";
8
8
  constructor(separator?: string);
9
- static isSeparator(choice: undefined | Separator | Record<string, unknown>): choice is Separator;
9
+ static isSeparator(choice: unknown): choice is Separator;
10
10
  }
@@ -1,3 +1,10 @@
1
+ export declare class AbortPromptError extends Error {
2
+ name: string;
3
+ message: string;
4
+ constructor(options?: {
5
+ cause?: unknown;
6
+ });
7
+ }
1
8
  export declare class CancelPromptError extends Error {
2
9
  name: string;
3
10
  message: string;
@@ -1,5 +1,5 @@
1
1
  import type { InquirerReadline } from '@inquirer/type';
2
- export declare function withHooks(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => void): void;
2
+ export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
3
3
  export declare function readline(): InquirerReadline;
4
4
  export declare function withUpdates<R, T extends (...args: any[]) => R>(fn: T): (...args: Parameters<T>) => R;
5
5
  type SetPointer<Value> = {
@@ -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
+ }
@@ -1,17 +1,151 @@
1
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
+ */
10
+ export type Status = 'loading' | 'idle' | 'done';
2
11
  type DefaultTheme = {
3
- prefix: string;
12
+ /**
13
+ * Prefix to prepend to the message. If a function is provided, it will be
14
+ * called with the current status of the prompt, and the return value will be
15
+ * used as the prefix.
16
+ *
17
+ * @remarks
18
+ * If `status === 'loading'`, this property is ignored and the spinner (styled
19
+ * by the `spinner` property) will be displayed instead.
20
+ *
21
+ * @defaultValue
22
+ * ```ts
23
+ * // import colors from 'yoctocolors-cjs';
24
+ * (status) => status === 'done' ? colors.green('✔') : colors.blue('?')
25
+ * ```
26
+ */
27
+ prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
28
+ /**
29
+ * Configuration for the spinner that is displayed when the prompt is in the
30
+ * `'loading'` state.
31
+ *
32
+ * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
33
+ */
4
34
  spinner: {
35
+ /**
36
+ * The time interval between frames, in milliseconds.
37
+ *
38
+ * @defaultValue
39
+ * ```ts
40
+ * 80
41
+ * ```
42
+ */
5
43
  interval: number;
44
+ /**
45
+ * A list of frames to show for the spinner.
46
+ *
47
+ * @defaultValue
48
+ * ```ts
49
+ * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
50
+ * ```
51
+ */
6
52
  frames: string[];
7
53
  };
54
+ /**
55
+ * Object containing functions to style different parts of the prompt.
56
+ */
8
57
  style: {
58
+ /**
59
+ * Style to apply to the user's answer once it has been submitted.
60
+ *
61
+ * @param text - The user's answer.
62
+ * @returns The styled answer.
63
+ *
64
+ * @defaultValue
65
+ * ```ts
66
+ * // import colors from 'yoctocolors-cjs';
67
+ * (text) => colors.cyan(text)
68
+ * ```
69
+ */
9
70
  answer: (text: string) => string;
10
- message: (text: string) => string;
71
+ /**
72
+ * Style to apply to the message displayed to the user.
73
+ *
74
+ * @param text - The message to style.
75
+ * @param status - The current status of the prompt.
76
+ * @returns The styled message.
77
+ *
78
+ * @defaultValue
79
+ * ```ts
80
+ * // import colors from 'yoctocolors-cjs';
81
+ * (text, status) => colors.bold(text)
82
+ * ```
83
+ */
84
+ message: (text: string, status: Status) => string;
85
+ /**
86
+ * Style to apply to error messages.
87
+ *
88
+ * @param text - The error message.
89
+ * @returns The styled error message.
90
+ *
91
+ * @defaultValue
92
+ * ```ts
93
+ * // import colors from 'yoctocolors-cjs';
94
+ * (text) => colors.red(`> ${text}`)
95
+ * ```
96
+ */
11
97
  error: (text: string) => string;
98
+ /**
99
+ * Style to apply to the default answer when one is provided.
100
+ *
101
+ * @param text - The default answer.
102
+ * @returns The styled default answer.
103
+ *
104
+ * @defaultValue
105
+ * ```ts
106
+ * // import colors from 'yoctocolors-cjs';
107
+ * (text) => colors.dim(`(${text})`)
108
+ * ```
109
+ */
12
110
  defaultAnswer: (text: string) => string;
111
+ /**
112
+ * Style to apply to help text.
113
+ *
114
+ * @param text - The help text.
115
+ * @returns The styled help text.
116
+ *
117
+ * @defaultValue
118
+ * ```ts
119
+ * // import colors from 'yoctocolors-cjs';
120
+ * (text) => colors.dim(text)
121
+ * ```
122
+ */
13
123
  help: (text: string) => string;
124
+ /**
125
+ * Style to apply to highlighted text.
126
+ *
127
+ * @param text - The text to highlight.
128
+ * @returns The highlighted text.
129
+ *
130
+ * @defaultValue
131
+ * ```ts
132
+ * // import colors from 'yoctocolors-cjs';
133
+ * (text) => colors.cyan(text)
134
+ * ```
135
+ */
14
136
  highlight: (text: string) => string;
137
+ /**
138
+ * Style to apply to keyboard keys referred to in help texts.
139
+ *
140
+ * @param text - The key to style.
141
+ * @returns The styled key.
142
+ *
143
+ * @defaultValue
144
+ * ```ts
145
+ * // import colors from 'yoctocolors-cjs';
146
+ * (text) => colors.cyan(colors.bold(`<${text}>`))
147
+ * ```
148
+ */
15
149
  key: (text: string) => string;
16
150
  };
17
151
  };
@@ -1,5 +1,5 @@
1
- import { type Theme } from './theme.js';
2
- export declare function usePrefix({ isLoading, theme, }: {
3
- isLoading?: boolean;
1
+ import type { Theme, Status } from './theme.js';
2
+ export declare function usePrefix({ status, theme, }: {
3
+ status?: Status;
4
4
  theme?: Theme;
5
5
  }): string;
@@ -1,4 +1,4 @@
1
1
  type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
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 | undefined) => void];
3
+ export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
4
4
  export {};
@@ -13,6 +13,9 @@ export class Separator {
13
13
  }
14
14
  }
15
15
  static isSeparator(choice) {
16
- return Boolean(choice && choice.type === 'separator');
16
+ return Boolean(choice &&
17
+ typeof choice === 'object' &&
18
+ 'type' in choice &&
19
+ choice.type === 'separator');
17
20
  }
18
21
  }
@@ -1,87 +1,84 @@
1
1
  import * as readline from 'node:readline';
2
2
  import { AsyncResource } from 'node:async_hooks';
3
- import { CancelablePromise } from '@inquirer/type';
4
3
  import MuteStream from 'mute-stream';
5
4
  import { onExit as onSignalExit } from 'signal-exit';
6
5
  import ScreenManager from './screen-manager.mjs';
6
+ import { PromisePolyfill } from './promise-polyfill.mjs';
7
7
  import { withHooks, effectScheduler } from './hook-engine.mjs';
8
- import { CancelPromptError, ExitPromptError } from './errors.mjs';
8
+ import { AbortPromptError, CancelPromptError, ExitPromptError } from './errors.mjs';
9
9
  export function createPrompt(view) {
10
- const prompt = (config, context) => {
10
+ const prompt = (config, context = {}) => {
11
11
  // Default `input` to stdin
12
- const input = context?.input ?? process.stdin;
12
+ const { input = process.stdin, signal } = context;
13
+ const cleanups = new Set();
13
14
  // Add mute capabilities to the output
14
15
  const output = new MuteStream();
15
- output.pipe(context?.output ?? process.stdout);
16
+ output.pipe(context.output ?? process.stdout);
16
17
  const rl = readline.createInterface({
17
18
  terminal: true,
18
19
  input,
19
20
  output,
20
21
  });
21
22
  const screen = new ScreenManager(rl);
22
- let cancel = () => { };
23
- const answer = new CancelablePromise((resolve, reject) => {
24
- withHooks(rl, (cycle) => {
25
- function checkCursorPos() {
26
- screen.checkCursorPos();
27
- }
28
- const removeExitListener = onSignalExit((code, signal) => {
29
- onExit();
30
- reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
31
- });
32
- const hooksCleanup = AsyncResource.bind(() => {
33
- try {
34
- effectScheduler.clearAll();
35
- }
36
- catch (error) {
37
- reject(error);
38
- }
39
- });
40
- function onExit() {
41
- hooksCleanup();
42
- screen.done({ clearContent: Boolean(context?.clearPromptOnDone) });
43
- removeExitListener();
44
- rl.input.removeListener('keypress', checkCursorPos);
45
- rl.removeListener('close', hooksCleanup);
46
- output.end();
47
- }
48
- cancel = () => {
49
- onExit();
50
- reject(new CancelPromptError());
51
- };
52
- function done(value) {
53
- // Delay execution to let time to the hookCleanup functions to registers.
54
- setImmediate(() => {
55
- onExit();
56
- // Finally we resolve our promise
57
- resolve(value);
23
+ const { promise, resolve, reject } = PromisePolyfill.withResolver();
24
+ /** @deprecated pass an AbortSignal in the context options instead. See {@link https://github.com/SBoudrias/Inquirer.js#canceling-prompt} */
25
+ const cancel = () => reject(new CancelPromptError());
26
+ if (signal) {
27
+ const abort = () => reject(new AbortPromptError({ cause: signal.reason }));
28
+ if (signal.aborted) {
29
+ abort();
30
+ return Object.assign(promise, { cancel });
31
+ }
32
+ signal.addEventListener('abort', abort);
33
+ cleanups.add(() => signal.removeEventListener('abort', abort));
34
+ }
35
+ cleanups.add(onSignalExit((code, signal) => {
36
+ reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
37
+ }));
38
+ // Re-renders only happen when the state change; but the readline cursor could change position
39
+ // and that also requires a re-render (and a manual one because we mute the streams).
40
+ // We set the listener after the initial workLoop to avoid a double render if render triggered
41
+ // by a state change sets the cursor to the right position.
42
+ const checkCursorPos = () => screen.checkCursorPos();
43
+ rl.input.on('keypress', checkCursorPos);
44
+ cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
45
+ return withHooks(rl, (cycle) => {
46
+ // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
47
+ // triggers after the process is done (which happens after timeouts are done triggering.)
48
+ // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
49
+ const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll());
50
+ rl.on('close', hooksCleanup);
51
+ cleanups.add(() => rl.removeListener('close', hooksCleanup));
52
+ cycle(() => {
53
+ try {
54
+ const nextView = view(config, (value) => {
55
+ setImmediate(() => resolve(value));
58
56
  });
57
+ const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
58
+ screen.render(content, bottomContent);
59
+ effectScheduler.run();
60
+ }
61
+ catch (error) {
62
+ reject(error);
59
63
  }
60
- cycle(() => {
61
- try {
62
- const nextView = view(config, done);
63
- const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
64
- screen.render(content, bottomContent);
65
- effectScheduler.run();
66
- }
67
- catch (error) {
68
- onExit();
69
- reject(error);
70
- }
71
- });
72
- // Re-renders only happen when the state change; but the readline cursor could change position
73
- // and that also requires a re-render (and a manual one because we mute the streams).
74
- // We set the listener after the initial workLoop to avoid a double render if render triggered
75
- // by a state change sets the cursor to the right position.
76
- rl.input.on('keypress', checkCursorPos);
77
- // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
78
- // triggers after the process is done (which happens after timeouts are done triggering.)
79
- // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
80
- rl.on('close', hooksCleanup);
81
64
  });
65
+ return Object.assign(promise
66
+ .then((answer) => {
67
+ effectScheduler.clearAll();
68
+ return answer;
69
+ }, (error) => {
70
+ effectScheduler.clearAll();
71
+ throw error;
72
+ })
73
+ // Wait for the promise to settle, then cleanup.
74
+ .finally(() => {
75
+ cleanups.forEach((cleanup) => cleanup());
76
+ screen.done({ clearContent: Boolean(context?.clearPromptOnDone) });
77
+ output.end();
78
+ })
79
+ // Once cleanup is done, let the expose promise resolve/reject to the internal one.
80
+ .then(() => promise), { cancel });
82
81
  });
83
- answer.cancel = cancel;
84
- return answer;
85
82
  };
86
83
  return prompt;
87
84
  }
@@ -1,3 +1,11 @@
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
+ }
1
9
  export class CancelPromptError extends Error {
2
10
  name = 'CancelPromptError';
3
11
  message = 'Prompt was canceled';
@@ -24,7 +24,7 @@ export function withHooks(rl, cb) {
24
24
  };
25
25
  store.handleChange();
26
26
  }
27
- cb(cycle);
27
+ return cb(cycle);
28
28
  });
29
29
  }
30
30
  // Safe getStore utility that'll return the store or throw if undefined.
@@ -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
+ }
@@ -1,10 +1,14 @@
1
1
  import colors from 'yoctocolors-cjs';
2
- import spinners from 'cli-spinners';
2
+ import figures from '@inquirer/figures';
3
3
  export const defaultTheme = {
4
- prefix: colors.green('?'),
4
+ prefix: {
5
+ idle: colors.blue('?'),
6
+ // TODO: use figure
7
+ done: colors.green(figures.tick),
8
+ },
5
9
  spinner: {
6
- interval: spinners.dots.interval,
7
- frames: spinners.dots.frames.map((frame) => colors.yellow(frame)),
10
+ interval: 80,
11
+ frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => colors.yellow(frame)),
8
12
  },
9
13
  style: {
10
14
  answer: colors.cyan,
@@ -2,12 +2,12 @@ import { AsyncResource } from 'node:async_hooks';
2
2
  import { useState } from './use-state.mjs';
3
3
  import { useEffect } from './use-effect.mjs';
4
4
  import { makeTheme } from './make-theme.mjs';
5
- export function usePrefix({ isLoading = false, theme, }) {
5
+ export function usePrefix({ status = 'idle', theme, }) {
6
6
  const [showLoader, setShowLoader] = useState(false);
7
7
  const [tick, setTick] = useState(0);
8
8
  const { prefix, spinner } = makeTheme(theme);
9
9
  useEffect(() => {
10
- if (isLoading) {
10
+ if (status === 'loading') {
11
11
  let tickInterval;
12
12
  let inc = -1;
13
13
  // Delay displaying spinner by 300ms, to avoid flickering
@@ -26,9 +26,11 @@ export function usePrefix({ isLoading = false, theme, }) {
26
26
  else {
27
27
  setShowLoader(false);
28
28
  }
29
- }, [isLoading]);
29
+ }, [status]);
30
30
  if (showLoader) {
31
31
  return spinner.frames[tick];
32
32
  }
33
- return prefix;
33
+ // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
34
+ const iconName = status === 'loading' ? 'idle' : status;
35
+ return typeof prefix === 'string' ? prefix : prefix[iconName];
34
36
  }
@@ -7,7 +7,7 @@ export { useMemo } from './lib/use-memo.mjs';
7
7
  export { useRef } from './lib/use-ref.mjs';
8
8
  export { useKeypress } from './lib/use-keypress.mjs';
9
9
  export { makeTheme } from './lib/make-theme.mjs';
10
- export type { Theme } from './lib/theme.mjs';
10
+ export type { Theme, Status } from './lib/theme.mjs';
11
11
  export { usePagination } from './lib/pagination/use-pagination.mjs';
12
12
  export { createPrompt } from './lib/create-prompt.mjs';
13
13
  export { Separator } from './lib/Separator.mjs';
@@ -6,5 +6,5 @@ export declare class Separator {
6
6
  readonly separator: string;
7
7
  readonly type = "separator";
8
8
  constructor(separator?: string);
9
- static isSeparator(choice: undefined | Separator | Record<string, unknown>): choice is Separator;
9
+ static isSeparator(choice: unknown): choice is Separator;
10
10
  }
@@ -1,3 +1,10 @@
1
+ export declare class AbortPromptError extends Error {
2
+ name: string;
3
+ message: string;
4
+ constructor(options?: {
5
+ cause?: unknown;
6
+ });
7
+ }
1
8
  export declare class CancelPromptError extends Error {
2
9
  name: string;
3
10
  message: string;
@@ -1,5 +1,5 @@
1
1
  import type { InquirerReadline } from '@inquirer/type';
2
- export declare function withHooks(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => void): void;
2
+ export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
3
3
  export declare function readline(): InquirerReadline;
4
4
  export declare function withUpdates<R, T extends (...args: any[]) => R>(fn: T): (...args: Parameters<T>) => R;
5
5
  type SetPointer<Value> = {
@@ -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
+ }
@@ -1,17 +1,151 @@
1
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
+ */
10
+ export type Status = 'loading' | 'idle' | 'done';
2
11
  type DefaultTheme = {
3
- prefix: string;
12
+ /**
13
+ * Prefix to prepend to the message. If a function is provided, it will be
14
+ * called with the current status of the prompt, and the return value will be
15
+ * used as the prefix.
16
+ *
17
+ * @remarks
18
+ * If `status === 'loading'`, this property is ignored and the spinner (styled
19
+ * by the `spinner` property) will be displayed instead.
20
+ *
21
+ * @defaultValue
22
+ * ```ts
23
+ * // import colors from 'yoctocolors-cjs';
24
+ * (status) => status === 'done' ? colors.green('✔') : colors.blue('?')
25
+ * ```
26
+ */
27
+ prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
28
+ /**
29
+ * Configuration for the spinner that is displayed when the prompt is in the
30
+ * `'loading'` state.
31
+ *
32
+ * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
33
+ */
4
34
  spinner: {
35
+ /**
36
+ * The time interval between frames, in milliseconds.
37
+ *
38
+ * @defaultValue
39
+ * ```ts
40
+ * 80
41
+ * ```
42
+ */
5
43
  interval: number;
44
+ /**
45
+ * A list of frames to show for the spinner.
46
+ *
47
+ * @defaultValue
48
+ * ```ts
49
+ * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
50
+ * ```
51
+ */
6
52
  frames: string[];
7
53
  };
54
+ /**
55
+ * Object containing functions to style different parts of the prompt.
56
+ */
8
57
  style: {
58
+ /**
59
+ * Style to apply to the user's answer once it has been submitted.
60
+ *
61
+ * @param text - The user's answer.
62
+ * @returns The styled answer.
63
+ *
64
+ * @defaultValue
65
+ * ```ts
66
+ * // import colors from 'yoctocolors-cjs';
67
+ * (text) => colors.cyan(text)
68
+ * ```
69
+ */
9
70
  answer: (text: string) => string;
10
- message: (text: string) => string;
71
+ /**
72
+ * Style to apply to the message displayed to the user.
73
+ *
74
+ * @param text - The message to style.
75
+ * @param status - The current status of the prompt.
76
+ * @returns The styled message.
77
+ *
78
+ * @defaultValue
79
+ * ```ts
80
+ * // import colors from 'yoctocolors-cjs';
81
+ * (text, status) => colors.bold(text)
82
+ * ```
83
+ */
84
+ message: (text: string, status: Status) => string;
85
+ /**
86
+ * Style to apply to error messages.
87
+ *
88
+ * @param text - The error message.
89
+ * @returns The styled error message.
90
+ *
91
+ * @defaultValue
92
+ * ```ts
93
+ * // import colors from 'yoctocolors-cjs';
94
+ * (text) => colors.red(`> ${text}`)
95
+ * ```
96
+ */
11
97
  error: (text: string) => string;
98
+ /**
99
+ * Style to apply to the default answer when one is provided.
100
+ *
101
+ * @param text - The default answer.
102
+ * @returns The styled default answer.
103
+ *
104
+ * @defaultValue
105
+ * ```ts
106
+ * // import colors from 'yoctocolors-cjs';
107
+ * (text) => colors.dim(`(${text})`)
108
+ * ```
109
+ */
12
110
  defaultAnswer: (text: string) => string;
111
+ /**
112
+ * Style to apply to help text.
113
+ *
114
+ * @param text - The help text.
115
+ * @returns The styled help text.
116
+ *
117
+ * @defaultValue
118
+ * ```ts
119
+ * // import colors from 'yoctocolors-cjs';
120
+ * (text) => colors.dim(text)
121
+ * ```
122
+ */
13
123
  help: (text: string) => string;
124
+ /**
125
+ * Style to apply to highlighted text.
126
+ *
127
+ * @param text - The text to highlight.
128
+ * @returns The highlighted text.
129
+ *
130
+ * @defaultValue
131
+ * ```ts
132
+ * // import colors from 'yoctocolors-cjs';
133
+ * (text) => colors.cyan(text)
134
+ * ```
135
+ */
14
136
  highlight: (text: string) => string;
137
+ /**
138
+ * Style to apply to keyboard keys referred to in help texts.
139
+ *
140
+ * @param text - The key to style.
141
+ * @returns The styled key.
142
+ *
143
+ * @defaultValue
144
+ * ```ts
145
+ * // import colors from 'yoctocolors-cjs';
146
+ * (text) => colors.cyan(colors.bold(`<${text}>`))
147
+ * ```
148
+ */
15
149
  key: (text: string) => string;
16
150
  };
17
151
  };
@@ -1,5 +1,5 @@
1
- import { type Theme } from './theme.mjs';
2
- export declare function usePrefix({ isLoading, theme, }: {
3
- isLoading?: boolean;
1
+ import type { Theme, Status } from './theme.mjs';
2
+ export declare function usePrefix({ status, theme, }: {
3
+ status?: Status;
4
4
  theme?: Theme;
5
5
  }): string;
@@ -1,4 +1,4 @@
1
1
  type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
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 | undefined) => void];
3
+ export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
4
4
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "9.0.10",
3
+ "version": "9.2.0",
4
4
  "engines": {
5
5
  "node": ">=18"
6
6
  },
@@ -58,12 +58,11 @@
58
58
  "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/core/README.md",
59
59
  "dependencies": {
60
60
  "@inquirer/figures": "^1.0.5",
61
- "@inquirer/type": "^1.5.2",
61
+ "@inquirer/type": "^1.5.4",
62
62
  "@types/mute-stream": "^0.0.4",
63
- "@types/node": "^22.1.0",
63
+ "@types/node": "^22.5.5",
64
64
  "@types/wrap-ansi": "^3.0.0",
65
65
  "ansi-escapes": "^4.3.2",
66
- "cli-spinners": "^2.9.2",
67
66
  "cli-width": "^4.1.0",
68
67
  "mute-stream": "^1.0.0",
69
68
  "signal-exit": "^4.1.0",
@@ -72,7 +71,7 @@
72
71
  "yoctocolors-cjs": "^2.1.2"
73
72
  },
74
73
  "devDependencies": {
75
- "@inquirer/testing": "^2.1.31"
74
+ "@inquirer/testing": "^2.1.33"
76
75
  },
77
76
  "scripts": {
78
77
  "tsc": "yarn run tsc:esm && yarn run tsc:cjs",
@@ -96,5 +95,5 @@
96
95
  }
97
96
  },
98
97
  "sideEffects": false,
99
- "gitHead": "273b16eeb96fab346854b9b92257c930d7ca7661"
98
+ "gitHead": "5fe03a4686d349d0d6cf281f86f12a4f7c992ad4"
100
99
  }