inquirerer 3.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # inquirerer
2
2
 
3
3
  <p align="center" width="100%">
4
- <img height="90" src="https://raw.githubusercontent.com/constructive-io/dev-utils/refs/heads/main/docs/img/genomic.svg" />
4
+ <img height="90" src="https://raw.githubusercontent.com/constructive-io/dev-utils/refs/heads/main/docs/img/inquirerer.svg" />
5
5
  </p>
6
6
 
7
7
  <p align="center" width="100%">
@@ -11,36 +11,10 @@
11
11
  <a href="https://github.com/constructive-io/dev-utils/blob/main/LICENSE">
12
12
  <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
13
  </a>
14
- <a href="https://www.npmjs.com/package/inquirerer"><img height="20" src="https://img.shields.io/npm/dt/inquirerer"></a>
15
14
  <a href="https://www.npmjs.com/package/inquirerer"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/dev-utils?filename=packages%2Finquirerer%2Fpackage.json"></a>
16
15
  </p>
17
16
 
18
- > **Note:** This package has been renamed to [`genomic`](https://www.npmjs.com/package/genomic). Please migrate to `genomic` for the latest features and updates.
19
-
20
- A powerful, TypeScript-first library for building beautiful command-line interfaces. Create interactive CLI tools with ease using intuitive prompts, validation, and rich user experiences.
21
-
22
- ## Migration to genomic
23
-
24
- This package is now maintained as `genomic`. To migrate:
25
-
26
- ```bash
27
- npm uninstall inquirerer
28
- npm install genomic
29
- ```
30
-
31
- Then update your imports:
32
-
33
- ```typescript
34
- // Before
35
- import { Inquirerer, InquirererOptions } from 'inquirerer';
36
-
37
- // After
38
- import { Prompter, PrompterOptions } from 'genomic';
39
- ```
40
-
41
- The API is the same, only the class names have changed:
42
- - `Inquirerer` -> `Prompter`
43
- - `InquirererOptions` -> `PrompterOptions`
17
+ A powerful, TypeScript-first library for building beautiful command-line interfaces.Create interactive CLI tools with ease using intuitive prompts, validation, and rich user experiences.
44
18
 
45
19
  ## Installation
46
20
 
@@ -50,22 +24,54 @@ npm install inquirerer
50
24
 
51
25
  ## Features
52
26
 
53
- - **CLI Builder** - Build command-line utilities fast
54
- - **Multiple Question Types** - Support for text, autocomplete, checkbox, and confirm questions
55
- - **Non-Interactive Mode** - Fallback to defaults for CI/CD environments, great for testing
56
- - **Smart Validation** - Built-in pattern matching, custom validators, and sanitizers
57
- - **Conditional Logic** - Show/hide questions based on previous answers
58
- - **Interactive UX** - Fuzzy search, keyboard navigation, and visual feedback
59
- - **Dynamic Defaults** - Auto-populate defaults from git config, date/time, or custom resolvers
27
+ - 🔌 **CLI Builder** - Build command-line utilties fast
28
+ - 🖊 **Multiple Question Types** - Support for text, autocomplete, checkbox, and confirm questions
29
+ - 🤖 **Non-Interactive Mode** - Fallback to defaults for CI/CD environments, great for testing
30
+ - ✅ **Smart Validation** - Built-in pattern matching, custom validators, and sanitizers
31
+ - 🔀 **Conditional Logic** - Show/hide questions based on previous answers
32
+ - 🎨 **Interactive UX** - Fuzzy search, keyboard navigation, and visual feedback
33
+ - 🔄 **Dynamic Defaults** - Auto-populate defaults from git config, date/time, or custom resolvers
34
+
35
+ ## Table of Contents
36
+
37
+ - [Quick Start](#quick-start)
38
+ - [Core Concepts](#core-concepts)
39
+ - [TypeScript Support](#typescript-support)
40
+ - [Question Types](#question-types)
41
+ - [Non-Interactive Mode](#non-interactive-mode)
42
+ - [API Reference](#api-reference)
43
+ - [Inquirerer Class](#inquirerer-class)
44
+ - [Question Types](#question-types-1)
45
+ - [Text Question](#text-question)
46
+ - [Number Question](#number-question)
47
+ - [Confirm Question](#confirm-question)
48
+ - [List Question](#list-question)
49
+ - [Autocomplete Question](#autocomplete-question)
50
+ - [Checkbox Question](#checkbox-question)
51
+ - [Advanced Question Options](#advanced-question-options)
52
+ - [Positional Arguments](#positional-arguments)
53
+ - [Alias](#alias)
54
+ - [Real-World Examples](#real-world-examples)
55
+ - [Project Setup Wizard](#project-setup-wizard)
56
+ - [Configuration Builder](#configuration-builder)
57
+ - [CLI with Commander Integration](#cli-with-commander-integration)
58
+ - [Dynamic Dependencies](#dynamic-dependencies)
59
+ - [Custom Validation](#custom-validation)
60
+ - [Dynamic Defaults with Resolvers](#dynamic-defaults-with-resolvers)
61
+ - [Built-in Resolvers](#built-in-resolvers)
62
+ - [Custom Resolvers](#custom-resolvers)
63
+ - [Resolver Examples](#resolver-examples)
64
+ - [CLI Helper](#cli-helper)
65
+ - [Developing](#developing)
60
66
 
61
67
  ## Quick Start
62
68
 
63
69
  ```typescript
64
70
  import { Inquirerer } from 'inquirerer';
65
71
 
66
- const inquirerer = new Inquirerer();
72
+ const prompter = new Inquirerer();
67
73
 
68
- const answers = await inquirerer.prompt({}, [
74
+ const answers = await prompter.prompt({}, [
69
75
  {
70
76
  type: 'text',
71
77
  name: 'username',
@@ -112,7 +118,7 @@ interface UserConfig {
112
118
  newsletter: boolean;
113
119
  }
114
120
 
115
- const answers = await inquirerer.prompt<UserConfig>({}, questions);
121
+ const answers = await prompter.prompt<UserConfig>({}, questions);
116
122
  // answers is typed as UserConfig
117
123
  ```
118
124
 
@@ -125,6 +131,7 @@ interface BaseQuestion {
125
131
  name: string; // Property name in result object
126
132
  type: string; // Question type
127
133
  _?: boolean; // Mark as positional argument (can be passed without --name flag)
134
+ alias?: string | string[]; // Short flag alias(es) for CLI (e.g., 'w' for --workspace)
128
135
  message?: string; // Prompt message to display
129
136
  description?: string; // Additional context
130
137
  default?: any; // Default value
@@ -145,7 +152,7 @@ interface BaseQuestion {
145
152
  When running in CI/CD or without a TTY, inquirerer automatically falls back to default values:
146
153
 
147
154
  ```typescript
148
- const inquirerer = new Inquirerer({
155
+ const prompter = new Inquirerer({
149
156
  noTty: true, // Force non-interactive mode
150
157
  useDefaults: true // Use defaults without prompting
151
158
  });
@@ -168,7 +175,7 @@ interface InquirererOptions {
168
175
  resolverRegistry?: DefaultResolverRegistry; // Custom resolver registry
169
176
  }
170
177
 
171
- const inquirerer = new Inquirerer(options);
178
+ const prompter = new Inquirerer(options);
172
179
  ```
173
180
 
174
181
  #### Methods
@@ -185,13 +192,1056 @@ close(): void
185
192
  exit(): void
186
193
  ```
187
194
 
188
- ## Full Documentation
195
+ #### Managing Multiple Instances
196
+
197
+ When working with multiple `Prompter` instances that share the same input stream (typically `process.stdin`), only one instance should be actively prompting at a time. Each instance attaches its own keyboard listener, so having multiple active instances will cause duplicate or unexpected keypress behavior.
198
+
199
+ **Best practices:**
200
+
201
+ 1. **Reuse a single instance** - Create one `Prompter` instance and reuse it for all prompts:
202
+ ```typescript
203
+ const prompter = new Inquirerer();
204
+
205
+ // Use the same instance for multiple prompt sessions
206
+ const answers1 = await prompter.prompt({}, questions1);
207
+ const answers2 = await prompter.prompt({}, questions2);
208
+
209
+ prompter.close(); // Clean up when done
210
+ ```
211
+
212
+ 2. **Close before creating another** - If you need separate instances, close the first before using the second:
213
+ ```typescript
214
+ const prompter1 = new Prompter();
215
+ const answers1 = await prompter1.prompt({}, questions1);
216
+ prompter1.close(); // Important: close before creating another
217
+
218
+ const prompter2 = new Prompter();
219
+ const answers2 = await prompter2.prompt({}, questions2);
220
+ prompter2.close();
221
+ ```
222
+
223
+ ### Question Types
224
+
225
+ #### Text Question
226
+
227
+ Collect string input from users.
228
+
229
+ ```typescript
230
+ {
231
+ type: 'text',
232
+ name: 'projectName',
233
+ message: 'What is your project name?',
234
+ default: 'my-app',
235
+ required: true,
236
+ pattern: '^[a-z0-9-]+$', // Regex validation
237
+ validate: (input) => {
238
+ if (input.length < 3) {
239
+ return { success: false, reason: 'Name must be at least 3 characters' };
240
+ }
241
+ return true;
242
+ }
243
+ }
244
+ ```
245
+
246
+ #### Number Question
247
+
248
+ Collect numeric input.
249
+
250
+ ```typescript
251
+ {
252
+ type: 'number',
253
+ name: 'port',
254
+ message: 'Which port to use?',
255
+ default: 3000,
256
+ validate: (input) => {
257
+ if (input < 1 || input > 65535) {
258
+ return { success: false, reason: 'Port must be between 1 and 65535' };
259
+ }
260
+ return true;
261
+ }
262
+ }
263
+ ```
264
+
265
+ #### Confirm Question
266
+
267
+ Yes/no questions.
268
+
269
+ ```typescript
270
+ {
271
+ type: 'confirm',
272
+ name: 'useTypeScript',
273
+ message: 'Use TypeScript?',
274
+ default: true // Default to 'yes'
275
+ }
276
+ ```
277
+
278
+ #### List Question
279
+
280
+ Select one option from a list (no search).
281
+
282
+ ```typescript
283
+ {
284
+ type: 'list',
285
+ name: 'license',
286
+ message: 'Choose a license',
287
+ options: ['MIT', 'Apache-2.0', 'GPL-3.0', 'BSD-3-Clause'],
288
+ default: 'MIT',
289
+ maxDisplayLines: 5
290
+ }
291
+ ```
292
+
293
+ #### Autocomplete Question
294
+
295
+ Select with fuzzy search capabilities.
296
+
297
+ ```typescript
298
+ {
299
+ type: 'autocomplete',
300
+ name: 'framework',
301
+ message: 'Choose your framework',
302
+ options: [
303
+ { name: 'React', value: 'react' },
304
+ { name: 'Vue.js', value: 'vue' },
305
+ { name: 'Angular', value: 'angular' },
306
+ { name: 'Svelte', value: 'svelte' }
307
+ ],
308
+ allowCustomOptions: true, // Allow user to enter custom value
309
+ maxDisplayLines: 8
310
+ }
311
+ ```
312
+
313
+ #### Checkbox Question
314
+
315
+ Multi-select with search.
316
+
317
+ ```typescript
318
+ {
319
+ type: 'checkbox',
320
+ name: 'features',
321
+ message: 'Select features to include',
322
+ options: [
323
+ 'Authentication',
324
+ 'Database',
325
+ 'API Routes',
326
+ 'Testing',
327
+ 'Documentation'
328
+ ],
329
+ default: ['Authentication', 'API Routes'],
330
+ returnFullResults: false, // Only return selected items
331
+ required: true
332
+ }
333
+ ```
334
+
335
+ With `returnFullResults: true`, returns all options with selection status:
336
+
337
+ ```typescript
338
+ [
339
+ { name: 'Authentication', value: 'Authentication', selected: true },
340
+ { name: 'Database', value: 'Database', selected: false },
341
+ // ...
342
+ ]
343
+ ```
344
+
345
+ ### Advanced Question Options
346
+
347
+ #### Custom Validation
348
+
349
+ ```typescript
350
+ {
351
+ type: 'text',
352
+ name: 'email',
353
+ message: 'Enter your email',
354
+ pattern: '^[^@]+@[^@]+\\.[^@]+$',
355
+ validate: (email, answers) => {
356
+ // Custom async validation possible
357
+ if (email.endsWith('@example.com')) {
358
+ return {
359
+ success: false,
360
+ reason: 'Please use a real email address'
361
+ };
362
+ }
363
+ return { success: true };
364
+ }
365
+ }
366
+ ```
367
+
368
+ #### Value Sanitization
369
+
370
+ ```typescript
371
+ {
372
+ type: 'text',
373
+ name: 'tags',
374
+ message: 'Enter tags (comma-separated)',
375
+ sanitize: (input) => {
376
+ return input.split(',').map(tag => tag.trim());
377
+ }
378
+ }
379
+ ```
380
+
381
+ #### Conditional Questions
382
+
383
+ ```typescript
384
+ const questions: Question[] = [
385
+ {
386
+ type: 'confirm',
387
+ name: 'useDatabase',
388
+ message: 'Do you need a database?',
389
+ default: false
390
+ },
391
+ {
392
+ type: 'list',
393
+ name: 'database',
394
+ message: 'Which database?',
395
+ options: ['PostgreSQL', 'MySQL', 'MongoDB', 'SQLite'],
396
+ when: (answers) => answers.useDatabase === true // Only show if useDatabase is true
397
+ }
398
+ ];
399
+ ```
400
+
401
+ #### Question Dependencies
402
+
403
+ Ensure questions appear in the correct order:
404
+
405
+ ```typescript
406
+ [
407
+ {
408
+ type: 'checkbox',
409
+ name: 'services',
410
+ message: 'Select services',
411
+ options: ['Auth', 'Storage', 'Functions']
412
+ },
413
+ {
414
+ type: 'text',
415
+ name: 'authProvider',
416
+ message: 'Which auth provider?',
417
+ dependsOn: ['services'], // Wait for services question
418
+ when: (answers) => {
419
+ const selected = answers.services.find(s => s.name === 'Auth');
420
+ return selected?.selected === true;
421
+ }
422
+ }
423
+ ]
424
+ ```
425
+
426
+ ### Positional Arguments
427
+
428
+ The `_` property allows you to name positional parameters, enabling users to pass values without flags. This is useful for CLI tools where the first few arguments have obvious meanings.
429
+
430
+ #### Basic Usage
431
+
432
+ ```typescript
433
+ const questions: Question[] = [
434
+ {
435
+ _: true,
436
+ name: 'database',
437
+ type: 'text',
438
+ message: 'Database name',
439
+ required: true
440
+ }
441
+ ];
442
+
443
+ const argv = minimist(process.argv.slice(2));
444
+ const result = await prompter.prompt(argv, questions);
445
+ ```
446
+
447
+ Now users can run either:
448
+ ```bash
449
+ node myprogram.js mydb1
450
+ # or equivalently:
451
+ node myprogram.js --database mydb1
452
+ ```
453
+
454
+ #### Multiple Positional Arguments
455
+
456
+ Positional arguments are assigned in declaration order:
457
+
458
+ ```typescript
459
+ const questions: Question[] = [
460
+ { _: true, name: 'source', type: 'text', message: 'Source file' },
461
+ { name: 'verbose', type: 'confirm', default: false },
462
+ { _: true, name: 'destination', type: 'text', message: 'Destination file' }
463
+ ];
464
+
465
+ // Running: node copy.js input.txt output.txt --verbose
466
+ // Results in: { source: 'input.txt', destination: 'output.txt', verbose: true }
467
+ ```
468
+
469
+ #### Named Arguments Take Precedence
470
+
471
+ When both positional and named arguments are provided, named arguments win and the positional slot is preserved for the next positional question:
472
+
473
+ ```typescript
474
+ const questions: Question[] = [
475
+ { _: true, name: 'foo', type: 'text' },
476
+ { _: true, name: 'bar', type: 'text' },
477
+ { _: true, name: 'baz', type: 'text' }
478
+ ];
479
+
480
+ // Running: node myprogram.js pos1 pos2 --bar named-bar
481
+ // Results in: { foo: 'pos1', bar: 'named-bar', baz: 'pos2' }
482
+ ```
483
+
484
+ In this example, `bar` gets its value from the named flag, so the two positional values go to `foo` and `baz`.
485
+
486
+ ### Alias
487
+
488
+ The `alias` property allows you to define short flag alternatives for question names, making CLI usage more convenient. Users can pass values using either the full name or any defined alias.
489
+
490
+ #### Basic Usage
491
+
492
+ ```typescript
493
+ const questions: Question[] = [
494
+ {
495
+ name: 'workspace',
496
+ type: 'confirm',
497
+ alias: 'w',
498
+ message: 'Create workspace?'
499
+ },
500
+ {
501
+ name: 'outputDir',
502
+ type: 'text',
503
+ alias: 'o',
504
+ message: 'Output directory',
505
+ default: './dist'
506
+ }
507
+ ];
508
+
509
+ const argv = minimist(process.argv.slice(2));
510
+ const result = await prompter.prompt(argv, questions);
511
+ ```
512
+
513
+ Now users can run either:
514
+ ```bash
515
+ node myprogram.js --workspace --outputDir ./build
516
+ # or equivalently:
517
+ node myprogram.js -w -o ./build
518
+ ```
519
+
520
+ #### Multiple Aliases
521
+
522
+ You can define multiple aliases for a single question using an array:
523
+
524
+ ```typescript
525
+ {
526
+ name: 'verbose',
527
+ type: 'confirm',
528
+ alias: ['v', 'V'], // Both -v and -V work
529
+ message: 'Enable verbose output?'
530
+ }
531
+ ```
532
+
533
+ #### Alias Priority
534
+
535
+ When both the main name and an alias are provided, the main name takes precedence:
536
+
537
+ ```typescript
538
+ // Running: node myprogram.js --workspace --w=false
539
+ // Results in: { workspace: true } (--workspace wins)
540
+ ```
541
+
542
+ When multiple aliases are provided in argv, the first alias in the definition order is used:
543
+
544
+ ```typescript
545
+ {
546
+ name: 'workspace',
547
+ type: 'text',
548
+ alias: ['w', 'ws']
549
+ }
550
+
551
+ // Running: node myprogram.js -w first --ws second
552
+ // Results in: { workspace: 'first' } (-w is checked first)
553
+ ```
554
+
555
+ #### Positional with Options
556
+
557
+ Positional arguments work with list, autocomplete, and checkbox questions. The value is mapped through the options:
558
+
559
+ ```typescript
560
+ const questions: Question[] = [
561
+ {
562
+ _: true,
563
+ name: 'framework',
564
+ type: 'list',
565
+ options: [
566
+ { name: 'React', value: 'react' },
567
+ { name: 'Vue', value: 'vue' }
568
+ ]
569
+ }
570
+ ];
571
+
572
+ // Running: node setup.js React
573
+ // Results in: { framework: 'react' }
574
+ ```
575
+
576
+ ## Real-World Examples
577
+
578
+ ### Project Setup Wizard
579
+
580
+ ```typescript
581
+ import { Inquirerer, Question } from 'inquirerer';
582
+ import minimist from 'minimist';
583
+
584
+ const argv = minimist(process.argv.slice(2));
585
+ const prompter = new Inquirerer();
586
+
587
+ const questions: Question[] = [
588
+ {
589
+ type: 'text',
590
+ name: 'projectName',
591
+ message: 'Project name',
592
+ required: true,
593
+ pattern: '^[a-z0-9-]+$'
594
+ },
595
+ {
596
+ type: 'text',
597
+ name: 'description',
598
+ message: 'Project description',
599
+ default: 'My awesome project'
600
+ },
601
+ {
602
+ type: 'confirm',
603
+ name: 'typescript',
604
+ message: 'Use TypeScript?',
605
+ default: true
606
+ },
607
+ {
608
+ type: 'autocomplete',
609
+ name: 'framework',
610
+ message: 'Choose a framework',
611
+ options: ['React', 'Vue', 'Svelte', 'None'],
612
+ default: 'React'
613
+ },
614
+ {
615
+ type: 'checkbox',
616
+ name: 'tools',
617
+ message: 'Additional tools',
618
+ options: ['ESLint', 'Prettier', 'Jest', 'Husky'],
619
+ default: ['ESLint', 'Prettier']
620
+ }
621
+ ];
622
+
623
+ const config = await prompter.prompt(argv, questions);
624
+ console.log('Creating project with:', config);
625
+ ```
626
+
627
+ Run interactively:
628
+ ```bash
629
+ node setup.js
630
+ ```
631
+
632
+ Or with CLI args:
633
+ ```bash
634
+ node setup.js --projectName=my-app --typescript --framework=React
635
+ ```
636
+
637
+ ### Configuration Builder
638
+
639
+ ```typescript
640
+ interface AppConfig {
641
+ port: number;
642
+ host: string;
643
+ ssl: boolean;
644
+ sslCert?: string;
645
+ sslKey?: string;
646
+ database: string;
647
+ logLevel: string;
648
+ }
649
+
650
+ const questions: Question[] = [
651
+ {
652
+ type: 'number',
653
+ name: 'port',
654
+ message: 'Server port',
655
+ default: 3000,
656
+ validate: (port) => port > 0 && port < 65536
657
+ },
658
+ {
659
+ type: 'text',
660
+ name: 'host',
661
+ message: 'Server host',
662
+ default: '0.0.0.0'
663
+ },
664
+ {
665
+ type: 'confirm',
666
+ name: 'ssl',
667
+ message: 'Enable SSL?',
668
+ default: false
669
+ },
670
+ {
671
+ type: 'text',
672
+ name: 'sslCert',
673
+ message: 'SSL certificate path',
674
+ when: (answers) => answers.ssl === true,
675
+ required: true
676
+ },
677
+ {
678
+ type: 'text',
679
+ name: 'sslKey',
680
+ message: 'SSL key path',
681
+ when: (answers) => answers.ssl === true,
682
+ required: true
683
+ },
684
+ {
685
+ type: 'list',
686
+ name: 'database',
687
+ message: 'Database type',
688
+ options: ['PostgreSQL', 'MySQL', 'SQLite'],
689
+ default: 'PostgreSQL'
690
+ },
691
+ {
692
+ type: 'list',
693
+ name: 'logLevel',
694
+ message: 'Log level',
695
+ options: ['error', 'warn', 'info', 'debug'],
696
+ default: 'info'
697
+ }
698
+ ];
699
+
700
+ const config = await prompter.prompt<AppConfig>(argv, questions);
701
+
702
+ // Write config to file
703
+ fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
704
+ ```
705
+
706
+ ### CLI with Commander Integration
707
+
708
+ ```typescript
709
+ import { CLI, CommandHandler } from 'inquirerer';
710
+ import { Question } from 'inquirerer';
711
+
712
+ const handler: CommandHandler = async (argv, prompter, options) => {
713
+ const questions: Question[] = [
714
+ {
715
+ type: 'text',
716
+ name: 'name',
717
+ message: 'What is your name?',
718
+ required: true
719
+ },
720
+ {
721
+ type: 'number',
722
+ name: 'age',
723
+ message: 'What is your age?',
724
+ validate: (age) => age >= 0 && age <= 120
725
+ }
726
+ ];
727
+
728
+ const answers = await prompter.prompt(argv, questions);
729
+ console.log('Hello,', answers.name);
730
+ };
731
+
732
+ const cli = new CLI(handler, {
733
+ version: 'myapp@1.0.0',
734
+ minimistOpts: {
735
+ alias: {
736
+ n: 'name',
737
+ a: 'age',
738
+ v: 'version'
739
+ }
740
+ }
741
+ });
742
+
743
+ await cli.run();
744
+ ```
745
+
746
+ ### Dynamic Dependencies
747
+
748
+ ```typescript
749
+ const questions: Question[] = [
750
+ {
751
+ type: 'checkbox',
752
+ name: 'cloud',
753
+ message: 'Select cloud services',
754
+ options: ['AWS', 'Azure', 'GCP'],
755
+ returnFullResults: true
756
+ },
757
+ {
758
+ type: 'text',
759
+ name: 'awsRegion',
760
+ message: 'AWS Region',
761
+ dependsOn: ['cloud'],
762
+ when: (answers) => {
763
+ const aws = answers.cloud?.find(c => c.name === 'AWS');
764
+ return aws?.selected === true;
765
+ },
766
+ default: 'us-east-1'
767
+ },
768
+ {
769
+ type: 'text',
770
+ name: 'azureLocation',
771
+ message: 'Azure Location',
772
+ dependsOn: ['cloud'],
773
+ when: (answers) => {
774
+ const azure = answers.cloud?.find(c => c.name === 'Azure');
775
+ return azure?.selected === true;
776
+ },
777
+ default: 'eastus'
778
+ },
779
+ {
780
+ type: 'text',
781
+ name: 'gcpZone',
782
+ message: 'GCP Zone',
783
+ dependsOn: ['cloud'],
784
+ when: (answers) => {
785
+ const gcp = answers.cloud?.find(c => c.name === 'GCP');
786
+ return gcp?.selected === true;
787
+ },
788
+ default: 'us-central1-a'
789
+ }
790
+ ];
791
+
792
+ const config = await prompter.prompt({}, questions);
793
+ ```
794
+
795
+ ### Custom Validation
796
+
797
+ ```typescript
798
+ const questions: Question[] = [
799
+ {
800
+ type: 'text',
801
+ name: 'username',
802
+ message: 'Choose a username',
803
+ required: true,
804
+ pattern: '^[a-zA-Z0-9_]{3,20}$',
805
+ validate: async (username) => {
806
+ // Simulate API call to check availability
807
+ const available = await checkUsernameAvailability(username);
808
+ if (!available) {
809
+ return {
810
+ success: false,
811
+ reason: 'Username is already taken'
812
+ };
813
+ }
814
+ return { success: true };
815
+ }
816
+ },
817
+ {
818
+ type: 'text',
819
+ name: 'password',
820
+ message: 'Choose a password',
821
+ required: true,
822
+ validate: (password) => {
823
+ if (password.length < 8) {
824
+ return {
825
+ success: false,
826
+ reason: 'Password must be at least 8 characters'
827
+ };
828
+ }
829
+ if (!/[A-Z]/.test(password)) {
830
+ return {
831
+ success: false,
832
+ reason: 'Password must contain an uppercase letter'
833
+ };
834
+ }
835
+ if (!/[0-9]/.test(password)) {
836
+ return {
837
+ success: false,
838
+ reason: 'Password must contain a number'
839
+ };
840
+ }
841
+ return { success: true };
842
+ }
843
+ },
844
+ {
845
+ type: 'text',
846
+ name: 'confirmPassword',
847
+ message: 'Confirm password',
848
+ required: true,
849
+ dependsOn: ['password'],
850
+ validate: (confirm, answers) => {
851
+ if (confirm !== answers.password) {
852
+ return {
853
+ success: false,
854
+ reason: 'Passwords do not match'
855
+ };
856
+ }
857
+ return { success: true };
858
+ }
859
+ }
860
+ ];
861
+ ```
862
+
863
+ ## Dynamic Defaults with Resolvers
864
+
865
+ The `defaultFrom` feature allows you to automatically populate question defaults from dynamic sources like git configuration, environment variables, date/time values, or custom resolvers. This eliminates repetitive boilerplate code for common default values.
866
+
867
+ ### Quick Example
868
+
869
+ ```typescript
870
+ import { Inquirerer } from 'inquirerer';
871
+
872
+ const questions = [
873
+ {
874
+ type: 'text',
875
+ name: 'authorName',
876
+ message: 'Author name?',
877
+ defaultFrom: 'git.user.name' // Auto-fills from git config
878
+ },
879
+ {
880
+ type: 'text',
881
+ name: 'authorEmail',
882
+ message: 'Author email?',
883
+ defaultFrom: 'git.user.email' // Auto-fills from git config
884
+ },
885
+ {
886
+ type: 'text',
887
+ name: 'npmUser',
888
+ message: 'NPM username?',
889
+ defaultFrom: 'npm.whoami' // Auto-fills from npm whoami
890
+ },
891
+ {
892
+ type: 'text',
893
+ name: 'copyrightYear',
894
+ message: 'Copyright year?',
895
+ defaultFrom: 'date.year' // Auto-fills current year
896
+ }
897
+ ];
898
+
899
+ const prompter = new Inquirerer();
900
+ const answers = await prompter.prompt({}, questions);
901
+ ```
902
+
903
+ ### Built-in Resolvers
904
+
905
+ Prompter comes with several built-in resolvers ready to use:
906
+
907
+ #### Git Configuration
908
+
909
+ | Resolver | Description | Example Output |
910
+ |----------|-------------|----------------|
911
+ | `git.user.name` | Git global user name | `"John Doe"` |
912
+ | `git.user.email` | Git global user email | `"john@example.com"` |
913
+
914
+ #### NPM
915
+
916
+ | Resolver | Description | Example Output |
917
+ |----------|-------------|----------------|
918
+ | `npm.whoami` | Currently logged in npm user | `"johndoe"` |
189
919
 
190
- For complete documentation, examples, and advanced usage, please see the [`genomic` package documentation](https://www.npmjs.com/package/genomic).
920
+ #### Date & Time
191
921
 
192
- ## License
922
+ | Resolver | Description | Example Output |
923
+ |----------|-------------|----------------|
924
+ | `date.year` | Current year | `"2025"` |
925
+ | `date.month` | Current month (zero-padded) | `"11"` |
926
+ | `date.day` | Current day (zero-padded) | `"23"` |
927
+ | `date.iso` | ISO date (YYYY-MM-DD) | `"2025-11-23"` |
928
+ | `date.now` | ISO timestamp | `"2025-11-23T15:30:45.123Z"` |
929
+ | `date.timestamp` | Unix timestamp (ms) | `"1732375845123"` |
193
930
 
194
- MIT
931
+ #### Workspace (nearest package.json)
932
+
933
+ | Resolver | Description | Example Output |
934
+ |----------|-------------|----------------|
935
+ | `workspace.name` | Repo slug from `repository` URL (fallback: `package.json` `name`) | `"dev-utils"` |
936
+ | `workspace.repo.name` | Repo name from `repository` URL | `"dev-utils"` |
937
+ | `workspace.repo.organization` | Repo org/owner from `repository` URL | `"constructive-io"` |
938
+ | `workspace.organization.name` | Alias for `workspace.repo.organization` | `"constructive-io"` |
939
+ | `workspace.license` | License field from `package.json` | `"MIT"` |
940
+ | `workspace.author` | Author name from `package.json` | `"Constructive"` |
941
+ | `workspace.author.name` | Author name from `package.json` | `"Constructive"` |
942
+ | `workspace.author.email` | Author email from `package.json` | `"email@example.org"` |
943
+
944
+ ### Priority Order
945
+
946
+ When resolving default values, inquirerer follows this priority:
947
+
948
+ 1. **CLI Arguments** - Values passed via command line (highest priority)
949
+ 2. **`setFrom`** - Auto-set values (bypasses prompt entirely)
950
+ 3. **`defaultFrom`** - Dynamically resolved default values
951
+ 4. **`default`** - Static default values
952
+ 5. **`undefined`** - No default available
953
+
954
+ ```typescript
955
+ {
956
+ type: 'text',
957
+ name: 'author',
958
+ defaultFrom: 'git.user.name', // Try git first
959
+ default: 'Anonymous' // Fallback if git not configured
960
+ }
961
+ ```
962
+
963
+ ### `setFrom` vs `defaultFrom`
964
+
965
+ Both `setFrom` and `defaultFrom` use resolvers to get values, but they behave differently:
966
+
967
+ | Feature | `defaultFrom` | `setFrom` |
968
+ |---------|---------------|-----------|
969
+ | Sets value as | Default (user can override) | Final value (no prompt) |
970
+ | User prompted? | Yes, with pre-filled default | No, question is skipped |
971
+ | Use case | Suggested values | Auto-computed values |
972
+
973
+ **`defaultFrom`** - The resolved value becomes the default, but the user is still prompted and can change it:
974
+
975
+ ```typescript
976
+ {
977
+ type: 'text',
978
+ name: 'authorName',
979
+ message: 'Author name?',
980
+ defaultFrom: 'git.user.name' // User sees "Author name? [John Doe]" and can change it
981
+ }
982
+ ```
983
+
984
+ **`setFrom`** - The resolved value is set directly and the question is skipped entirely:
985
+
986
+ ```typescript
987
+ {
988
+ type: 'text',
989
+ name: 'year',
990
+ message: 'Copyright year?',
991
+ setFrom: 'date.year' // Automatically set to "2025", no prompt shown
992
+ }
993
+ ```
994
+
995
+ #### When to use each
996
+
997
+ Use `defaultFrom` when:
998
+ - The value is a suggestion the user might want to change
999
+ - User confirmation is desired
1000
+
1001
+ Use `setFrom` when:
1002
+ - The value should be computed automatically
1003
+ - No user input is needed (e.g., timestamps, computed fields)
1004
+ - You want to reduce the number of prompts
1005
+
1006
+ #### Combined example
1007
+
1008
+ ```typescript
1009
+ const questions = [
1010
+ {
1011
+ type: 'text',
1012
+ name: 'authorName',
1013
+ message: 'Author name?',
1014
+ defaultFrom: 'git.user.name' // User can override
1015
+ },
1016
+ {
1017
+ type: 'text',
1018
+ name: 'createdAt',
1019
+ setFrom: 'date.iso' // Auto-set, no prompt
1020
+ },
1021
+ {
1022
+ type: 'text',
1023
+ name: 'copyrightYear',
1024
+ setFrom: 'date.year' // Auto-set, no prompt
1025
+ }
1026
+ ];
1027
+
1028
+ // User only sees prompt for authorName
1029
+ // createdAt and copyrightYear are set automatically
1030
+ ```
1031
+
1032
+ ### Custom Resolvers
1033
+
1034
+ Register your own custom resolvers for project-specific needs:
1035
+
1036
+ ```typescript
1037
+ import { registerDefaultResolver } from 'inquirerer';
1038
+
1039
+ // Register a resolver for current directory name
1040
+ registerDefaultResolver('cwd.name', () => {
1041
+ return process.cwd().split('/').pop();
1042
+ });
1043
+
1044
+ // Register a resolver for environment variable
1045
+ registerDefaultResolver('env.user', () => {
1046
+ return process.env.USER;
1047
+ });
1048
+
1049
+ // Use in questions
1050
+ const questions = [
1051
+ {
1052
+ type: 'text',
1053
+ name: 'projectName',
1054
+ message: 'Project name?',
1055
+ defaultFrom: 'cwd.name',
1056
+ default: 'my-project'
1057
+ },
1058
+ {
1059
+ type: 'text',
1060
+ name: 'author',
1061
+ message: 'Author?',
1062
+ defaultFrom: 'env.user'
1063
+ }
1064
+ ];
1065
+ ```
1066
+
1067
+ ### Instance-Specific Resolvers
1068
+
1069
+ For isolated resolver registries, use a custom resolver registry per Prompter instance:
1070
+
1071
+ ```typescript
1072
+ import { DefaultResolverRegistry, Prompter } from 'inquirerer';
1073
+
1074
+ const customRegistry = new DefaultResolverRegistry();
1075
+
1076
+ // Register resolvers specific to this instance
1077
+ customRegistry.register('app.name', () => 'my-app');
1078
+ customRegistry.register('app.port', () => 3000);
1079
+
1080
+ const prompter = new Inquirerer({
1081
+ resolverRegistry: customRegistry // Use custom registry
1082
+ });
1083
+
1084
+ const questions = [
1085
+ {
1086
+ type: 'text',
1087
+ name: 'appName',
1088
+ defaultFrom: 'app.name'
1089
+ },
1090
+ {
1091
+ type: 'number',
1092
+ name: 'port',
1093
+ defaultFrom: 'app.port'
1094
+ }
1095
+ ];
1096
+
1097
+ const answers = await prompter.prompt({}, questions);
1098
+ ```
1099
+
1100
+ ### Resolver Examples
1101
+
1102
+ #### System Information
1103
+
1104
+ ```typescript
1105
+ import os from 'os';
1106
+ import { registerDefaultResolver } from 'inquirerer';
1107
+
1108
+ registerDefaultResolver('system.hostname', () => os.hostname());
1109
+ registerDefaultResolver('system.username', () => os.userInfo().username);
1110
+
1111
+ const questions = [
1112
+ {
1113
+ type: 'text',
1114
+ name: 'hostname',
1115
+ message: 'Hostname?',
1116
+ defaultFrom: 'system.hostname'
1117
+ }
1118
+ ];
1119
+ ```
1120
+
1121
+ #### Conditional Defaults
1122
+
1123
+ ```typescript
1124
+ registerDefaultResolver('app.port', () => {
1125
+ return process.env.NODE_ENV === 'production' ? 80 : 3000;
1126
+ });
1127
+
1128
+ const questions = [
1129
+ {
1130
+ type: 'number',
1131
+ name: 'port',
1132
+ message: 'Port?',
1133
+ defaultFrom: 'app.port'
1134
+ }
1135
+ ];
1136
+ ```
1137
+
1138
+ ### Error Handling
1139
+
1140
+ Resolvers fail silently by default. If a resolver throws an error or returns `undefined`, inquirerer falls back to the static `default` value (if provided):
1141
+
1142
+ ```typescript
1143
+ {
1144
+ type: 'text',
1145
+ name: 'author',
1146
+ defaultFrom: 'git.user.name', // May fail if git not configured
1147
+ default: 'Anonymous', // Used if resolver fails
1148
+ required: true
1149
+ }
1150
+ ```
1151
+
1152
+ For debugging, set `DEBUG=inquirerer` to see resolver errors:
1153
+
1154
+ ```bash
1155
+ DEBUG=inquirerer node your-cli.js
1156
+ ```
1157
+
1158
+ ### Real-World Use Case
1159
+
1160
+ ```typescript
1161
+ import { Inquirerer, registerDefaultResolver } from 'inquirerer';
1162
+
1163
+ // Register a resolver for current directory name
1164
+ registerDefaultResolver('cwd.name', () => {
1165
+ return process.cwd().split('/').pop();
1166
+ });
1167
+
1168
+ const questions = [
1169
+ {
1170
+ type: 'text',
1171
+ name: 'projectName',
1172
+ message: 'Project name?',
1173
+ defaultFrom: 'cwd.name',
1174
+ required: true
1175
+ },
1176
+ {
1177
+ type: 'text',
1178
+ name: 'author',
1179
+ message: 'Author?',
1180
+ defaultFrom: 'git.user.name',
1181
+ required: true
1182
+ },
1183
+ {
1184
+ type: 'text',
1185
+ name: 'email',
1186
+ message: 'Email?',
1187
+ defaultFrom: 'git.user.email',
1188
+ required: true
1189
+ },
1190
+ {
1191
+ type: 'text',
1192
+ name: 'year',
1193
+ message: 'Copyright year?',
1194
+ defaultFrom: 'date.year'
1195
+ }
1196
+ ];
1197
+
1198
+ const prompter = new Inquirerer();
1199
+ const config = await prompter.prompt({}, questions);
1200
+ ```
1201
+
1202
+ With git configured, the prompts will show:
1203
+
1204
+ ```bash
1205
+ Project name? (my-project-dir)
1206
+ Author? (John Doe)
1207
+ Email? (john@example.com)
1208
+ Copyright year? (2025)
1209
+ ```
1210
+
1211
+ All defaults automatically populated from git config, directory name, and current date!
1212
+
1213
+ ## CLI Helper
1214
+
1215
+ The `CLI` class provides integration with command-line argument parsing:
1216
+
1217
+ ```typescript
1218
+ import { CLI, CommandHandler, CLIOptions } from 'inquirerer';
1219
+
1220
+ const options: Partial<CLIOptions> = {
1221
+ version: 'myapp@1.0.0',
1222
+ minimistOpts: {
1223
+ alias: {
1224
+ v: 'version',
1225
+ h: 'help'
1226
+ },
1227
+ boolean: ['help', 'version'],
1228
+ string: ['name', 'output']
1229
+ }
1230
+ };
1231
+
1232
+ const handler: CommandHandler = async (argv, prompter) => {
1233
+ if (argv.help) {
1234
+ console.log('Usage: myapp [options]');
1235
+ process.exit(0);
1236
+ }
1237
+
1238
+ const answers = await prompter.prompt(argv, questions);
1239
+ // Handle answers
1240
+ };
1241
+
1242
+ const cli = new CLI(handler, options);
1243
+ await cli.run();
1244
+ ```
195
1245
 
196
1246
  ---
197
1247