@depup/inquirer 13.3.0-depup.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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2025 Simon Boudrias
2
+
3
+ Permission is hereby granted, free of charge, to any person
4
+ obtaining a copy of this software and associated documentation
5
+ files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use,
7
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the
9
+ Software is furnished to do so, subject to the following
10
+ conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,555 @@
1
+ <img width="75px" height="75px" align="right" alt="Inquirer Logo" src="https://raw.githubusercontent.com/SBoudrias/Inquirer.js/main/assets/inquirer_readme.svg?sanitize=true" title="Inquirer.js"/>
2
+
3
+ # Inquirer.js
4
+
5
+ [![npm](https://badge.fury.io/js/inquirer.svg)](https://www.npmjs.com/package/inquirer)
6
+ [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FSBoudrias%2FInquirer.js.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FSBoudrias%2FInquirer.js?ref=badge_shield)
7
+
8
+ A collection of common interactive command line user interfaces.
9
+
10
+ > [!IMPORTANT]
11
+ > This is the legacy version of Inquirer.js. While it still receives maintenance, it is not actively developed. For the new Inquirer, see [@inquirer/prompts](https://www.npmjs.com/package/@inquirer/prompts).
12
+
13
+ ## Table of Contents
14
+
15
+ 1. [Documentation](#documentation)
16
+ 1. [Installation](#installation)
17
+ 2. [Examples](#examples)
18
+ 3. [Methods](#methods)
19
+ 4. [Objects](#objects)
20
+ 5. [Question](#question)
21
+ 6. [Answers](#answers)
22
+ 7. [Separator](#separator)
23
+ 8. [Prompt Types](#prompt-types)
24
+ 2. [User Interfaces and Layouts](#user-interfaces-and-layouts)
25
+ 1. [Reactive Interface](#reactive-interface)
26
+ 3. [Support](#support)
27
+ 4. [Known issues](#issues)
28
+ 5. [News](#news)
29
+ 6. [Contributing](#contributing)
30
+ 7. [License](#license)
31
+ 8. [Plugins](#plugins)
32
+
33
+ ## Goal and Philosophy
34
+
35
+ **`Inquirer.js`** strives to be an easily embeddable and beautiful command line interface for [Node.js](https://nodejs.org/) (and perhaps the "CLI [Xanadu](https://en.wikipedia.org/wiki/Citizen_Kane)").
36
+
37
+ **`Inquirer.js`** should ease the process of
38
+
39
+ - providing _error feedback_
40
+ - _asking questions_
41
+ - _parsing_ input
42
+ - _validating_ answers
43
+ - managing _hierarchical prompts_
44
+
45
+ > **Note:** **`Inquirer.js`** provides the user interface and the inquiry session flow. If you're searching for a full blown command line program utility, then check out [commander](https://github.com/visionmedia/commander.js), [vorpal](https://github.com/dthree/vorpal) or [args](https://github.com/leo/args).
46
+
47
+ ## [Documentation](#documentation)
48
+
49
+ <a name="documentation"></a>
50
+
51
+ ### Installation
52
+
53
+ <a name="installation"></a>
54
+
55
+ <table>
56
+ <tr>
57
+ <th>npm</th>
58
+ <th>yarn</th>
59
+ </tr>
60
+ <tr>
61
+ <td>
62
+
63
+ ```sh
64
+ npm install inquirer
65
+ ```
66
+
67
+ </td>
68
+ <td>
69
+
70
+ ```sh
71
+ yarn add inquirer
72
+ ```
73
+
74
+ </td>
75
+ </tr>
76
+ </table>
77
+
78
+ ```javascript
79
+ import inquirer from 'inquirer';
80
+
81
+ inquirer
82
+ .prompt([
83
+ /* Pass your questions in here */
84
+ ])
85
+ .then((answers) => {
86
+ // Use user feedback for... whatever!!
87
+ })
88
+ .catch((error) => {
89
+ if (error.isTtyError) {
90
+ // Prompt couldn't be rendered in the current environment
91
+ } else {
92
+ // Something else went wrong
93
+ }
94
+ });
95
+ ```
96
+
97
+ <a name="examples"></a>
98
+
99
+ ### Examples (Run it and see it)
100
+
101
+ Check out the [`packages/inquirer/examples/`](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/inquirer/examples) folder for code and interface examples.
102
+
103
+ ```shell
104
+ yarn node packages/inquirer/examples/pizza.js
105
+ yarn node packages/inquirer/examples/checkbox.js
106
+ # etc...
107
+ ```
108
+
109
+ ### Methods
110
+
111
+ <a name="methods"></a>
112
+
113
+ > [!WARNING]
114
+ > Those interfaces are not necessary for modern Javascript, while still maintained, they're depreciated. We highly encourage you to adopt the more ergonomic and modern API with [@inquirer/prompts](https://www.npmjs.com/package/@inquirer/prompts). Both `inquirer` and `@inquirer/prompts` are usable at the same time, so you can progressively migrate.
115
+
116
+ #### `inquirer.prompt(questions, answers) -> promise`
117
+
118
+ Launch the prompt interface (inquiry session)
119
+
120
+ - **questions** (Array) containing [Question Object](#question) (using the [reactive interface](#reactive-interface), you can also pass a `Rx.Observable` instance)
121
+ - **answers** (object) contains values of already answered questions. Inquirer will avoid asking answers already provided here. Defaults `{}`.
122
+ - returns a **Promise**
123
+
124
+ #### `inquirer.registerPrompt(name, prompt)`
125
+
126
+ Register prompt plugins under `name`.
127
+
128
+ - **name** (string) name of the this new prompt. (used for question `type`)
129
+ - **prompt** (object) the prompt object itself (the plugin)
130
+
131
+ #### `inquirer.createPromptModule() -> prompt function`
132
+
133
+ Create a self contained inquirer module. If you don't want to affect other libraries that also rely on inquirer when you overwrite or add new prompt types.
134
+
135
+ ```js
136
+ const prompt = inquirer.createPromptModule();
137
+
138
+ prompt(questions).then(/* ... */);
139
+ ```
140
+
141
+ ### Objects
142
+
143
+ <a name="objects"></a>
144
+
145
+ #### Question
146
+
147
+ <a name="questions"></a>
148
+ A question object is a `hash` containing question related values:
149
+
150
+ - **type**: (String) Type of the prompt. Defaults: `input` - Possible values: `input`, `number`, `confirm`, `list`, `rawlist`, `expand`, `checkbox`, `password`, `editor`
151
+ - **name**: (String) The name to use when storing the answer in the answers hash. If the name contains periods, it will define a path in the answers hash.
152
+ - **message**: (String|Function) The question to print. If defined as a function, the first parameter will be the current inquirer session answers. Defaults to the value of `name` (followed by a colon).
153
+ - **default**: (String|Number|Boolean|Array|Function) Default value(s) to use if nothing is entered, or a function that returns the default value(s). If defined as a function, the first parameter will be the current inquirer session answers.
154
+ - **choices**: (Array|Function) Choices array or a function returning a choices array. If defined as a function, the first parameter will be the current inquirer session answers.
155
+ Array values can be simple `numbers`, `strings`, or `objects` containing a `name` (to display in list), a `value` (to save in the answers hash), and a `short` (to display after selection) properties. The choices array can also contain [a `Separator`](#separator).
156
+ - **validate**: (Function) Receive the user input and answers hash. Should return `true` if the value is valid, and an error message (`String`) otherwise. If `false` is returned, a default error message is provided.
157
+ - **filter**: (Function) Receive the user input and answers hash. Returns the filtered value to be used inside the program. The value returned will be added to the _Answers_ hash.
158
+ - **transformer**: (Function) Receive the user input, answers hash and option flags, and return a transformed value to display to the user. The transformation only impacts what is shown while editing. It does not modify the answers hash.
159
+ - **when**: (Function, Boolean) Receive the current user answers hash and should return `true` or `false` depending on whether or not this question should be asked. The value can also be a simple boolean.
160
+ - **pageSize**: (Number) Change the number of lines that will be rendered when using `list`, `rawList`, `expand` or `checkbox`.
161
+ - **prefix**: (String) Change the default _prefix_ message.
162
+ - **suffix**: (String) Change the default _suffix_ message.
163
+ - **askAnswered**: (Boolean) Force to prompt the question if the answer already exists.
164
+ - **loop**: (Boolean) Enable list looping. Defaults: `true`
165
+ - **waitUserInput**: (Boolean) Flag to enable/disable wait for user input before opening system editor - Defaults: `true`
166
+
167
+ `default`, `choices`(if defined as functions), `validate`, `filter` and `when` functions can be called asynchronously. Either return a promise or use `this.async()` to get a callback you'll call with the final value.
168
+
169
+ ```javascript
170
+ {
171
+ /* Preferred way: with promise */
172
+ filter() {
173
+ return new Promise(/* etc... */);
174
+ },
175
+
176
+ /* Legacy way: with this.async */
177
+ validate: function (input) {
178
+ // Declare function as asynchronous, and save the done callback
179
+ const done = this.async();
180
+
181
+ // Do async stuff
182
+ setTimeout(function() {
183
+ if (typeof input !== 'number') {
184
+ // Pass the return value in the done callback
185
+ done('You need to provide a number');
186
+ } else {
187
+ // Pass the return value in the done callback
188
+ done(null, true);
189
+ }
190
+ }, 3000);
191
+ }
192
+ }
193
+ ```
194
+
195
+ ### Answers
196
+
197
+ <a name="answers"></a>
198
+ A key/value hash containing the client answers in each prompt.
199
+
200
+ - **Key** The `name` property of the _question_ object
201
+ - **Value** (Depends on the prompt)
202
+ - `confirm`: (Boolean)
203
+ - `input` : User input (filtered if `filter` is defined) (String)
204
+ - `number`: User input (filtered if `filter` is defined) (Number)
205
+ - `rawlist`, `list` : Selected choice value (or name if no value specified) (String)
206
+
207
+ ### Separator
208
+
209
+ <a name="separator"></a>
210
+ A separator can be added to any `choices` array:
211
+
212
+ ```
213
+ // In the question object
214
+ choices: [ "Choice A", new inquirer.Separator(), "choice B" ]
215
+
216
+ // Which'll be displayed this way
217
+ [?] What do you want to do?
218
+ > Order a pizza
219
+ Make a reservation
220
+ --------
221
+ Ask opening hours
222
+ Talk to the receptionist
223
+ ```
224
+
225
+ The constructor takes a facultative `String` value that'll be use as the separator. If omitted, the separator will be `--------`.
226
+
227
+ Separator instances have a property `type` equal to `separator`. This should allow tools façading Inquirer interface from detecting separator types in lists.
228
+
229
+ <a name="prompt"></a>
230
+
231
+ ### Prompt types
232
+
233
+ ---
234
+
235
+ > **Note:**: _allowed options written inside square brackets (`[]`) are optional. Others are required._
236
+
237
+ #### List - `{type: 'list'}`
238
+
239
+ Take `type`, `name`, `message`, `choices`[, `default`, `filter`, `loop`] properties.
240
+ (Note: `default` must be set to the `index` or `value` of one of the entries in `choices`)
241
+
242
+ ![List prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/list.svg)
243
+
244
+ ---
245
+
246
+ #### Raw List - `{type: 'rawlist'}`
247
+
248
+ Take `type`, `name`, `message`, `choices`[, `default`, `filter`, `loop`] properties.
249
+ (Note: `default` must be set to the `index` of one of the entries in `choices`)
250
+
251
+ ![Raw list prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/rawlist.svg)
252
+
253
+ ---
254
+
255
+ #### Expand - `{type: 'expand'}`
256
+
257
+ Take `type`, `name`, `message`, `choices`[, `default`] properties.
258
+ Note: `default` must be the `index` of the desired default selection of the array. If `default` key not provided, then `help` will be used as default choice
259
+
260
+ Note that the `choices` object will take an extra parameter called `key` for the `expand` prompt. This parameter must be a single (lowercased) character. The `h` option is added by the prompt and shouldn't be defined by the user.
261
+
262
+ See `examples/expand.js` for a running example.
263
+
264
+ ![Expand prompt closed](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/expand-y.svg)
265
+ ![Expand prompt expanded](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/expand-d.svg)
266
+
267
+ ---
268
+
269
+ #### Checkbox - `{type: 'checkbox'}`
270
+
271
+ Take `type`, `name`, `message`, `choices`[, `filter`, `validate`, `default`, `loop`] properties. `default` is expected to be an Array of the checked choices value.
272
+
273
+ Choices marked as `{checked: true}` will be checked by default.
274
+
275
+ Choices whose property `disabled` is truthy will be unselectable. If `disabled` is a string, then the string will be outputted next to the disabled choice, otherwise it'll default to `"Disabled"`. The `disabled` property can also be a synchronous function receiving the current answers as argument and returning a boolean or a string.
276
+
277
+ ![Checkbox prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/checkbox.svg)
278
+
279
+ ---
280
+
281
+ #### Confirm - `{type: 'confirm'}`
282
+
283
+ Take `type`, `name`, `message`, [`default`, `transformer`] properties. `default` is expected to be a boolean if used.
284
+
285
+ ![Confirm prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/confirm.svg)
286
+
287
+ ---
288
+
289
+ #### Input - `{type: 'input'}`
290
+
291
+ Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] properties.
292
+
293
+ ![Input prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/input.svg)
294
+
295
+ ---
296
+
297
+ #### Input - `{type: 'number'}`
298
+
299
+ Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] properties.
300
+
301
+ ---
302
+
303
+ #### Password - `{type: 'password'}`
304
+
305
+ Take `type`, `name`, `message`, `mask`,[, `default`, `filter`, `validate`] properties.
306
+
307
+ ![Password prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/password.svg)
308
+
309
+ ---
310
+
311
+ Note that `mask` is required to hide the actual user input.
312
+
313
+ #### Editor - `{type: 'editor'}`
314
+
315
+ Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `postfix`, `waitUserInput`] properties
316
+
317
+ Launches an instance of the users preferred editor on a temporary file. Once the user exits their editor, the contents of the temporary file are read in as the result. The editor to use is determined by reading the $VISUAL or $EDITOR environment variables. If neither of those are present, notepad (on Windows) or vim (Linux or Mac) is used.
318
+
319
+ The `postfix` property is useful if you want to provide an extension.
320
+
321
+ <a name="layouts"></a>
322
+
323
+ ### Use in Non-Interactive Environments
324
+
325
+ `prompt()` requires that it is run in an interactive environment. (I.e. [One where `process.stdin.isTTY` is `true`](https://nodejs.org/docs/latest-v12.x/api/process.html#process_a_note_on_process_i_o)). If `prompt()` is invoked outside of such an environment, then `prompt()` will return a rejected promise with an error. For convenience, the error will have a `isTtyError` property to programmatically indicate the cause.
326
+
327
+ <a name="reactive"></a>
328
+
329
+ ## Reactive interface
330
+
331
+ Internally, Inquirer uses the [JS reactive extension](https://github.com/ReactiveX/rxjs) to handle events and async flows.
332
+
333
+ This mean you can take advantage of this feature to provide more advanced flows. For example, you can dynamically add questions to be asked:
334
+
335
+ ```js
336
+ const prompts = new Rx.Subject();
337
+ inquirer.prompt(prompts);
338
+
339
+ // At some point in the future, push new questions
340
+ prompts.next({
341
+ /* question... */
342
+ });
343
+ prompts.next({
344
+ /* question... */
345
+ });
346
+
347
+ // When you're done
348
+ prompts.complete();
349
+ ```
350
+
351
+ And using the return value `process` property, you can access more fine grained callbacks:
352
+
353
+ ```js
354
+ inquirer.prompt(prompts).ui.process.subscribe(onEachAnswer, onError, onComplete);
355
+ ```
356
+
357
+ ## Support (OS Terminals)
358
+
359
+ <a name="support"></a>
360
+
361
+ You should expect mostly good support for the CLI below. This does not mean we won't
362
+ look at issues found on other command line - feel free to report any!
363
+
364
+ - **Mac OS**:
365
+ - Terminal.app
366
+ - iTerm
367
+ - **Windows ([Known issues](#issues))**:
368
+ - [Windows Terminal](https://github.com/microsoft/terminal)
369
+ - [ConEmu](https://conemu.github.io/)
370
+ - cmd.exe
371
+ - Powershell
372
+ - Cygwin
373
+ - **Linux (Ubuntu, openSUSE, Arch Linux, etc)**:
374
+ - gnome-terminal (Terminal GNOME)
375
+ - konsole
376
+
377
+ ## Known issues
378
+
379
+ <a name="issues"></a>
380
+
381
+ - **nodemon** - Makes the arrow keys print gibrish on list prompts.
382
+ Workaround: Add `{ stdin : false }` in the configuration file or pass `--no-stdin` in the CLI.
383
+ Please refer to [this issue](https://github.com/SBoudrias/Inquirer.js/issues/844#issuecomment-736675867)
384
+
385
+ - **grunt-exec** - Calling a node script that uses Inquirer from grunt-exec can cause the program to crash. To fix this, add to your grunt-exec config `stdio: 'inherit'`.
386
+ Please refer to [this issue](https://github.com/jharding/grunt-exec/issues/85)
387
+
388
+ - **Windows network streams** - Running Inquirer together with network streams in Windows platform inside some terminals can result in process hang.
389
+ Workaround: run inside another terminal.
390
+ Please refer to [this issue](https://github.com/nodejs/node/issues/21771)
391
+
392
+ ## News on the march (Release notes)
393
+
394
+ <a name="news"></a>
395
+
396
+ Please refer to the [GitHub releases section for the changelog](https://github.com/SBoudrias/Inquirer.js/releases)
397
+
398
+ ## Contributing
399
+
400
+ <a name="contributing"></a>
401
+
402
+ **Unit test**
403
+ Please add a unit test for every new feature or bug fix. `yarn test` to run the test suite.
404
+
405
+ **Documentation**
406
+ Add documentation for every API change. Feel free to send typo fixes and better docs!
407
+
408
+ We're looking to offer good support for multiple prompts and environments. If you want to
409
+ help, we'd like to keep a list of testers for each terminal/OS so we can contact you and
410
+ get feedback before release. Let us know if you want to be added to the list (just tweet
411
+ to [@vaxilart](https://twitter.com/Vaxilart)) or just add your name to [the wiki](https://github.com/SBoudrias/Inquirer.js/wiki/Testers)
412
+
413
+ ## License
414
+
415
+ <a name="license"></a>
416
+
417
+ Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
418
+ Licensed under the MIT license.
419
+
420
+ ## Plugins
421
+
422
+ <a name="plugins"></a>
423
+
424
+ You can build custom prompts, or use open sourced ones. See [`@inquirer/core` documentation for building custom prompts](https://github.com/SBoudrias/Inquirer.js/tree/main/packages/core).
425
+
426
+ You can either call the custom prompts directly (preferred), or you can register them (depreciated):
427
+
428
+ ```js
429
+ import customPrompt from '$$$/custom-prompt';
430
+
431
+ // 1. Preferred solution with new plugins
432
+ const answer = await customPrompt({ ...config });
433
+
434
+ // 2. Depreciated interface (or for old plugins)
435
+ inquirer.registerPrompt('custom', customPrompt);
436
+ const answers = await inquirer.prompt([
437
+ {
438
+ type: 'custom',
439
+ ...config,
440
+ },
441
+ ]);
442
+ ```
443
+
444
+ When using Typescript and `registerPrompt`, you'll also need to define your prompt signature. Since Typescript is static, we cannot infer available plugins from function calls.
445
+
446
+ ```ts
447
+ import customPrompt from '$$$/custom-prompt';
448
+
449
+ declare module 'inquirer' {
450
+ interface QuestionMap {
451
+ // 1. Easiest option
452
+ custom: Parameters<typeof customPrompt>[0];
453
+
454
+ // 2. Or manually define the prompt config
455
+ custom_alt: { message: string; option: number[] };
456
+ }
457
+ }
458
+ ```
459
+
460
+ ### Prompts
461
+
462
+ [**autocomplete**](https://github.com/mokkabonna/inquirer-autocomplete-prompt)<br>
463
+ Presents a list of options as the user types, compatible with other packages such as fuzzy (for search)<br>
464
+ <br>
465
+ ![autocomplete prompt](https://raw.githubusercontent.com/mokkabonna/inquirer-autocomplete-prompt/master/packages/inquirer-autocomplete-prompt/inquirer.gif)
466
+
467
+ [**checkbox-plus**](https://github.com/faressoft/inquirer-checkbox-plus-prompt)<br>
468
+ Checkbox list with autocomplete and other additions<br>
469
+ <br>
470
+ ![checkbox-plus](https://github.com/faressoft/inquirer-checkbox-plus-prompt/raw/master/demo.gif)
471
+
472
+ [**inquirer-date-prompt**](https://github.com/haversnail/inquirer-date-prompt)<br>
473
+ Customizable date/time selector with localization support<br>
474
+ <br>
475
+ ![Date Prompt](https://github.com/haversnail/inquirer-date-prompt/raw/master/examples/demo.gif)
476
+
477
+ [**datetime**](https://github.com/DerekTBrown/inquirer-datepicker-prompt)<br>
478
+ Customizable date/time selector using both number pad and arrow keys<br>
479
+ <br>
480
+ ![Datetime Prompt](https://github.com/DerekTBrown/inquirer-datepicker-prompt/raw/master/example/datetime-prompt.png)
481
+
482
+ [**inquirer-select-line**](https://github.com/adam-golab/inquirer-select-line)<br>
483
+ Prompt for selecting index in array where add new element<br>
484
+ <br>
485
+ ![inquirer-select-line gif](https://media.giphy.com/media/xUA7b1MxpngddUvdHW/giphy.gif)
486
+
487
+ [**command**](https://github.com/sullof/inquirer-command-prompt)<br>
488
+ Simple prompt with command history and dynamic autocomplete<br>
489
+
490
+ [**inquirer-fuzzy-path**](https://github.com/adelsz/inquirer-fuzzy-path)<br>
491
+ Prompt for fuzzy file/directory selection.<br>
492
+ <br>
493
+ ![inquirer-fuzzy-path](https://raw.githubusercontent.com/adelsz/inquirer-fuzzy-path/master/recording.gif)
494
+
495
+ [**inquirer-emoji**](https://github.com/tannerntannern/inquirer-emoji)<br>
496
+ Prompt for inputting emojis.<br>
497
+ <br>
498
+ ![inquirer-emoji](https://github.com/tannerntannern/inquirer-emoji/raw/master/demo.gif)
499
+
500
+ [**inquirer-chalk-pipe**](https://github.com/LitoMore/inquirer-chalk-pipe)<br>
501
+ Prompt for input chalk-pipe style strings<br>
502
+ <br>
503
+ ![inquirer-chalk-pipe](https://github.com/LitoMore/inquirer-chalk-pipe/blob/main/screenshot.gif)
504
+
505
+ [**inquirer-search-checkbox**](https://github.com/clinyong/inquirer-search-checkbox)<br>
506
+ Searchable Inquirer checkbox<br>
507
+ ![inquirer-search-checkbox](https://github.com/clinyong/inquirer-search-checkbox/blob/master/screenshot.png)
508
+
509
+ [**inquirer-search-list**](https://github.com/robin-rpr/inquirer-search-list)<br>
510
+ Searchable Inquirer list<br>
511
+ <br>
512
+ ![inquirer-search-list](https://github.com/robin-rpr/inquirer-search-list/blob/master/preview.gif)
513
+
514
+ [**inquirer-prompt-suggest**](https://github.com/olistic/inquirer-prompt-suggest)<br>
515
+ Inquirer prompt for your less creative users.<br>
516
+ <br>
517
+ ![inquirer-prompt-suggest](https://user-images.githubusercontent.com/5600126/40391192-d4f3d6d0-5ded-11e8-932f-4b75b642c09e.gif)
518
+
519
+ [**inquirer-s3**](https://github.com/HQarroum/inquirer-s3)<br>
520
+ An S3 object selector for Inquirer.<br>
521
+ <br>
522
+ ![inquirer-s3](https://github.com/HQarroum/inquirer-s3/raw/master/docs/inquirer-screenshot.png)
523
+
524
+ [**inquirer-autosubmit-prompt**](https://github.com/yaodingyd/inquirer-autosubmit-prompt)<br>
525
+ Auto submit based on your current input, saving one extra enter<br>
526
+
527
+ [**inquirer-file-tree-selection-prompt**](https://github.com/anc95/inquirer-file-tree-selection)<br>
528
+ Inquirer prompt for to select a file or directory in file tree<br>
529
+ <br>
530
+ ![inquirer-file-tree-selection-prompt](https://github.com/anc95/inquirer-file-tree-selection/blob/master/example/screenshot.gif)
531
+
532
+ [**inquirer-tree-prompt**](https://github.com/insightfuls/inquirer-tree-prompt)<br>
533
+ Inquirer prompt to select from a tree<br>
534
+ <br>
535
+ ![inquirer-tree-prompt](https://github.com/insightfuls/inquirer-tree-prompt/blob/main/example/screenshot.gif)
536
+
537
+ [**inquirer-table-prompt**](https://github.com/eduardoboucas/inquirer-table-prompt)<br>
538
+ A table-like prompt for Inquirer.<br>
539
+ <br>
540
+ ![inquirer-table-prompt](https://raw.githubusercontent.com/eduardoboucas/inquirer-table-prompt/master/screen-capture.gif)
541
+
542
+ [**inquirer-table-input**](https://github.com/edelciomolina/inquirer-table-input)<br>
543
+ A table editing prompt for Inquirer.<br>
544
+ <br>
545
+ ![inquirer-table-prompt](https://raw.githubusercontent.com/edelciomolina/inquirer-table-input/master/screen-capture.gif)
546
+
547
+ [**inquirer-interrupted-prompt**](https://github.com/lnquy065/inquirer-interrupted-prompt)<br>
548
+ Turning any existing inquirer and its plugin prompts into prompts that can be interrupted with a custom key.<br>
549
+ <br>
550
+ ![inquirer-interrupted-prompt](https://raw.githubusercontent.com/lnquy065/inquirer-interrupted-prompt/master/example/demo-menu.gif)
551
+
552
+ [**inquirer-press-to-continue**](https://github.com/leonzalion/inquirer-press-to-continue)<br>
553
+ A "press any key to continue" prompt for Inquirer.js<br>
554
+ <br>
555
+ ![inquirer-press-to-continue](https://raw.githubusercontent.com/leonzalion/inquirer-press-to-continue/main/assets/demo.gif)
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Inquirer.js
3
+ * A collection of common interactive command line user interfaces.
4
+ */
5
+ import { Separator } from '@inquirer/prompts';
6
+ import type { Prettify } from '@inquirer/type';
7
+ import PromptsRunner from './ui/prompt.ts';
8
+ import type { PromptCollection, LegacyPromptConstructor, PromptFn } from './ui/prompt.ts';
9
+ import type { Answers, StreamOptions, QuestionMap, PromptSession, PromptModulePublicQuestion, PromptModuleSpecificQuestion, PromptModuleNamedQuestion, QuestionSequence, MergedAnswers, DictionaryAnswers } from './types.ts';
10
+ type PublicQuestions<A extends Answers, Prefilled extends Answers> = QuestionSequence<PromptModulePublicQuestion<MergedAnswers<A, Prefilled>, A>>;
11
+ type InternalQuestions<A extends Answers, Prefilled extends Answers, Prompts extends Record<string, Record<string, unknown>>> = QuestionSequence<PromptModuleNamedQuestion<MergedAnswers<A, Prefilled>, Prompts, A>>;
12
+ type QuestionsDictionary<A extends Answers, Prefilled extends Answers, Prompts extends Record<string, Record<string, unknown>>> = {
13
+ [name in keyof A]: PromptModuleSpecificQuestion<MergedAnswers<A, Prefilled>, Prompts>;
14
+ };
15
+ type PromptModuleApi<Prompts extends Record<string, Record<string, unknown>> = never> = {
16
+ <const A extends Answers, const Prefilled extends Answers = object>(questions: PublicQuestions<A, Prefilled> | InternalQuestions<A, Prefilled, Prompts>, answers?: Prefilled): PromptReturnType<MergedAnswers<A, Prefilled>>;
17
+ <const A extends Answers, const Prefilled extends Answers = object>(questions: QuestionsDictionary<A, Prefilled, Prompts>, answers?: Prefilled): PromptReturnType<DictionaryAnswers<A, Prefilled>>;
18
+ <A extends Answers>(questions: PromptSession<A>, answers?: Partial<A>): PromptReturnType<A>;
19
+ } & {
20
+ prompts: PromptCollection;
21
+ registerPrompt(name: string, prompt: LegacyPromptConstructor | PromptFn): PromptModuleApi<Prompts>;
22
+ restoreDefaultPrompts(): void;
23
+ };
24
+ export type { QuestionMap, Question, DistinctQuestion, Answers, PromptSession, } from './types.ts';
25
+ type PromptReturnType<T> = Promise<Prettify<T>> & {
26
+ ui: PromptsRunner<Prettify<T>>;
27
+ };
28
+ /**
29
+ * Create a new self-contained prompt module.
30
+ */
31
+ export declare function createPromptModule<Prompts extends Record<string, Record<string, unknown>> = never>(opt?: StreamOptions): PromptModuleApi<Prompts>;
32
+ declare function registerPrompt(name: string, newPrompt: LegacyPromptConstructor): void;
33
+ declare function restoreDefaultPrompts(): void;
34
+ declare const inquirer: {
35
+ prompt: PromptModuleApi<Omit<QuestionMap, "__dummy">>;
36
+ ui: {
37
+ Prompt: typeof PromptsRunner;
38
+ };
39
+ createPromptModule: typeof createPromptModule;
40
+ registerPrompt: typeof registerPrompt;
41
+ restoreDefaultPrompts: typeof restoreDefaultPrompts;
42
+ Separator: typeof Separator;
43
+ };
44
+ export default inquirer;
package/dist/index.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Inquirer.js
3
+ * A collection of common interactive command line user interfaces.
4
+ */
5
+ import { input, select, number, confirm, rawlist, expand, checkbox, password, editor, search, Separator, } from '@inquirer/prompts';
6
+ import PromptsRunner from "./ui/prompt.js";
7
+ const builtInPrompts = {
8
+ input,
9
+ select,
10
+ number,
11
+ confirm,
12
+ rawlist,
13
+ expand,
14
+ checkbox,
15
+ password,
16
+ editor,
17
+ search,
18
+ };
19
+ /**
20
+ * Create a new self-contained prompt module.
21
+ */
22
+ export function createPromptModule(opt) {
23
+ function promptModule(questions, answers) {
24
+ const runner = new PromptsRunner(promptModule.prompts, opt);
25
+ const promptPromise = runner.run(questions, answers);
26
+ return Object.assign(promptPromise, { ui: runner });
27
+ }
28
+ promptModule.prompts = { ...builtInPrompts };
29
+ /**
30
+ * Register a prompt type
31
+ */
32
+ promptModule.registerPrompt = function (name, prompt) {
33
+ promptModule.prompts[name] = prompt;
34
+ return this;
35
+ };
36
+ /**
37
+ * Register the defaults provider prompts
38
+ */
39
+ promptModule.restoreDefaultPrompts = function () {
40
+ promptModule.prompts = { ...builtInPrompts };
41
+ };
42
+ return promptModule;
43
+ }
44
+ /**
45
+ * Public CLI helper interface
46
+ */
47
+ const prompt = createPromptModule();
48
+ // Expose helper functions on the top level for easiest usage by common users
49
+ function registerPrompt(name, newPrompt) {
50
+ prompt.registerPrompt(name, newPrompt);
51
+ }
52
+ function restoreDefaultPrompts() {
53
+ prompt.restoreDefaultPrompts();
54
+ }
55
+ const inquirer = {
56
+ prompt,
57
+ ui: {
58
+ Prompt: PromptsRunner,
59
+ },
60
+ createPromptModule,
61
+ registerPrompt,
62
+ restoreDefaultPrompts,
63
+ Separator,
64
+ };
65
+ export default inquirer;
@@ -0,0 +1,100 @@
1
+ import { checkbox, confirm, editor, expand, input, number, password, rawlist, search, select } from '@inquirer/prompts';
2
+ import type { Context, DistributiveMerge, Prettify } from '@inquirer/type';
3
+ import { Observable } from 'rxjs';
4
+ export type Answers<Key extends string = string> = Record<Key, any>;
5
+ export type NoInfer<T> = [T][T extends any ? 0 : never];
6
+ type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
7
+ type EmptyRecord = Record<string, never>;
8
+ type DotPathRecord<Path extends string, Value> = Path extends `${infer Head}.${infer Rest}` ? Head extends '' ? EmptyRecord : {
9
+ [K in Head]: DotPathRecord<Rest, Value>;
10
+ } : Path extends '' ? EmptyRecord : {
11
+ [K in Path]: Value;
12
+ };
13
+ export type NormalizeAnswers<A extends Answers> = string extends keyof A ? A : Extract<keyof A, string> extends never ? EmptyRecord : Prettify<UnionToIntersection<{
14
+ [Key in Extract<keyof A, string>]: DotPathRecord<Key, [
15
+ A[Key]
16
+ ] extends [never] ? any : A[Key]>;
17
+ }[Extract<keyof A, string>]>>;
18
+ type Mutable<T> = {
19
+ -readonly [K in keyof T]: T[K];
20
+ };
21
+ type WidenAnswerLiterals<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T extends bigint ? bigint : T extends symbol ? symbol : T extends ReadonlyArray<infer U> ? ReadonlyArray<WidenAnswerLiterals<U>> : T extends Array<infer U> ? Array<WidenAnswerLiterals<U>> : T extends Record<string, unknown> ? {
22
+ [K in keyof Mutable<T>]: Mutable<T>[K] extends infer V ? V extends undefined ? never : WidenAnswerLiterals<V> : never;
23
+ } : T;
24
+ type MergeAnswerObjects<Base, Override> = Prettify<Omit<Base, keyof Override> & Override>;
25
+ export type AsyncGetterFunction<T, A extends Answers> = (this: {
26
+ async: () => (...args: [error: null | undefined, value: T] | [error: Error, value: undefined]) => void;
27
+ }, answers: NoInfer<Prettify<Partial<A>>>) => void | T | Promise<T>;
28
+ type MaybeAsyncValue<T, A extends Answers> = T | AsyncGetterFunction<T, A>;
29
+ /**
30
+ * Allows to inject a custom question type into inquirer module.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * declare module 'inquirer' {
35
+ * interface QuestionMap {
36
+ * custom: { message: string };
37
+ * }
38
+ * }
39
+ * ```
40
+ *
41
+ * Globally defined question types are not correct.
42
+ */
43
+ export interface QuestionMap {
44
+ __dummy: {
45
+ message: string;
46
+ };
47
+ }
48
+ type KeyValueOrAsyncGetterFunction<T, k extends string, A extends Answers> = T extends Record<string, any> ? MaybeAsyncValue<T[k], A> : never;
49
+ export type Question<A extends Answers = Answers, Type extends string = string> = {
50
+ type: Type;
51
+ name: string;
52
+ message: MaybeAsyncValue<string, A>;
53
+ default?: any;
54
+ choices?: any;
55
+ validate?: (value: any, answers: NoInfer<Partial<A>>) => boolean | string | Promise<boolean | string>;
56
+ filter?: (answer: any, answers: NoInfer<Partial<A>>) => any;
57
+ askAnswered?: boolean;
58
+ when?: MaybeAsyncValue<boolean, A>;
59
+ };
60
+ type QuestionWithGetters<Type extends string, Q extends Record<string, any>, A extends Answers> = DistributiveMerge<Q, {
61
+ type: Type;
62
+ askAnswered?: boolean;
63
+ when?: MaybeAsyncValue<boolean, A>;
64
+ filter?(input: any, answers: NoInfer<A>): any;
65
+ message: KeyValueOrAsyncGetterFunction<Q, 'message', A>;
66
+ default?: KeyValueOrAsyncGetterFunction<Q, 'default', A>;
67
+ choices?: KeyValueOrAsyncGetterFunction<Q, 'choices', A>;
68
+ }>;
69
+ export type UnnamedDistinctQuestion<A extends Answers = object> = QuestionWithGetters<'checkbox', Parameters<typeof checkbox>[0] & {
70
+ default: unknown[];
71
+ }, A> | QuestionWithGetters<'confirm', Parameters<typeof confirm>[0], A> | QuestionWithGetters<'editor', Parameters<typeof editor>[0], A> | QuestionWithGetters<'expand', Parameters<typeof expand>[0], A> | QuestionWithGetters<'input', Parameters<typeof input>[0], A> | QuestionWithGetters<'number', Parameters<typeof number>[0], A> | QuestionWithGetters<'password', Parameters<typeof password>[0], A> | QuestionWithGetters<'rawlist', Parameters<typeof rawlist>[0], A> | QuestionWithGetters<'search', Parameters<typeof search>[0], A> | QuestionWithGetters<'select', Parameters<typeof select>[0], A>;
72
+ export type CustomQuestion<A extends Answers, Q extends Record<string, Record<string, any>>> = {
73
+ [key in Extract<keyof Q, string>]: Readonly<QuestionWithGetters<key, Q[key], A>>;
74
+ }[Extract<keyof Q, string>];
75
+ export type PromptModuleSpecificQuestion<A extends Answers, Prompts extends Record<string, Record<string, any>> = never> = UnnamedDistinctQuestion<A> | CustomQuestion<A, Prompts>;
76
+ export type PromptModuleNamedQuestion<A extends Answers, Prompts extends Record<string, Record<string, any>> = never, Flat extends Answers = A> = Prettify<PromptModuleSpecificQuestion<A, Prompts> & {
77
+ name: Extract<keyof Flat, string>;
78
+ }>;
79
+ export type DistinctQuestion<A extends Answers = Answers> = PromptModuleNamedQuestion<A>;
80
+ export type PromptSession<A extends Answers = Answers, Q extends Question<A> = Question<A>> = readonly Q[] | Record<string, Omit<Q, 'name'>> | Observable<Q> | Q;
81
+ export type QuestionSequence<Q> = Q | readonly Q[] | Observable<Q>;
82
+ export type MergedAnswers<A extends Answers, Prefilled extends Answers> = MergeAnswerObjects<NormalizeAnswers<A>, WidenAnswerLiterals<Prefilled>>;
83
+ export type QuestionDictionary<A extends Answers, Q> = {
84
+ [name in keyof A]: Q;
85
+ };
86
+ export type DictionaryAnswers<A extends Answers, Prefilled extends Answers> = MergeAnswerObjects<NormalizeAnswers<Answers<Extract<keyof A, string>>>, WidenAnswerLiterals<Prefilled>>;
87
+ export type PromptModulePublicQuestion<A extends Answers, Flat extends Answers = A> = {
88
+ type: 'input' | 'confirm' | 'editor' | 'password' | 'number' | 'rawlist' | 'expand' | 'checkbox' | 'search' | 'select';
89
+ name: Extract<keyof Flat, string>;
90
+ message: MaybeAsyncValue<string, A>;
91
+ default?: unknown;
92
+ choices?: unknown;
93
+ filter?: (input: any, answers: NoInfer<Partial<A>>) => any;
94
+ askAnswered?: boolean;
95
+ when?: MaybeAsyncValue<boolean, A>;
96
+ } & Record<string, unknown>;
97
+ export type StreamOptions = Prettify<Context & {
98
+ skipTTYChecks?: boolean;
99
+ }>;
100
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ import { Observable } from 'rxjs';
2
+ import type { InquirerReadline } from '@inquirer/type';
3
+ import type { Answers, PromptSession, StreamOptions } from '../types.ts';
4
+ export declare const _: {
5
+ set: (obj: Record<string, unknown>, path: string | undefined, value: unknown) => void;
6
+ get: (obj: object, path?: string | number | symbol, defaultValue?: unknown) => any;
7
+ };
8
+ export interface PromptBase {
9
+ /**
10
+ * Runs the prompt.
11
+ *
12
+ * @returns
13
+ * The result of the prompt.
14
+ */
15
+ run(): Promise<any>;
16
+ }
17
+ /**
18
+ * Provides the functionality to initialize new prompts.
19
+ */
20
+ export interface LegacyPromptConstructor {
21
+ /**
22
+ * Initializes a new instance of a prompt.
23
+ *
24
+ * @param question
25
+ * The question to prompt.
26
+ *
27
+ * @param readLine
28
+ * An object for reading from the command-line.
29
+ *
30
+ * @param answers
31
+ * The answers provided by the user.
32
+ */
33
+ new (question: any, readLine: InquirerReadline, answers: Record<string, any>): PromptBase;
34
+ }
35
+ export type PromptFn<Value = any, Config = any> = (config: Config, context: StreamOptions & {
36
+ signal: AbortSignal;
37
+ }) => Promise<Value>;
38
+ /**
39
+ * Provides a set of prompt-constructors.
40
+ */
41
+ export type PromptCollection = Record<string, PromptFn | LegacyPromptConstructor>;
42
+ /**
43
+ * Base interface class other can inherits from
44
+ */
45
+ export default class PromptsRunner<A extends Answers> {
46
+ private prompts;
47
+ answers: Partial<A>;
48
+ process: Observable<any>;
49
+ private abortController;
50
+ private opt;
51
+ constructor(prompts: PromptCollection, opt?: StreamOptions);
52
+ run(questions: PromptSession<A>, answers?: Partial<A>): Promise<A>;
53
+ private prepareQuestion;
54
+ private fetchAnswer;
55
+ /**
56
+ * Close the interface and cleanup listeners
57
+ */
58
+ close: () => void;
59
+ private shouldRun;
60
+ }
@@ -0,0 +1,271 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment */
2
+ import readline from 'node:readline';
3
+ import { defer, EMPTY, from, of, concatMap, filter, reduce, isObservable, lastValueFrom, } from 'rxjs';
4
+ import runAsync from 'run-async';
5
+ import MuteStream from 'mute-stream';
6
+ import { AbortPromptError } from '@inquirer/core';
7
+ import { cursorShow } from '@inquirer/ansi';
8
+ export const _ = {
9
+ set: (obj, path = '', value) => {
10
+ let pointer = obj;
11
+ path.split('.').forEach((key, index, arr) => {
12
+ if (key === '__proto__' || key === 'constructor')
13
+ return;
14
+ if (index === arr.length - 1) {
15
+ pointer[key] = value;
16
+ }
17
+ else if (!(key in pointer) || typeof pointer[key] !== 'object') {
18
+ pointer[key] = {};
19
+ }
20
+ pointer = pointer[key];
21
+ });
22
+ },
23
+ get: (obj, path = '', defaultValue) => {
24
+ const travel = (regexp) => String.prototype.split
25
+ .call(path, regexp)
26
+ .filter(Boolean)
27
+ .reduce(
28
+ // @ts-expect-error implicit any on res[key]
29
+ (res, key) => (res == null ? res : res[key]), obj);
30
+ const result = travel(/[,[\]]+?/) || travel(/[,.[\]]+?/);
31
+ return result === undefined || result === obj ? defaultValue : result;
32
+ },
33
+ };
34
+ /**
35
+ * Resolve a question property value if it is passed as a function.
36
+ * This method will overwrite the property on the question object with the received value.
37
+ */
38
+ async function fetchAsyncQuestionProperty(question, prop, answers) {
39
+ const propGetter = question[prop];
40
+ if (typeof propGetter === 'function') {
41
+ return runAsync(propGetter)(answers);
42
+ }
43
+ return propGetter;
44
+ }
45
+ class TTYError extends Error {
46
+ name = 'TTYError';
47
+ isTtyError = true;
48
+ }
49
+ function setupReadlineOptions(opt) {
50
+ // Inquirer 8.x:
51
+ // opt.skipTTYChecks = opt.skipTTYChecks === undefined ? opt.input !== undefined : opt.skipTTYChecks;
52
+ opt.skipTTYChecks = opt.skipTTYChecks === undefined ? true : opt.skipTTYChecks;
53
+ // Default `input` to stdin
54
+ const input = opt.input || process.stdin;
55
+ // Check if prompt is being called in TTY environment
56
+ // If it isn't return a failed promise
57
+ // @ts-expect-error: ignore isTTY type error
58
+ if (!opt.skipTTYChecks && !input.isTTY) {
59
+ throw new TTYError('Prompts can not be meaningfully rendered in non-TTY environments');
60
+ }
61
+ // Add mute capabilities to the output
62
+ const ms = new MuteStream();
63
+ ms.pipe(opt.output || process.stdout);
64
+ const output = ms;
65
+ return {
66
+ terminal: true,
67
+ ...opt,
68
+ input,
69
+ output,
70
+ };
71
+ }
72
+ function isQuestionArray(questions) {
73
+ return Array.isArray(questions);
74
+ }
75
+ function isQuestionMap(questions) {
76
+ return Object.values(questions).every((maybeQuestion) => typeof maybeQuestion === 'object' &&
77
+ !Array.isArray(maybeQuestion) &&
78
+ maybeQuestion != null);
79
+ }
80
+ function isPromptConstructor(prompt) {
81
+ return Boolean(prompt.prototype &&
82
+ 'run' in prompt.prototype &&
83
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
84
+ typeof prompt.prototype.run === 'function');
85
+ }
86
+ /**
87
+ * Base interface class other can inherits from
88
+ */
89
+ export default class PromptsRunner {
90
+ prompts;
91
+ answers = {};
92
+ process = EMPTY;
93
+ abortController = new AbortController();
94
+ opt;
95
+ constructor(prompts, opt = {}) {
96
+ this.opt = opt;
97
+ this.prompts = prompts;
98
+ }
99
+ async run(questions, answers) {
100
+ this.abortController = new AbortController();
101
+ // Keep global reference to the answers
102
+ this.answers = typeof answers === 'object' ? { ...answers } : {};
103
+ let obs;
104
+ if (isQuestionArray(questions)) {
105
+ obs = from(questions);
106
+ }
107
+ else if (isObservable(questions)) {
108
+ obs = questions;
109
+ }
110
+ else if (isQuestionMap(questions)) {
111
+ // Case: Called with a set of { name: question }
112
+ obs = from(Object.entries(questions).map(([name, question]) => {
113
+ return Object.assign({}, question, { name });
114
+ }));
115
+ }
116
+ else {
117
+ // Case: Called with a single question config
118
+ obs = from([questions]);
119
+ }
120
+ this.process = obs.pipe(concatMap((question) => of(question).pipe(concatMap((question) => from(this.shouldRun(question).then((shouldRun) => {
121
+ if (shouldRun) {
122
+ return question;
123
+ }
124
+ return;
125
+ })).pipe(filter((val) => val != null))), concatMap((question) => defer(() => from(this.fetchAnswer(question)))))));
126
+ return lastValueFrom(this.process.pipe(reduce((answersObj, answer) => {
127
+ _.set(answersObj, answer.name, answer.answer);
128
+ return answersObj;
129
+ }, this.answers)))
130
+ .then(() => this.answers)
131
+ .finally(() => this.close());
132
+ }
133
+ prepareQuestion = async (question) => {
134
+ const [message, defaultValue, resolvedChoices] = await Promise.all([
135
+ fetchAsyncQuestionProperty(question, 'message', this.answers),
136
+ fetchAsyncQuestionProperty(question, 'default', this.answers),
137
+ fetchAsyncQuestionProperty(question, 'choices', this.answers),
138
+ ]);
139
+ let choices;
140
+ if (Array.isArray(resolvedChoices)) {
141
+ choices = resolvedChoices.map((choice) => {
142
+ const choiceObj = typeof choice !== 'object' || choice == null
143
+ ? { name: choice, value: choice }
144
+ : {
145
+ ...choice,
146
+ value: 'value' in choice
147
+ ? choice.value
148
+ : 'name' in choice
149
+ ? choice.name
150
+ : undefined,
151
+ };
152
+ if ('value' in choiceObj && Array.isArray(defaultValue)) {
153
+ // Add checked to question for backward compatibility. default was supported as alternative of per choice checked.
154
+ return {
155
+ checked: defaultValue.includes(choiceObj.value),
156
+ ...choiceObj,
157
+ };
158
+ }
159
+ return choiceObj;
160
+ });
161
+ }
162
+ // Wrap the validate function to pass answers as second parameter for backward compatibility
163
+ const wrappedQuestion = Object.assign({}, question, {
164
+ message,
165
+ default: defaultValue,
166
+ choices,
167
+ type: question.type in this.prompts ? question.type : 'input',
168
+ });
169
+ if (question.validate) {
170
+ const originalValidate = question.validate;
171
+ wrappedQuestion.validate = (value) => {
172
+ return originalValidate(value, this.answers);
173
+ };
174
+ }
175
+ return wrappedQuestion;
176
+ };
177
+ fetchAnswer = async (rawQuestion) => {
178
+ const question = await this.prepareQuestion(rawQuestion);
179
+ const prompt = this.prompts[question.type];
180
+ if (prompt == null) {
181
+ throw new Error(`Prompt for type ${question.type} not found`);
182
+ }
183
+ let cleanupSignal;
184
+ const promptFn = isPromptConstructor(prompt)
185
+ ? (q, opt) => new Promise((resolve, reject) => {
186
+ const { signal } = opt;
187
+ if (signal.aborted) {
188
+ reject(new AbortPromptError({ cause: signal.reason }));
189
+ return;
190
+ }
191
+ const rl = readline.createInterface(setupReadlineOptions(opt));
192
+ /**
193
+ * Handle the ^C exit
194
+ */
195
+ const onForceClose = () => {
196
+ this.close();
197
+ process.kill(process.pid, 'SIGINT');
198
+ console.log('');
199
+ };
200
+ const onClose = () => {
201
+ process.removeListener('exit', onForceClose);
202
+ rl.removeListener('SIGINT', onForceClose);
203
+ rl.setPrompt('');
204
+ rl.output.unmute();
205
+ rl.output.write(cursorShow);
206
+ rl.output.end();
207
+ rl.close();
208
+ };
209
+ // Make sure new prompt start on a newline when closing
210
+ process.on('exit', onForceClose);
211
+ rl.on('SIGINT', onForceClose);
212
+ const activePrompt = new prompt(q, rl, this.answers);
213
+ const cleanup = () => {
214
+ onClose();
215
+ cleanupSignal?.();
216
+ };
217
+ const abort = () => {
218
+ reject(new AbortPromptError({ cause: signal.reason }));
219
+ cleanup();
220
+ };
221
+ signal.addEventListener('abort', abort);
222
+ cleanupSignal = () => {
223
+ signal.removeEventListener('abort', abort);
224
+ cleanupSignal = undefined;
225
+ };
226
+ activePrompt.run().then(resolve, reject).finally(cleanup);
227
+ })
228
+ : prompt;
229
+ let cleanupModuleSignal;
230
+ const { signal: moduleSignal } = this.opt;
231
+ if (moduleSignal?.aborted) {
232
+ this.abortController.abort(moduleSignal.reason);
233
+ }
234
+ else if (moduleSignal) {
235
+ const abort = () => this.abortController.abort(moduleSignal.reason);
236
+ moduleSignal.addEventListener('abort', abort);
237
+ cleanupModuleSignal = () => {
238
+ moduleSignal.removeEventListener('abort', abort);
239
+ };
240
+ }
241
+ const { filter = (value) => value } = question;
242
+ const { signal } = this.abortController;
243
+ return promptFn(question, { ...this.opt, signal })
244
+ .then((answer) => ({
245
+ name: question.name,
246
+ answer: filter(answer, this.answers),
247
+ }))
248
+ .finally(() => {
249
+ cleanupSignal?.();
250
+ cleanupModuleSignal?.();
251
+ });
252
+ };
253
+ /**
254
+ * Close the interface and cleanup listeners
255
+ */
256
+ close = () => {
257
+ this.abortController.abort();
258
+ };
259
+ shouldRun = async (question) => {
260
+ if (question.askAnswered !== true &&
261
+ _.get(this.answers, question.name) !== undefined) {
262
+ return false;
263
+ }
264
+ const { when } = question;
265
+ if (typeof when === 'function') {
266
+ const shouldRun = await runAsync(when)(this.answers);
267
+ return Boolean(shouldRun);
268
+ }
269
+ return when !== false;
270
+ };
271
+ }
@@ -0,0 +1,13 @@
1
+ import { Answers, Question } from '../types.ts';
2
+ type RendererFunction<A extends Answers = Answers> = (question: Question<A>) => string;
3
+ type SkippedRendererType<A extends Answers = Answers> = {
4
+ [key: string]: RendererFunction<A>;
5
+ confirm: RendererFunction<A>;
6
+ select: RendererFunction<A>;
7
+ checkbox: RendererFunction<A>;
8
+ editor: RendererFunction<A>;
9
+ password: RendererFunction<A>;
10
+ default: RendererFunction<A>;
11
+ };
12
+ declare const SkippedRenderer: SkippedRendererType;
13
+ export default SkippedRenderer;
@@ -0,0 +1,57 @@
1
+ import { makeTheme } from '@inquirer/core';
2
+ const theme = makeTheme();
3
+ const prefix = typeof theme.prefix === 'string' ? theme.prefix : theme.prefix.idle;
4
+ const SkippedRenderer = {
5
+ confirm: (question) => {
6
+ const defaultVal = question.default;
7
+ const answerText = defaultVal === true ? 'Yes' : defaultVal === false ? 'No' : '';
8
+ return renderLine(question.message.toString(), answerText);
9
+ },
10
+ select: (question) => {
11
+ const defaultVal = question.default;
12
+ let answerText = String(defaultVal);
13
+ if (question.choices && defaultVal !== undefined) {
14
+ const selectedChoice = question.choices.find((c) => c.value === defaultVal);
15
+ answerText = selectedChoice ? selectedChoice.name : String(defaultVal);
16
+ }
17
+ return renderLine(question.message.toString(), answerText);
18
+ },
19
+ checkbox: (question) => {
20
+ const defaultVal = question.default;
21
+ let answerText = '';
22
+ if (Array.isArray(defaultVal) && question.choices) {
23
+ const selectedNames = question.choices
24
+ .filter((c) => defaultVal.includes(c.value))
25
+ .map((c) => c.name);
26
+ answerText = selectedNames.join(', ');
27
+ }
28
+ else if (defaultVal !== undefined) {
29
+ answerText = String(defaultVal);
30
+ }
31
+ return renderLine(question.message.toString(), answerText);
32
+ },
33
+ editor: (question) => {
34
+ const answerText = question.default !== undefined ? '[Default Content]' : '';
35
+ return renderLine(question.message.toString(), answerText);
36
+ },
37
+ password: (question) => {
38
+ const defaultVal = question.default;
39
+ let answerText = '';
40
+ if (defaultVal !== undefined) {
41
+ answerText = '[PASSWORD SET]';
42
+ }
43
+ return renderLine(question.message.toString(), answerText);
44
+ },
45
+ default: (question) => {
46
+ const answerText = question.default !== undefined ? String(question.default) : '';
47
+ return renderLine(question.message.toString(), answerText);
48
+ },
49
+ list: (question) => SkippedRenderer.select(question),
50
+ rawlist: (question) => SkippedRenderer.select(question),
51
+ input: (question) => SkippedRenderer.default(question),
52
+ number: (question) => SkippedRenderer.default(question),
53
+ };
54
+ function renderLine(message, answerText) {
55
+ return theme.style.help(`${prefix} ${message} ${answerText}`);
56
+ }
57
+ export default SkippedRenderer;
package/package.json ADDED
@@ -0,0 +1,96 @@
1
+ {
2
+ "name": "@depup/inquirer",
3
+ "version": "13.3.0-depup.0",
4
+ "description": "A collection of common interactive command line user interfaces.",
5
+ "keywords": [
6
+ "answer",
7
+ "answers",
8
+ "ask",
9
+ "base",
10
+ "cli",
11
+ "command",
12
+ "command-line",
13
+ "confirm",
14
+ "enquirer",
15
+ "generate",
16
+ "generator",
17
+ "hyper",
18
+ "input",
19
+ "inquire",
20
+ "inquirer",
21
+ "interface",
22
+ "iterm",
23
+ "javascript",
24
+ "menu",
25
+ "node",
26
+ "nodejs",
27
+ "prompt",
28
+ "promptly",
29
+ "prompts",
30
+ "question",
31
+ "readline",
32
+ "scaffold",
33
+ "scaffolder",
34
+ "scaffolding",
35
+ "stdin",
36
+ "stdout",
37
+ "terminal",
38
+ "tty",
39
+ "ui",
40
+ "yeoman",
41
+ "yo",
42
+ "zsh"
43
+ ],
44
+ "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/inquirer/README.md",
45
+ "license": "MIT",
46
+ "author": "Simon Boudrias <admin@simonboudrias.com>",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/SBoudrias/Inquirer.js.git"
50
+ },
51
+ "files": [
52
+ "dist"
53
+ ],
54
+ "type": "module",
55
+ "sideEffects": false,
56
+ "exports": {
57
+ ".": {
58
+ "types": "./dist/index.d.ts",
59
+ "default": "./dist/index.js"
60
+ },
61
+ "./package.json": "./package.json"
62
+ },
63
+ "publishConfig": {
64
+ "access": "public"
65
+ },
66
+ "scripts": {
67
+ "tsc": "tsc"
68
+ },
69
+ "dependencies": {
70
+ "@inquirer/ansi": "^2.0.3",
71
+ "@inquirer/core": "^11.1.5",
72
+ "@inquirer/prompts": "^8.3.0",
73
+ "@inquirer/type": "^4.0.3",
74
+ "mute-stream": "^3.0.0",
75
+ "run-async": "^4.0.6",
76
+ "rxjs": "^7.8.2"
77
+ },
78
+ "devDependencies": {
79
+ "@types/mute-stream": "^0.0.4",
80
+ "typescript": "^5.9.3"
81
+ },
82
+ "peerDependencies": {
83
+ "@types/node": ">=18"
84
+ },
85
+ "peerDependenciesMeta": {
86
+ "@types/node": {
87
+ "optional": true
88
+ }
89
+ },
90
+ "engines": {
91
+ "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0"
92
+ },
93
+ "main": "./dist/index.js",
94
+ "types": "./dist/index.d.ts",
95
+ "gitHead": "526eca2e64853510821ffd457561840ec0cbfb93"
96
+ }