@inquirer/core 0.0.30-alpha.0 → 1.0.1

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.
Files changed (34) hide show
  1. package/README.md +11 -11
  2. package/dist/cjs/index.js +158 -0
  3. package/dist/cjs/lib/Paginator.js +53 -0
  4. package/dist/cjs/lib/key.js +27 -0
  5. package/dist/cjs/lib/options.js +19 -0
  6. package/dist/cjs/lib/prefix.js +27 -0
  7. package/dist/cjs/lib/readline.js +60 -0
  8. package/dist/cjs/lib/screen-manager.js +130 -0
  9. package/dist/cjs/lib/utils.js +20 -0
  10. package/dist/cjs/types/index.d.mts +31 -0
  11. package/dist/{lib/key.d.ts → cjs/types/lib/key.d.mts} +1 -1
  12. package/dist/{lib/options.d.ts → cjs/types/lib/options.d.mts} +1 -1
  13. package/dist/{lib/readline.d.ts → cjs/types/lib/readline.d.mts} +1 -1
  14. package/dist/{lib/screen-manager.d.ts → cjs/types/lib/screen-manager.d.mts} +1 -1
  15. package/dist/{index.js → esm/index.mjs} +20 -13
  16. package/dist/{lib/Paginator.js → esm/lib/Paginator.mjs} +3 -15
  17. package/dist/{lib/prefix.js → esm/lib/prefix.mjs} +1 -1
  18. package/dist/{lib/screen-manager.js → esm/lib/screen-manager.mjs} +7 -21
  19. package/dist/{lib/utils.js → esm/lib/utils.mjs} +0 -1
  20. package/dist/{index.d.ts → esm/types/index.d.mts} +7 -7
  21. package/dist/esm/types/lib/Paginator.d.mts +9 -0
  22. package/dist/esm/types/lib/key.d.mts +11 -0
  23. package/dist/esm/types/lib/options.d.mts +2 -0
  24. package/dist/esm/types/lib/prefix.d.mts +1 -0
  25. package/dist/esm/types/lib/readline.d.mts +31 -0
  26. package/dist/esm/types/lib/screen-manager.d.mts +11 -0
  27. package/dist/esm/types/lib/utils.d.mts +8 -0
  28. package/package.json +36 -15
  29. /package/dist/{lib/Paginator.d.ts → cjs/types/lib/Paginator.d.mts} +0 -0
  30. /package/dist/{lib/prefix.d.ts → cjs/types/lib/prefix.d.mts} +0 -0
  31. /package/dist/{lib/utils.d.ts → cjs/types/lib/utils.d.mts} +0 -0
  32. /package/dist/{lib/key.js → esm/lib/key.mjs} +0 -0
  33. /package/dist/{lib/options.js → esm/lib/options.mjs} +0 -0
  34. /package/dist/{lib/readline.js → esm/lib/readline.mjs} +0 -0
package/README.md CHANGED
@@ -62,22 +62,22 @@ const answer = await confirm({ message: 'Do you want to continue?' });
62
62
 
63
63
  See more examples:
64
64
 
65
- - [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/confirm/src/index.ts)
66
- - [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/input/src/index.ts)
67
- - [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/password/src/index.ts)
68
- - [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/editor/src/index.ts)
69
- - [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/select/src/index.ts)
70
- - [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/checkbox/src/index.ts)
71
- - [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/rawlist/src/index.ts)
72
- - [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/expand/src/index.ts)
65
+ - [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/confirm/src/index.mts)
66
+ - [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/input/src/index.mts)
67
+ - [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/password/src/index.mts)
68
+ - [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/editor/src/index.mts)
69
+ - [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/select/src/index.mts)
70
+ - [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/checkbox/src/index.mts)
71
+ - [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/rawlist/src/index.mts)
72
+ - [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/expand/src/index.mts)
73
73
 
74
74
  ## API
75
75
 
76
- ### `createPrompt(config, context)`
76
+ ### `createPrompt(viewFn)`
77
77
 
78
- The `createPrompt` function returns an asynchronous function that returns a promise that'll resolve to the valid answer a user submit. This prompt function takes the prompt configuration as its first argument (this is defined by each prompt), and the context options as a second argument.
78
+ The `createPrompt` function returns an asynchronous function that returns a promise resolving to the valid answer a user submit. This prompt function takes the prompt configuration as its first argument (this is defined by each prompt), and the context options as a second argument.
79
79
 
80
- The context options are:
80
+ The prompt configuration is unique to each prompt. The context options are:
81
81
 
82
82
  | Property | Type | Required | Description |
