@inquirer/core 0.0.20-alpha.0 → 0.0.21-alpha.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/index.js DELETED
@@ -1,217 +0,0 @@
1
- const readline = require('readline');
2
- const chalk = require('chalk');
3
- const MuteStream = require('mute-stream');
4
- const runAsync = require('run-async');
5
- const spinner = require('cli-spinners').dots;
6
- const ScreenManager = require('./lib/screen-manager');
7
-
8
- const defaultState = {
9
- validate: () => true,
10
- filter: (val) => val,
11
- transformer: (val) => val,
12
- };
13
-
14
- const defaultMapStateToValue = (state) => {
15
- if (!state.value) {
16
- return state.default;
17
- }
18
-
19
- return state.value;
20
- };
21
-
22
- const defaultOnLine = (state, { submit }) => submit();
23
-
24
- class StateManager {
25
- constructor(configFactory, initialState, render) {
26
- this.initialState = initialState;
27
- this.render = render;
28
- this.currentState = {
29
- loadingIncrement: 0,
30
- value: '',
31
- status: 'idle',
32
- };
33
-
34
- // Default `input` to stdin
35
- const input = process.stdin;
36
-
37
- // Add mute capabilities to the output
38
- const output = new MuteStream();
39
- output.pipe(process.stdout);
40
-
41
- this.rl = readline.createInterface({
42
- terminal: true,
43
- input,
44
- output,
45
- });
46
- this.screen = new ScreenManager(this.rl);
47
-
48
- let config = configFactory;
49
- if (typeof configFactory === 'function') {
50
- config = configFactory(this.rl);
51
- }
52
-
53
- this.config = config;
54
-
55
- this.onKeypress = this.onKeypress.bind(this);
56
- this.onSubmit = this.onSubmit.bind(this);
57
- this.startLoading = this.startLoading.bind(this);
58
- this.onLoaderTick = this.onLoaderTick.bind(this);
59
- this.setState = this.setState.bind(this);
60
- this.handleLineEvent = this.handleLineEvent.bind(this);
61
- }
62
-
63
- async execute(cb) {
64
- let { message } = this.getState();
65
- this.cb = cb;
66
-
67
- // Load asynchronous properties
68
- const showLoader = setTimeout(this.startLoading, 500);
69
- if (typeof message === 'function') {
70
- message = await runAsync(message)();
71
- }
72
-
73
- this.setState({ message, status: 'idle' });
74
-
75
- // Disable the loader if it didn't launch
76
- clearTimeout(showLoader);
77
-
78
- // Setup event listeners once we're done fetching the configs
79
- this.rl.input.on('keypress', this.onKeypress);
80
- this.rl.on('line', this.handleLineEvent);
81
- }
82
-
83
- onKeypress(value, key) {
84
- const { onKeypress } = this.config;
85
- // Ignore enter keypress. The "line" event is handling those.
86
- if (key.name === 'enter' || key.name === 'return') {
87
- return;
88
- }
89
-
90
- this.setState({ value: this.rl.line, error: null });
91
- if (onKeypress) {
92
- onKeypress(this.rl.line, key, this.getState(), this.setState);
93
- }
94
- }
95
-
96
- startLoading() {
97
- this.setState({ loadingIncrement: 0, status: 'loading' });
98
- setTimeout(this.onLoaderTick, spinner.interval);
99
- }
100
-
101
- onLoaderTick() {
102
- const { status, loadingIncrement } = this.getState();
103
- if (status === 'loading') {
104
- this.setState({ loadingIncrement: loadingIncrement + 1 });
105
- setTimeout(this.onLoaderTick, spinner.interval);
106
- }
107
- }
108
-
109
- handleLineEvent() {
110
- const { onLine = defaultOnLine } = this.config;
111
- onLine(this.getState(), {
112
- submit: this.onSubmit,
113
- setState: this.setState,
114
- });
115
- }
116
-
117
- async onSubmit() {
118
- const state = this.getState();
119
- const { validate, filter } = state;
120
- const { validate: configValidate = () => true } = this.config;
121
-
122
- const { mapStateToValue = defaultMapStateToValue } = this.config;
123
- const value = mapStateToValue(state);
124
-
125
- const showLoader = setTimeout(this.startLoading, 500);
126
- this.rl.pause();
127
- try {
128
- const filteredValue = await runAsync(filter)(value);
129
- let isValid = configValidate(value, state);
130
- if (isValid === true) {
131
- isValid = await runAsync(validate)(filteredValue);
132
- }
133
-
134
- if (isValid === true) {
135
- this.onDone(filteredValue);
136
- clearTimeout(showLoader);
137
- return;
138
- }
139
-
140
- this.onError(isValid);
141
- } catch (err) {
142
- this.onError(err.message + '\n' + err.stack);
143
- }
144
-
145
- clearTimeout(showLoader);
146
- this.rl.resume();
147
- }
148
-
149
- onError(error) {
150
- this.setState({
151
- status: 'idle',
152
- error: error || 'You must provide a valid value',
153
- });
154
- }
155
-
156
- onDone(value) {
157
- this.setState({ status: 'done' });
158
- this.rl.input.removeListener('keypress', this.onKeypress);
159
- this.rl.removeListener('line', this.handleLineEvent);
160
- this.screen.done();
161
- this.cb(value);
162
- }
163
-
164
- setState(partialState) {
165
- this.currentState = { ...this.currentState, ...partialState };
166
- this.onChange(this.getState());
167
- }
168
-
169
- getState() {
170
- return { ...defaultState, ...this.initialState, ...this.currentState };
171
- }
172
-
173
- getPrefix() {
174
- const { status, loadingIncrement } = this.getState();
175
- let prefix = chalk.green('?');
176
- if (status === 'loading') {
177
- const frame = loadingIncrement % spinner.frames.length;
178
- prefix = chalk.yellow(spinner.frames[frame]);
179
- }
180
-
181
- return prefix;
182
- }
183
-
184
- onChange(state) {
185
- const { status, message, value, transformer } = this.getState();
186
-
187
- let error;
188
- if (state.error) {
189
- error = `${chalk.red('>>')} ${state.error}`;
190
- }
191
-
192
- const renderState = {
193
- prefix: this.getPrefix(),
194
- ...state,
195
- // Only pass message down if it's a string. Otherwise we're still in init state
196
- message: typeof message === 'function' ? 'Loading...' : message,
197
- value: transformer(value, { isFinal: status === 'done' }),
198
- validate: undefined,
199
- filter: undefined,
200
- transformer: undefined,
201
- };
202
- this.screen.render(this.render(renderState, this.config), error);
203
- }
204
- }
205
-
206
- exports.createPrompt = (config, render) => {
207
- const run = (initialState) =>
208
- new Promise((resolve) => {
209
- const prompt = new StateManager(config, initialState, render);
210
- prompt.execute(resolve);
211
- });
212
-
213
- run.render = render;
214
- run.config = config;
215
-
216
- return run;
217
- };
package/lib/key.js DELETED
@@ -1,13 +0,0 @@
1
- exports.isUpKey = (key) =>
2
- key.name === 'up' || key.name === 'k' || (key.name === 'p' && key.ctrl);
3
-
4
- exports.isDownKey = (key) =>
5
- key.name === 'down' || key.name === 'j' || (key.name === 'n' && key.ctrl);
6
-
7
- exports.isSpaceKey = (key) => key.name === 'space';
8
-
9
- exports.isBackspaceKey = (key) => key.name === 'backspace';
10
-
11
- exports.isNumberKey = (key) => '123456789'.includes(key.name);
12
-
13
- exports.isEnterKey = (key) => key.name === 'enter' || key.name === 'return';
package/lib/options.js DELETED
@@ -1,12 +0,0 @@
1
- exports.getPromptConfig = async (options) => {
2
- let { message } = options;
3
- if (typeof options.message === 'function') {
4
- message = message();
5
- }
6
-
7
- return {
8
- validate: () => true,
9
- ...options,
10
- message: await message,
11
- };
12
- };
package/test.js DELETED
@@ -1,265 +0,0 @@
1
- const readline = require('readline');
2
- const { createPrompt } = require('.');
3
-
4
- jest.mock('readline', () => {
5
- const readline = jest.requireActual('readline');
6
- const EventEmitter = require('events');
7
- const stream = require('stream');
8
- const MuteStream = require('mute-stream');
9
- const fakeInstance = new EventEmitter();
10
- fakeInstance.input = new stream.Duplex();
11
- fakeInstance.output = new MuteStream();
12
- fakeInstance.line = '';
13
- fakeInstance.setPrompt = jest.fn();
14
- fakeInstance._getCursorPos = jest.fn(() => ({ rows: 0, col: 0 }));
15
-
16
- const fakeInstance2 = readline.createInterface({
17
- output: new MuteStream(),
18
- input: new MuteStream(),
19
- });
20
- fakeInstance2.line = '';
21
-
22
- return { createInterface: () => fakeInstance2 };
23
- });
24
- jest.useFakeTimers();
25
-
26
- describe('createPrompt()', () => {
27
- it('handle async message', async () => {
28
- const render = jest.fn(() => '');
29
- const prompt = createPrompt({}, render);
30
- let resolveCb;
31
- const promise = new Promise((resolve) => {
32
- resolveCb = resolve;
33
- });
34
- prompt({ message: () => promise });
35
-
36
- // Initially, we leave a few ms for message to resolve
37
- expect(render).not.toHaveBeenCalled();
38
-
39
- jest.advanceTimersByTime(500);
40
- expect(render).toHaveBeenCalledTimes(1);
41
- expect(render).toHaveBeenLastCalledWith(
42
- expect.objectContaining({
43
- loadingIncrement: 0,
44
- message: 'Loading...',
45
- status: 'loading',
46
- }),
47
- {}
48
- );
49
-
50
- jest.advanceTimersByTime(80);
51
- expect(render).toHaveBeenCalledTimes(2);
52
- expect(render).toHaveBeenLastCalledWith(
53
- expect.objectContaining({
54
- loadingIncrement: 1,
55
- message: 'Loading...',
56
- status: 'loading',
57
- }),
58
- {}
59
- );
60
-
61
- resolveCb('Async message:');
62
- await promise;
63
- await Promise.resolve(); // Wait one extra tick
64
- expect(render).toHaveBeenCalledTimes(3);
65
- expect(render).toHaveBeenLastCalledWith(
66
- expect.objectContaining({ message: 'Async message:', status: 'idle' }),
67
- {}
68
- );
69
- });
70
-
71
- it('submit: default filtering and validation', async () => {
72
- const rl = readline.createInterface();
73
- const render = jest.fn(() => '');
74
- const prompt = createPrompt({}, render);
75
- const promptPromise = prompt({ message: 'Question:' });
76
- expect(render).toHaveBeenCalledTimes(1);
77
- expect(render).toHaveBeenLastCalledWith(
78
- expect.objectContaining({ message: 'Question:', status: 'idle' }),
79
- {}
80
- );
81
-
82
- // Check it ignores return <enter> keypress
83
- rl.input.emit('keypress', null, { name: 'enter' });
84
- rl.input.emit('keypress', null, { name: 'return' });
85
- expect(render).toHaveBeenCalledTimes(1);
86
-
87
- rl.line = 'new value';
88
- rl.input.emit('keypress', null, { name: 'a' });
89
- await Promise.resolve();
90
- expect(render).toHaveBeenCalledTimes(2);
91
- expect(render).toHaveBeenLastCalledWith(
92
- expect.objectContaining({ value: 'new value', status: 'idle' }),
93
- {}
94
- );
95
-
96
- // Submit
97
- rl.emit('line');
98
- await Promise.resolve();
99
- await Promise.resolve();
100
-
101
- expect(render).toHaveBeenCalledTimes(3);
102
- expect(render).toHaveBeenLastCalledWith(
103
- expect.objectContaining({
104
- message: 'Question:',
105
- value: 'new value',
106
- status: 'done',
107
- }),
108
- {}
109
- );
110
-
111
- await expect(promptPromise).resolves.toEqual('new value');
112
- });
113
-
114
- it('submit: async filtering and validation', async () => {
115
- const rl = readline.createInterface();
116
- const render = jest.fn(() => '');
117
- const prompt = createPrompt({}, render);
118
- const filter = jest.fn(() => Promise.resolve('filtered value'));
119
- const validate = jest.fn(() => Promise.resolve(true));
120
- const promptPromise = prompt({ message: 'Question:', filter, validate });
121
- expect(render).toHaveBeenCalledTimes(1);
122
- expect(render).toHaveBeenLastCalledWith(
123
- expect.objectContaining({ message: 'Question:', status: 'idle' }),
124
- {}
125
- );
126
-
127
- rl.line = 'new value';
128
- rl.input.emit('keypress', null, { name: 'a' });
129
- await Promise.resolve();
130
- expect(render).toHaveBeenCalledTimes(2);
131
-
132
- rl.emit('line');
133
- expect(filter).toHaveBeenCalledWith('new value');
134
- jest.advanceTimersByTime(500);
135
- expect(render).toHaveBeenCalledTimes(3);
136
- expect(render).toHaveBeenLastCalledWith(
137
- expect.objectContaining({ message: 'Question:', status: 'loading' }),
138
- {}
139
- );
140
-
141
- await Promise.resolve();
142
- await Promise.resolve();
143
- expect(validate).toHaveBeenCalledWith('filtered value');
144
-
145
- await expect(promptPromise).resolves.toEqual('filtered value');
146
- });
147
-
148
- it('submit: handle validation error (function resolving to false)', async () => {
149
- const rl = readline.createInterface();
150
- const render = jest.fn(() => '');
151
- const prompt = createPrompt({}, render);
152
- const validate = jest.fn(() => Promise.resolve(false));
153
- prompt({ message: 'Question:', validate });
154
- expect(render).toHaveBeenCalledTimes(1);
155
-
156
- rl.emit('line');
157
- await Promise.resolve();
158
- await Promise.resolve();
159
- await Promise.resolve();
160
- expect(render).toHaveBeenCalledTimes(2);
161
- expect(render).toHaveBeenLastCalledWith(
162
- expect.objectContaining({
163
- message: 'Question:',
164
- error: 'You must provide a valid value',
165
- }),
166
- {}
167
- );
168
-
169
- // New input will clear the error message
170
- rl.input.emit('keypress', null, { name: 'a' });
171
- expect(render).toHaveBeenCalledTimes(3);
172
- expect(render).toHaveBeenLastCalledWith(expect.objectContaining({ error: null }), {});
173
- });
174
-
175
- it('submit: handle validation error (rejected promise)', async () => {
176
- const rl = readline.createInterface();
177
- const render = jest.fn(() => '');
178
- const prompt = createPrompt({}, render);
179
- const validate = jest.fn(() => Promise.reject(new Error('Only numbers allowed')));
180
- const promptPromise = prompt({ message: 'Question:', validate });
181
- expect(render).toHaveBeenCalledTimes(1);
182
-
183
- rl.emit('line');
184
- await Promise.resolve();
185
- await Promise.resolve();
186
- await Promise.resolve();
187
- expect(render).toHaveBeenCalledTimes(2);
188
- expect(render).toHaveBeenLastCalledWith(
189
- expect.objectContaining({
190
- message: 'Question:',
191
- error: expect.stringMatching('Only numbers allowed'),
192
- }),
193
- {}
194
- );
195
-
196
- validate.mockImplementation(() => Promise.resolve(true));
197
- rl.emit('line');
198
- await Promise.resolve();
199
- await Promise.resolve();
200
- await Promise.resolve();
201
- expect(render).toHaveBeenCalledTimes(3);
202
- expect(render).toHaveBeenLastCalledWith(
203
- expect.objectContaining({ status: 'done' }),
204
- {}
205
- );
206
- await promptPromise;
207
- });
208
-
209
- it('transformer: applies transformation to the value', async () => {
210
- const rl = readline.createInterface();
211
- const render = jest.fn(() => '');
212
- const prompt = createPrompt({}, render);
213
- const transformer = jest.fn((value, { isFinal }) =>
214
- isFinal ? 'last value' : 'transformed value'
215
- );
216
- const promptPromise = prompt({
217
- message: 'Question',
218
- transformer,
219
- filter: () => 'dummy value',
220
- });
221
- expect(render).toHaveBeenCalledTimes(1);
222
- expect(transformer).toHaveBeenLastCalledWith('', { isFinal: false });
223
- expect(render).toHaveBeenLastCalledWith(
224
- expect.objectContaining({ value: 'transformed value' }),
225
- {}
226
- );
227
-
228
- rl.emit('line');
229
- await Promise.resolve();
230
- await Promise.resolve();
231
- await Promise.resolve();
232
- expect(transformer).toHaveBeenLastCalledWith('', { isFinal: true });
233
- expect(render).toHaveBeenCalledTimes(2);
234
- expect(render).toHaveBeenLastCalledWith(
235
- expect.objectContaining({ value: 'last value' }),
236
- {}
237
- );
238
- await expect(promptPromise).resolves.toEqual('dummy value');
239
- });
240
-
241
- it('onKeypress: allow to implement custom behavior on keypress', () => {
242
- const rl = readline.createInterface();
243
- const render = jest.fn(() => '');
244
- const onKeypress = jest.fn((value, key, state, setState) => {
245
- setState({ value: key.name });
246
- });
247
- const prompt = createPrompt({ onKeypress }, render);
248
- prompt({ message: 'Question' });
249
-
250
- rl.input.emit('keypress', 'a value', { name: 'foo' });
251
- expect(onKeypress).toHaveBeenCalledTimes(1);
252
- expect(onKeypress).toHaveBeenLastCalledWith(
253
- 'new value',
254
- { name: 'foo' },
255
- expect.objectContaining({ message: 'Question', status: 'idle' }),
256
- expect.any(Function)
257
- );
258
-
259
- expect(render).toHaveBeenCalledTimes(3);
260
- expect(render).toHaveBeenLastCalledWith(
261
- expect.objectContaining({ status: 'idle', value: 'foo' }),
262
- expect.objectContaining({ onKeypress: expect.any(Function) })
263
- );
264
- });
265
- });