83
83
  | ----------------- | ----------------------- | -------- | ------------------------------------------------------------ |
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.createPrompt = exports.useRef = exports.useKeypress = exports.useEffect = exports.useState = exports.usePrefix = void 0;
30
+ const node_readline_1 = __importDefault(require("node:readline"));
31
+ const mute_stream_1 = __importDefault(require("mute-stream"));
32
+ const screen_manager_mjs_1 = __importDefault(require("./lib/screen-manager.mjs"));
33
+ const options_mjs_1 = require("./lib/options.mjs");
34
+ var prefix_mjs_1 = require("./lib/prefix.mjs");
35
+ Object.defineProperty(exports, "usePrefix", { enumerable: true, get: function () { return prefix_mjs_1.usePrefix; } });
36
+ __exportStar(require("./lib/key.mjs"), exports);
37
+ __exportStar(require("./lib/Paginator.mjs"), exports);
38
+ const hooks = [];
39
+ const hooksCleanup = [];
40
+ const hooksEffect = [];
41
+ let index = 0;
42
+ let handleChange = () => { };
43
+ let sessionRl;
44
+ const cleanupHook = (index) => {
45
+ const cleanFn = hooksCleanup[index];
46
+ if (typeof cleanFn === 'function') {
47
+ cleanFn();
48
+ }
49
+ };
50
+ function useState(defaultValue) {
51
+ const _idx = index;
52
+ index++;
53
+ if (!(_idx in hooks)) {
54
+ hooks[_idx] = defaultValue;
55
+ }
56
+ return [
57
+ hooks[_idx],
58
+ (newValue) => {
59
+ hooks[_idx] = newValue;
60
+ // Trigger re-render
61
+ handleChange();
62
+ },
63
+ ];
64
+ }
65
+ exports.useState = useState;
66
+ function useEffect(cb, depArray) {
67
+ const _idx = index;
68
+ index++;
69
+ const oldDeps = hooks[_idx];
70
+ let hasChanged = true;
71
+ if (oldDeps) {
72
+ hasChanged = depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
73
+ }
74
+ if (hasChanged) {
75
+ hooksEffect.push(() => {
76
+ cleanupHook(_idx);
77
+ hooksCleanup[_idx] = cb();
78
+ });
79
+ }
80
+ hooks[_idx] = depArray;
81
+ }
82
+ exports.useEffect = useEffect;
83
+ function useKeypress(userHandler) {
84
+ const rl = sessionRl;
85
+ if (!rl) {
86
+ throw new Error('useKeypress must be used within a prompt');
87
+ }
88
+ useEffect(() => {
89
+ const handler = (_input, event) => {
90
+ userHandler(event, rl);
91
+ };
92
+ rl.input.on('keypress', handler);
93
+ return () => {
94
+ rl.input.removeListener('keypress', handler);
95
+ };
96
+ }, [userHandler]);
97
+ }
98
+ exports.useKeypress = useKeypress;
99
+ function useRef(val) {
100
+ return useState({ current: val })[0];
101
+ }
102
+ exports.useRef = useRef;
103
+ function createPrompt(view) {
104
+ const prompt = (config, context) => __awaiter(this, void 0, void 0, function* () {
105
+ var _a, _b;
106
+ // Default `input` to stdin
107
+ const input = (_a = context === null || context === void 0 ? void 0 : context.input) !== null && _a !== void 0 ? _a : process.stdin;
108
+ // Add mute capabilities to the output
109
+ const output = new mute_stream_1.default();
110
+ output.pipe((_b = context === null || context === void 0 ? void 0 : context.output) !== null && _b !== void 0 ? _b : process.stdout);
111
+ const rl = node_readline_1.default.createInterface({
112
+ terminal: true,
113
+ input,
114
+ output,
115
+ });
116
+ const screen = new screen_manager_mjs_1.default(rl);
117
+ // Set our state before starting the prompt.
118
+ hooks.length = 0;
119
+ sessionRl = rl;
120
+ // TODO: we should display a loader while we get the default options.
121
+ const resolvedConfig = yield (0, options_mjs_1.getPromptConfig)(config);
122
+ return new Promise((resolve) => {
123
+ const done = (value) => {
124
+ let len = hooksCleanup.length;
125
+ while (len--) {
126
+ cleanupHook(len);
127
+ }
128
+ if (context === null || context === void 0 ? void 0 : context.clearPromptOnDone) {
129
+ screen.clean();
130
+ }
131
+ else {
132
+ screen.clearContent();
133
+ }
134
+ screen.done();
135
+ // Reset hooks state
136
+ index = 0;
137
+ hooks.length = 0;
138
+ sessionRl = undefined;
139
+ // Finally we resolve our promise
140
+ resolve(value);
141
+ };
142
+ const workLoop = () => {
143
+ index = 0;
144
+ hooksEffect.length = 0;
145
+ handleChange = () => workLoop();
146
+ const nextView = view(resolvedConfig, done);
147
+ for (const effect of hooksEffect) {
148
+ effect();
149
+ }
150
+ const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
151
+ screen.render(content, bottomContent);
152
+ };
153
+ workLoop();
154
+ });
155
+ });
156
+ return prompt;
157
+ }
158
+ exports.createPrompt = createPrompt;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Paginator = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const cli_width_1 = __importDefault(require("cli-width"));
9
+ const utils_mjs_1 = require("./utils.mjs");
10
+ /**
11
+ * The paginator keeps track of a pointer index in a list and returns
12
+ * a subset of the choices if the list is too long.
13
+ */
14
+ class Paginator {
15
+ constructor() {
16
+ Object.defineProperty(this, "pointer", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: 0
21
+ });
22
+ Object.defineProperty(this, "lastIndex", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: 0
27
+ });
28
+ }
29
+ paginate(output, active, pageSize = 7) {
30
+ const middleOfList = Math.floor(pageSize / 2);
31
+ // TODO: I've remove the dependency on readline here. But we should refactor the
32
+ // paginator to also rely on hook.
33
+ const width = (0, cli_width_1.default)({ defaultWidth: 80, output: process.stdout });
34
+ const lines = (0, utils_mjs_1.breakLines)(output, width).split('\n');
35
+ // Make sure there's enough lines to paginate
36
+ if (lines.length <= pageSize) {
37
+ return output;
38
+ }
39
+ // Move the pointer only when the user go down and limit it to the middle of the list
40
+ if (this.pointer < middleOfList &&
41
+ this.lastIndex < active &&
42
+ active - this.lastIndex < pageSize) {
43
+ this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex);
44
+ }
45
+ this.lastIndex = active;
46
+ // Duplicate the lines so it give an infinite list look
47
+ const infinite = [lines, lines, lines].flat();
48
+ const topIndex = Math.max(0, active + lines.length - this.pointer);
49
+ const section = infinite.splice(topIndex, pageSize).join('\n');
50
+ return section + '\n' + chalk_1.default.dim('(Move up and down to reveal more choices)');
51
+ }
52
+ }
53
+ exports.Paginator = Paginator;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isEnterKey = exports.isNumberKey = exports.isBackspaceKey = exports.isSpaceKey = exports.isDownKey = exports.isUpKey = void 0;
4
+ const isUpKey = (key) =>
5
+ // The up key
6
+ key.name === 'up' ||
7
+ // Vim keybinding
8
+ key.name === 'k' ||
9
+ // Emacs keybinding
10
+ (key.ctrl && key.name === 'p');
11
+ exports.isUpKey = isUpKey;
12
+ const isDownKey = (key) =>
13
+ // The down key
14
+ key.name === 'down' ||
15
+ // Vim keybinding
16
+ key.name === 'j' ||
17
+ // Emacs keybinding
18
+ (key.ctrl && key.name === 'n');
19
+ exports.isDownKey = isDownKey;
20
+ const isSpaceKey = (key) => key.name === 'space';
21
+ exports.isSpaceKey = isSpaceKey;
22
+ const isBackspaceKey = (key) => key.name === 'backspace';
23
+ exports.isBackspaceKey = isBackspaceKey;
24
+ const isNumberKey = (key) => '123456789'.includes(key.name);
25
+ exports.isNumberKey = isNumberKey;
26
+ const isEnterKey = (key) => key.name === 'enter' || key.name === 'return';
27
+ exports.isEnterKey = isEnterKey;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getPromptConfig = void 0;
13
+ function getPromptConfig(option) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ const message = typeof option.message === 'function' ? option.message() : option.message;
16
+ return Object.assign(Object.assign({ validate: () => true }, option), { message: yield message });
17
+ });
18
+ }
19
+ exports.getPromptConfig = getPromptConfig;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.usePrefix = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const cli_spinners_1 = __importDefault(require("cli-spinners"));
9
+ const index_mjs_1 = require("../index.mjs");
10
+ const spinner = cli_spinners_1.default.dots;
11
+ function usePrefix(isLoading = false) {
12
+ const [tick, setTick] = (0, index_mjs_1.useState)(0);
13
+ (0, index_mjs_1.useEffect)(() => {
14
+ if (isLoading) {
15
+ const timeout = setTimeout(() => {
16
+ setTick(tick + 1);
17
+ }, spinner.interval);
18
+ return () => clearTimeout(timeout);
19
+ }
20
+ }, [isLoading, tick]);
21
+ if (isLoading) {
22
+ const frame = tick % spinner.frames.length;
23
+ return chalk_1.default.yellow(spinner.frames[frame]);
24
+ }
25
+ return chalk_1.default.green('?');
26
+ }
27
+ exports.usePrefix = usePrefix;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.clearLine = exports.down = exports.up = exports.right = exports.left = void 0;
7
+ const ansi_escapes_1 = __importDefault(require("ansi-escapes"));
8
+ /**
9
+ * Move cursor left by `x`
10
+ * @param {Readline} rl - Readline instance
11
+ * @param {Number} x - How far to go left (default to 1)
12
+ */
13
+ function left(rl, x) {
14
+ if (x > 0) {
15
+ rl.output.write(ansi_escapes_1.default.cursorBackward(x));
16
+ }
17
+ }
18
+ exports.left = left;
19
+ /**
20
+ * Move cursor right by `x`
21
+ * @param {Readline} rl - Readline instance
22
+ * @param {Number} x - How far to go left (default to 1)
23
+ */
24
+ function right(rl, x) {
25
+ if (x > 0) {
26
+ rl.output.write(ansi_escapes_1.default.cursorForward(x));
27
+ }
28
+ }
29
+ exports.right = right;
30
+ /**
31
+ * Move cursor up by `x`
32
+ * @param {Readline} rl - Readline instance
33
+ * @param {Number} x - How far to go up (default to 1)
34
+ */
35
+ function up(rl, x) {
36
+ if (x > 0) {
37
+ rl.output.write(ansi_escapes_1.default.cursorUp(x));
38
+ }
39
+ }
40
+ exports.up = up;
41
+ /**
42
+ * Move cursor down by `x`
43
+ * @param {Readline} rl - Readline instance
44
+ * @param {Number} x - How far to go down (default to 1)
45
+ */
46
+ function down(rl, x) {
47
+ if (x > 0) {
48
+ rl.output.write(ansi_escapes_1.default.cursorDown(x));
49
+ }
50
+ }
51
+ exports.down = down;
52
+ /**
53
+ * Clear current line
54
+ * @param {Readline} rl - Readline instance
55
+ * @param {Number} len - number of line to delete
56
+ */
57
+ function clearLine(rl, len) {
58
+ rl.output.write(ansi_escapes_1.default.eraseLines(len));
59
+ }
60
+ exports.clearLine = clearLine;
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const cli_width_1 = __importDefault(require("cli-width"));
30
+ const strip_ansi_1 = __importDefault(require("strip-ansi"));
31
+ const string_width_1 = __importDefault(require("string-width"));
32
+ const ansi_escapes_1 = __importDefault(require("ansi-escapes"));
33
+ const util = __importStar(require("./readline.mjs"));
34
+ const utils_mjs_1 = require("./utils.mjs");
35
+ const height = (content) => content.split('\n').length;
36
+ const lastLine = (content) => { var _a; return (_a = content.split('\n').pop()) !== null && _a !== void 0 ? _a : ''; };
37
+ class ScreenManager {
38
+ constructor(rl) {
39
+ Object.defineProperty(this, "rl", {
40
+ enumerable: true,
41
+ configurable: true,
42
+ writable: true,
43
+ value: rl
44
+ });
45
+ // These variables are keeping information to allow correct prompt re-rendering
46
+ Object.defineProperty(this, "height", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: 0
51
+ });
52
+ Object.defineProperty(this, "extraLinesUnderPrompt", {
53
+ enumerable: true,
54
+ configurable: true,
55
+ writable: true,
56
+ value: 0
57
+ });
58
+ this.rl = rl;
59
+ }
60
+ render(content, bottomContent = '') {
61
+ this.clean();
62
+ this.rl.output.unmute();
63
+ /**
64
+ * Write message to screen and setPrompt to control backspace
65
+ */
66
+ const promptLine = lastLine(content);
67
+ const rawPromptLine = (0, strip_ansi_1.default)(promptLine);
68
+ // Remove the rl.line from our prompt. We can't rely on the content of
69
+ // rl.line (mainly because of the password prompt), so just rely on it's
70
+ // length.
71
+ let prompt = rawPromptLine;
72
+ if (this.rl.line.length) {
73
+ prompt = prompt.slice(0, -this.rl.line.length);
74
+ }
75
+ this.rl.setPrompt(prompt);
76
+ // SetPrompt will change cursor position, now we can get correct value
77
+ const cursorPos = this.rl._getCursorPos();
78
+ const width = (0, cli_width_1.default)({ defaultWidth: 80, output: this.rl.output });
79
+ content = (0, utils_mjs_1.breakLines)(content, width);
80
+ bottomContent = (0, utils_mjs_1.breakLines)(bottomContent, width);
81
+ // Manually insert an extra line if we're at the end of the line.
82
+ // This prevent the cursor from appearing at the beginning of the
83
+ // current line.
84
+ if (rawPromptLine.length % width === 0) {
85
+ content += '\n';
86
+ }
87
+ const fullContent = content + (bottomContent ? '\n' + bottomContent : '');
88
+ this.rl.output.write(fullContent);
89
+ /**
90
+ * Re-adjust the cursor at the correct position.
91
+ */
92
+ // We need to consider parts of the prompt under the cursor as part of the bottom
93
+ // content in order to correctly cleanup and re-render.
94
+ const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - cursorPos.rows;
95
+ const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
96
+ // Return cursor to the input position (on top of the bottomContent)
97
+ util.up(this.rl, bottomContentHeight);
98
+ // Move cursor at the start of the line, then return to the initial left offset.
99
+ util.left(this.rl, (0, string_width_1.default)(lastLine(fullContent)));
100
+ util.right(this.rl, cursorPos.cols);
101
+ /**
102
+ * Set up state for next re-rendering
103
+ */
104
+ this.extraLinesUnderPrompt = bottomContentHeight;
105
+ this.height = height(fullContent);
106
+ this.rl.output.mute();
107
+ }
108
+ clean() {
109
+ this.rl.output.unmute();
110
+ util.down(this.rl, this.extraLinesUnderPrompt);
111
+ util.clearLine(this.rl, this.height);
112
+ this.extraLinesUnderPrompt = 0;
113
+ this.rl.output.mute();
114
+ }
115
+ clearContent() {
116
+ this.rl.output.unmute();
117
+ // Reset the cursor at the end of the previously displayed content
118
+ util.down(this.rl, this.extraLinesUnderPrompt);
119
+ this.rl.output.write('\n');
120
+ this.rl.output.mute();
121
+ }
122
+ done() {
123
+ this.rl.setPrompt('');
124
+ this.rl.output.unmute();
125
+ this.rl.output.write(ansi_escapes_1.default.cursorShow);
126
+ this.rl.output.end();
127
+ this.rl.close();
128
+ }
129
+ }
130
+ exports.default = ScreenManager;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.breakLines = void 0;
7
+ const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
8
+ /**
9
+ * Force line returns at specific width. This function is ANSI code friendly and it'll
10
+ * ignore invisible codes during width calculation.
11
+ * @param {string} content
12
+ * @param {number} width
13
+ * @return {string}
14
+ */
15
+ const breakLines = (content, width) => content
16
+ .split('\n')
17
+ .map((line) => (0, wrap_ansi_1.default)(line, width, { trim: false, hard: true }).split('\n'))
18
+ .flat()
19
+ .join('\n');
20
+ exports.breakLines = breakLines;
@@ -0,0 +1,31 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import readline from 'node:readline';
4
+ import type { Prompt } from '@inquirer/type';
5
+ import MuteStream from 'mute-stream';
6
+ export { usePrefix } from './lib/prefix.mjs';
7
+ export * from './lib/key.mjs';
8
+ export * from './lib/Paginator.mjs';
9
+ export type InquirerReadline = readline.ReadLine & {
10
+ output: MuteStream;
11
+ input: NodeJS.ReadableStream;
12
+ };
13
+ export type KeypressEvent = {
14
+ name: string;
15
+ ctrl: boolean;
16
+ };
17
+ export declare function useState<Value>(defaultValue: Value): [Value, (newValue: Value) => void];
18
+ export declare function useEffect(cb: () => void | (() => void), depArray: unknown[]): void;
19
+ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
20
+ export declare function useRef<Value>(val: Value): {
21
+ current: Value;
22
+ };
23
+ export type AsyncPromptConfig = {
24
+ message: string | Promise<string> | (() => Promise<string>);
25
+ validate?: (value: string) => boolean | string | Promise<string | boolean>;
26
+ };
27
+ export type ResolvedPromptConfig = {
28
+ message: string;
29
+ validate: (value: string) => boolean | string | Promise<string | boolean>;
30
+ };
31
+ export declare function createPrompt<Value, Config extends AsyncPromptConfig>(view: (config: Config & ResolvedPromptConfig, done: (value: Value) => void) => string | [string, string | undefined]): Prompt<Value, Config>;
@@ -1,4 +1,4 @@
1
- declare type KeypressEvent = {
1
+ type KeypressEvent = {
2
2
  name: string;
3
3
  ctrl: boolean;
4
4
  };
@@ -1,2 +1,2 @@
1
- import type { AsyncPromptConfig, ResolvedPromptConfig } from '../index.js';
1
+ import type { AsyncPromptConfig, ResolvedPromptConfig } from '../index.mjs';
2
2
  export declare function getPromptConfig<In extends AsyncPromptConfig>(option: In): Promise<In & ResolvedPromptConfig>;
@@ -1,4 +1,4 @@
1
- import type { InquirerReadline } from '../index.js';
1
+ import type { InquirerReadline } from '../index.mjs';
2
2
  /**
3
3
  * Move cursor left by `x`
4
4
  * @param {Readline} rl - Readline instance
@@ -1,4 +1,4 @@
1
- import { InquirerReadline } from '../index.js';
1
+ import { InquirerReadline } from '../index.mjs';
2
2
  export default class ScreenManager {
3
3
  private readonly rl;
4
4
  private height;
@@ -1,15 +1,16 @@
1
1
  import readline from 'node:readline';
2
2
  import MuteStream from 'mute-stream';
3
- import ScreenManager from './lib/screen-manager.js';
4
- import { getPromptConfig } from './lib/options.js';
5
- export { usePrefix } from './lib/prefix.js';
6
- export * from './lib/key.js';
7
- export * from './lib/Paginator.js';
8
- let sessionRl;
9
- let hooks = [];
3
+ import ScreenManager from './lib/screen-manager.mjs';
4
+ import { getPromptConfig } from './lib/options.mjs';
5
+ export { usePrefix } from './lib/prefix.mjs';
6
+ export * from './lib/key.mjs';
7
+ export * from './lib/Paginator.mjs';
8
+ const hooks = [];
10
9
  const hooksCleanup = [];
10
+ const hooksEffect = [];
11
11
  let index = 0;
12
12
  let handleChange = () => { };
13
+ let sessionRl;
13
14
  const cleanupHook = (index) => {
14
15
  const cleanFn = hooksCleanup[index];
15
16
  if (typeof cleanFn === 'function') {
@@ -40,8 +41,10 @@ export function useEffect(cb, depArray) {
40
41
  hasChanged = depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
41
42
  }
42
43
  if (hasChanged) {
43
- cleanupHook(_idx);
44
- hooksCleanup[_idx] = cb();
44
+ hooksEffect.push(() => {
45
+ cleanupHook(_idx);
46
+ hooksCleanup[_idx] = cb();
47
+ });
45
48
  }
46
49
  hooks[_idx] = depArray;
47
50
  }
@@ -76,6 +79,9 @@ export function createPrompt(view) {
76
79
  output,
77
80
  });
78
81
  const screen = new ScreenManager(rl);
82
+ // Set our state before starting the prompt.
83
+ hooks.length = 0;
84
+ sessionRl = rl;
79
85
  // TODO: we should display a loader while we get the default options.
80
86
  const resolvedConfig = await getPromptConfig(config);
81
87
  return new Promise((resolve) => {
@@ -92,19 +98,20 @@ export function createPrompt(view) {
92
98
  }
93
99
  screen.done();
94
100
  // Reset hooks state
95
- hooks = [];
96
101
  index = 0;
102
+ hooks.length = 0;
97
103
  sessionRl = undefined;
98
104
  // Finally we resolve our promise
99
105
  resolve(value);
100
106
  };
101
- index = 0;
102
- hooks = [];
103
107
  const workLoop = () => {
104
- sessionRl = rl;
105
108
  index = 0;
109
+ hooksEffect.length = 0;
106
110
  handleChange = () => workLoop();
107
111
  const nextView = view(resolvedConfig, done);
112
+ for (const effect of hooksEffect) {
113
+ effect();
114
+ }
108
115
  const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
109
116
  screen.render(content, bottomContent);
110
117
  };
@@ -1,25 +1,13 @@
1
1
  import chalk from 'chalk';
2
2
  import cliWidth from 'cli-width';
3
- import { breakLines } from './utils.js';
3
+ import { breakLines } from './utils.mjs';
4
4
  /**
5
5
  * The paginator keeps track of a pointer index in a list and returns
6
6
  * a subset of the choices if the list is too long.
7
7
  */
8
8
  export class Paginator {
9
- constructor() {
10
- Object.defineProperty(this, "pointer", {
11
- enumerable: true,
12
- configurable: true,
13
- writable: true,
14
- value: 0
15
- });
16
- Object.defineProperty(this, "lastIndex", {
17
- enumerable: true,
18
- configurable: true,
19
- writable: true,
20
- value: 0
21
- });
22
- }
9
+ pointer = 0;
10
+ lastIndex = 0;
23
11
  paginate(output, active, pageSize = 7) {
24
12
  const middleOfList = Math.floor(pageSize / 2);
25
13
  // TODO: I've remove the dependency on readline here. But we should refactor the
@@ -1,6 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import spinners from 'cli-spinners';
3
- import { useState, useEffect } from '../index.js';
3
+ import { useState, useEffect } from '../index.mjs';
4
4
  const spinner = spinners.dots;
5
5
  export function usePrefix(isLoading = false) {
6
6
  const [tick, setTick] = useState(0);
@@ -2,31 +2,17 @@ import cliWidth from 'cli-width';
2
2
  import stripAnsi from 'strip-ansi';
3
3
  import stringWidth from 'string-width';
4
4
  import ansiEscapes from 'ansi-escapes';
5
- import * as util from './readline.js';
6
- import { breakLines } from './utils.js';
5
+ import * as util from './readline.mjs';
6
+ import { breakLines } from './utils.mjs';
7
7
  const height = (content) => content.split('\n').length;
8
8
  const lastLine = (content) => content.split('\n').pop() ?? '';
9
9
  export default class ScreenManager {
10
+ rl;
11
+ // These variables are keeping information to allow correct prompt re-rendering
12
+ height = 0;
13
+ extraLinesUnderPrompt = 0;
10
14
  constructor(rl) {
11
- Object.defineProperty(this, "rl", {
12
- enumerable: true,
13
- configurable: true,
14
- writable: true,
15
- value: rl
16
- });
17
- // These variables are keeping information to allow correct prompt re-rendering
18
- Object.defineProperty(this, "height", {
19
- enumerable: true,
20
- configurable: true,
21
- writable: true,
22
- value: 0
23
- });
24
- Object.defineProperty(this, "extraLinesUnderPrompt", {
25
- enumerable: true,
26
- configurable: true,
27
- writable: true,
28
- value: 0
29
- });
15
+ this.rl = rl;
30
16
  this.rl = rl;
31
17
  }
32
18
  render(content, bottomContent = '') {
@@ -8,7 +8,6 @@ import wrapAnsi from 'wrap-ansi';
8
8
  */
9
9
  export const breakLines = (content, width) => content
10
10
  .split('\n')
11
- // @ts-expect-error broken type check from library
12
11
  .map((line) => wrapAnsi(line, width, { trim: false, hard: true }).split('\n'))
13
12
  .flat()
14
13
  .join('\n');
@@ -3,14 +3,14 @@
3
3
  import readline from 'node:readline';
4
4
  import type { Prompt } from '@inquirer/type';
5
5
  import MuteStream from 'mute-stream';
6
- export { usePrefix } from './lib/prefix.js';
7
- export * from './lib/key.js';
8
- export * from './lib/Paginator.js';
9
- export declare type InquirerReadline = readline.ReadLine & {
6
+ export { usePrefix } from './lib/prefix.mjs';
7
+ export * from './lib/key.mjs';
8
+ export * from './lib/Paginator.mjs';
9
+ export type InquirerReadline = readline.ReadLine & {
10
10
  output: MuteStream;
11
11
  input: NodeJS.ReadableStream;
12
12
  };
13
- export declare type KeypressEvent = {
13
+ export type KeypressEvent = {
14
14
  name: string;
15
15
  ctrl: boolean;
16
16
  };
@@ -20,11 +20,11 @@ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: Inqu
20
20
  export declare function useRef<Value>(val: Value): {
21
21
  current: Value;
22
22
  };
23
- export declare type AsyncPromptConfig = {
23
+ export type AsyncPromptConfig = {
24
24
  message: string | Promise<string> | (() => Promise<string>);
25
25
  validate?: (value: string) => boolean | string | Promise<string | boolean>;
26
26
  };
27
- export declare type ResolvedPromptConfig = {
27
+ export type ResolvedPromptConfig = {
28
28
  message: string;
29
29
  validate: (value: string) => boolean | string | Promise<string | boolean>;
30
30
  };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The paginator keeps track of a pointer index in a list and returns
3
+ * a subset of the choices if the list is too long.
4
+ */
5
+ export declare class Paginator {
6
+ pointer: number;
7
+ lastIndex: number;
8
+ paginate(output: string, active: number, pageSize?: number): string;
9
+ }
@@ -0,0 +1,11 @@
1
+ type KeypressEvent = {
2
+ name: string;
3
+ ctrl: boolean;
4
+ };
5
+ export declare const isUpKey: (key: KeypressEvent) => boolean;
6
+ export declare const isDownKey: (key: KeypressEvent) => boolean;
7
+ export declare const isSpaceKey: (key: KeypressEvent) => boolean;
8
+ export declare const isBackspaceKey: (key: KeypressEvent) => boolean;
9
+ export declare const isNumberKey: (key: KeypressEvent) => boolean;
10
+ export declare const isEnterKey: (key: KeypressEvent) => boolean;
11
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { AsyncPromptConfig, ResolvedPromptConfig } from '../index.mjs';
2
+ export declare function getPromptConfig<In extends AsyncPromptConfig>(option: In): Promise<In & ResolvedPromptConfig>;
@@ -0,0 +1 @@
1
+ export declare function usePrefix(isLoading?: boolean): string;
@@ -0,0 +1,31 @@
1
+ import type { InquirerReadline } from '../index.mjs';
2
+ /**
3
+ * Move cursor left by `x`
4
+ * @param {Readline} rl - Readline instance
5
+ * @param {Number} x - How far to go left (default to 1)
6
+ */
7
+ export declare function left(rl: InquirerReadline, x: number): void;
8
+ /**
9
+ * Move cursor right by `x`
10
+ * @param {Readline} rl - Readline instance
11
+ * @param {Number} x - How far to go left (default to 1)
12
+ */
13
+ export declare function right(rl: InquirerReadline, x: number): void;
14
+ /**
15
+ * Move cursor up by `x`
16
+ * @param {Readline} rl - Readline instance
17
+ * @param {Number} x - How far to go up (default to 1)
18
+ */
19
+ export declare function up(rl: InquirerReadline, x: number): void;
20
+ /**
21
+ * Move cursor down by `x`
22
+ * @param {Readline} rl - Readline instance
23
+ * @param {Number} x - How far to go down (default to 1)
24
+ */
25
+ export declare function down(rl: InquirerReadline, x: number): void;
26
+ /**
27
+ * Clear current line
28
+ * @param {Readline} rl - Readline instance
29
+ * @param {Number} len - number of line to delete
30
+ */
31
+ export declare function clearLine(rl: InquirerReadline, len: number): void;
@@ -0,0 +1,11 @@
1
+ import { InquirerReadline } from '../index.mjs';
2
+ export default class ScreenManager {
3
+ private readonly rl;
4
+ private height;
5
+ private extraLinesUnderPrompt;
6
+ constructor(rl: InquirerReadline);
7
+ render(content: string, bottomContent?: string): void;
8
+ clean(): void;
9
+ clearContent(): void;
10
+ done(): void;
11
+ }
@@ -0,0 +1,8 @@
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 const breakLines: (content: string, width: number) => string;
package/package.json CHANGED
@@ -1,21 +1,25 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "type": "module",
4
- "version": "0.0.30-alpha.0",
3
+ "version": "1.0.1",
4
+ "engines": {
5
+ "node": ">=14.18.0"
6
+ },
5
7
  "description": "Core Inquirer prompt API",
6
- "main": "dist/index.js",
7
- "typings": "dist/index.d.ts",
8
+ "main": "./dist/cjs/index.js",
9
+ "typings": "./dist/cjs/types/index.d.mts",
8
10
  "files": [
9
- "dist/"
11
+ "dist/**/*"
10
12
  ],
11
- "repository": "SBoudrias/Inquirer.js",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/SBoudrias/Inquirer.js.git"
16
+ },
12
17
  "keywords": [
13
18
  "answer",
14
19
  "answers",
15
20
  "ask",
16
21
  "base",
17
22
  "cli",
18
- "cli",
19
23
  "command",
20
24
  "command-line",
21
25
  "confirm",
@@ -49,30 +53,47 @@
49
53
  "yo",
50
54
  "zsh"
51
55
  ],
52
- "author": "Simon Boudrias",
56
+ "author": "Simon Boudrias <admin@simonboudrias.com>",
53
57
  "license": "MIT",
54
58
  "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/master/packages/core/README.md",
55
59
  "dependencies": {
56
- "@inquirer/type": "^0.0.4-alpha.0",
60
+ "@inquirer/type": "^1.0.0",
57
61
  "ansi-escapes": "^6.0.0",
58
- "chalk": "^5.1.2",
62
+ "chalk": "^5.2.0",
59
63
  "cli-spinners": "^2.7.0",
60
64
  "cli-width": "^4.0.0",
61
65
  "lodash": "^4.17.21",
62
- "mute-stream": "^0.0.8",
66
+ "mute-stream": "^1.0.0",
63
67
  "run-async": "^2.3.0",
64
68
  "string-width": "^5.1.2",
65
69
  "strip-ansi": "^7.0.1",
66
- "wrap-ansi": "^8.0.1"
70
+ "wrap-ansi": "^8.1.0"
67
71
  },
68
72
  "devDependencies": {
69
- "@inquirer/testing": "^0.0.5-alpha.0"
73
+ "@inquirer/testing": "^1.0.0",
74
+ "@jest/globals": "^29.5.0"
70
75
  },
71
76
  "scripts": {
72
- "tsc": "tsc"
77
+ "tsc": "yarn run clean && yarn run tsc:esm && yarn run tsc:cjs",
78
+ "clean": "rm -rf dist",
79
+ "tsc:esm": "tsc -p ./tsconfig.esm.json",
80
+ "tsc:cjs": "tsc -p ./tsconfig.cjs.json && yarn run fix-ext",
81
+ "fix-ext": "ts-node ../../tools/rename-ext.ts"
73
82
  },
74
83
  "publishConfig": {
75
84
  "access": "public"
76
85
  },
77
- "gitHead": "f532af8be2d622caa5e54adf4c084d588c9ffad6"
86
+ "exports": {
87
+ ".": {
88
+ "import": {
89
+ "types": "./dist/esm/types/index.d.mts",
90
+ "default": "./dist/esm/index.mjs"
91
+ },
92
+ "require": {
93
+ "types": "./dist/cjs/types/index.d.mts",
94
+ "default": "./dist/cjs/index.js"
95
+ }
96
+ }
97
+ },
98
+ "gitHead": "e93c4cb14f0c35ebd1efb065776b90f48899b075"
78
99
  }
File without changes
File without changes
File without changes