inquirerer 2.1.3 → 2.1.5

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
@@ -31,6 +31,7 @@ npm install inquirerer
31
31
  - ✅ **Smart Validation** - Built-in pattern matching, custom validators, and sanitizers
32
32
  - 🔀 **Conditional Logic** - Show/hide questions based on previous answers
33
33
  - 🎨 **Interactive UX** - Fuzzy search, keyboard navigation, and visual feedback
34
+ - 🔄 **Dynamic Defaults** - Auto-populate defaults from git config, date/time, or custom resolvers
34
35
 
35
36
  ## Table of Contents
36
37
 
@@ -55,6 +56,10 @@ npm install inquirerer
55
56
  - [CLI with Commander Integration](#cli-with-commander-integration)
56
57
  - [Dynamic Dependencies](#dynamic-dependencies)
57
58
  - [Custom Validation](#custom-validation)
59
+ - [Dynamic Defaults with Resolvers](#dynamic-defaults-with-resolvers)
60
+ - [Built-in Resolvers](#built-in-resolvers)
61
+ - [Custom Resolvers](#custom-resolvers)
62
+ - [Resolver Examples](#resolver-examples)
58
63
  - [CLI Helper](#cli-helper)
59
64
  - [Developing](#developing)
60
65
 
@@ -100,7 +105,10 @@ import {
100
105
  ListQuestion,
101
106
  AutocompleteQuestion,
102
107
  CheckboxQuestion,
103
- InquirererOptions
108
+ InquirererOptions,
109
+ DefaultResolverRegistry,
110
+ registerDefaultResolver,
111
+ resolveDefault
104
112
  } from 'inquirerer';
105
113
 
106
114
  interface UserConfig {
@@ -124,6 +132,7 @@ interface BaseQuestion {
124
132
  message?: string; // Prompt message to display
125
133
  description?: string; // Additional context
126
134
  default?: any; // Default value
135
+ defaultFrom?: string; // Dynamic default from resolver (e.g., 'git.user.name')
127
136
  useDefault?: boolean; // Skip prompt and use default
128
137
  required?: boolean; // Validation requirement
129
138
  validate?: (input: any, answers: any) => boolean | Validation;
@@ -153,12 +162,13 @@ const prompter = new Inquirerer({
153
162
 
154
163
  ```typescript
155
164
  interface InquirererOptions {
156
- noTty?: boolean; // Disable interactive mode
157
- input?: Readable; // Input stream (default: process.stdin)
158
- output?: Writable; // Output stream (default: process.stdout)
159
- useDefaults?: boolean; // Skip prompts and use defaults
160
- globalMaxLines?: number; // Max lines for list displays (default: 10)
161
- mutateArgs?: boolean; // Mutate argv object (default: true)
165
+ noTty?: boolean; // Disable interactive mode
166
+ input?: Readable; // Input stream (default: process.stdin)
167
+ output?: Writable; // Output stream (default: process.stdout)
168
+ useDefaults?: boolean; // Skip prompts and use defaults
169
+ globalMaxLines?: number; // Max lines for list displays (default: 10)
170
+ mutateArgs?: boolean; // Mutate argv object (default: true)
171
+ resolverRegistry?: DefaultResolverRegistry; // Custom resolver registry
162
172
  }
163
173
 
164
174
  const prompter = new Inquirerer(options);
@@ -668,6 +678,261 @@ const questions: Question[] = [
668
678
  ];
669
679
  ```
670
680
 
681
+ ## Dynamic Defaults with Resolvers
682
+
683
+ 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.
684
+
685
+ ### Quick Example
686
+
687
+ ```typescript
688
+ import { Inquirerer } from 'inquirerer';
689
+
690
+ const questions = [
691
+ {
692
+ type: 'text',
693
+ name: 'authorName',
694
+ message: 'Author name?',
695
+ defaultFrom: 'git.user.name' // Auto-fills from git config
696
+ },
697
+ {
698
+ type: 'text',
699
+ name: 'authorEmail',
700
+ message: 'Author email?',
701
+ defaultFrom: 'git.user.email' // Auto-fills from git config
702
+ },
703
+ {
704
+ type: 'text',
705
+ name: 'copyrightYear',
706
+ message: 'Copyright year?',
707
+ defaultFrom: 'date.year' // Auto-fills current year
708
+ }
709
+ ];
710
+
711
+ const prompter = new Inquirerer();
712
+ const answers = await prompter.prompt({}, questions);
713
+ ```
714
+
715
+ ### Built-in Resolvers
716
+
717
+ Inquirerer comes with several built-in resolvers ready to use:
718
+
719
+ #### Git Configuration
720
+
721
+ | Resolver | Description | Example Output |
722
+ |----------|-------------|----------------|
723
+ | `git.user.name` | Git global user name | `"John Doe"` |
724
+ | `git.user.email` | Git global user email | `"john@example.com"` |
725
+
726
+ #### Date & Time
727
+
728
+ | Resolver | Description | Example Output |
729
+ |----------|-------------|----------------|
730
+ | `date.year` | Current year | `"2025"` |
731
+ | `date.month` | Current month (zero-padded) | `"11"` |
732
+ | `date.day` | Current day (zero-padded) | `"23"` |
733
+ | `date.iso` | ISO date (YYYY-MM-DD) | `"2025-11-23"` |
734
+ | `date.now` | ISO timestamp | `"2025-11-23T15:30:45.123Z"` |
735
+ | `date.timestamp` | Unix timestamp (ms) | `"1732375845123"` |
736
+
737
+ ### Priority Order
738
+
739
+ When resolving default values, inquirerer follows this priority:
740
+
741
+ 1. **CLI Arguments** - Values passed via command line (highest priority)
742
+ 2. **`defaultFrom`** - Dynamically resolved values
743
+ 3. **`default`** - Static default values
744
+ 4. **`undefined`** - No default available
745
+
746
+ ```typescript
747
+ {
748
+ type: 'text',
749
+ name: 'author',
750
+ defaultFrom: 'git.user.name', // Try git first
751
+ default: 'Anonymous' // Fallback if git not configured
752
+ }
753
+ ```
754
+
755
+ ### Custom Resolvers
756
+
757
+ Register your own custom resolvers for project-specific needs:
758
+
759
+ ```typescript
760
+ import { registerDefaultResolver } from 'inquirerer';
761
+
762
+ // Register a resolver for current directory name
763
+ registerDefaultResolver('cwd.name', () => {
764
+ return process.cwd().split('/').pop();
765
+ });
766
+
767
+ // Register a resolver for environment variable
768
+ registerDefaultResolver('env.user', () => {
769
+ return process.env.USER;
770
+ });
771
+
772
+ // Use in questions
773
+ const questions = [
774
+ {
775
+ type: 'text',
776
+ name: 'projectName',
777
+ message: 'Project name?',
778
+ defaultFrom: 'cwd.name',
779
+ default: 'my-project'
780
+ },
781
+ {
782
+ type: 'text',
783
+ name: 'author',
784
+ message: 'Author?',
785
+ defaultFrom: 'env.user'
786
+ }
787
+ ];
788
+ ```
789
+
790
+ ### Instance-Specific Resolvers
791
+
792
+ For isolated resolver registries, use a custom resolver registry per Inquirerer instance:
793
+
794
+ ```typescript
795
+ import { DefaultResolverRegistry, Inquirerer } from 'inquirerer';
796
+
797
+ const customRegistry = new DefaultResolverRegistry();
798
+
799
+ // Register resolvers specific to this instance
800
+ customRegistry.register('app.name', () => 'my-app');
801
+ customRegistry.register('app.port', () => 3000);
802
+
803
+ const prompter = new Inquirerer({
804
+ resolverRegistry: customRegistry // Use custom registry
805
+ });
806
+
807
+ const questions = [
808
+ {
809
+ type: 'text',
810
+ name: 'appName',
811
+ defaultFrom: 'app.name'
812
+ },
813
+ {
814
+ type: 'number',
815
+ name: 'port',
816
+ defaultFrom: 'app.port'
817
+ }
818
+ ];
819
+
820
+ const answers = await prompter.prompt({}, questions);
821
+ ```
822
+
823
+ ### Resolver Examples
824
+
825
+ #### System Information
826
+
827
+ ```typescript
828
+ import os from 'os';
829
+ import { registerDefaultResolver } from 'inquirerer';
830
+
831
+ registerDefaultResolver('system.hostname', () => os.hostname());
832
+ registerDefaultResolver('system.username', () => os.userInfo().username);
833
+
834
+ const questions = [
835
+ {
836
+ type: 'text',
837
+ name: 'hostname',
838
+ message: 'Hostname?',
839
+ defaultFrom: 'system.hostname'
840
+ }
841
+ ];
842
+ ```
843
+
844
+ #### Conditional Defaults
845
+
846
+ ```typescript
847
+ registerDefaultResolver('app.port', () => {
848
+ return process.env.NODE_ENV === 'production' ? 80 : 3000;
849
+ });
850
+
851
+ const questions = [
852
+ {
853
+ type: 'number',
854
+ name: 'port',
855
+ message: 'Port?',
856
+ defaultFrom: 'app.port'
857
+ }
858
+ ];
859
+ ```
860
+
861
+ ### Error Handling
862
+
863
+ Resolvers fail silently by default. If a resolver throws an error or returns `undefined`, inquirerer falls back to the static `default` value (if provided):
864
+
865
+ ```typescript
866
+ {
867
+ type: 'text',
868
+ name: 'author',
869
+ defaultFrom: 'git.user.name', // May fail if git not configured
870
+ default: 'Anonymous', // Used if resolver fails
871
+ required: true
872
+ }
873
+ ```
874
+
875
+ For debugging, set `DEBUG=inquirerer` to see resolver errors:
876
+
877
+ ```bash
878
+ DEBUG=inquirerer node your-cli.js
879
+ ```
880
+
881
+ ### Real-World Use Case
882
+
883
+ ```typescript
884
+ import { Inquirerer, registerDefaultResolver } from 'inquirerer';
885
+
886
+ // Register a resolver for current directory name
887
+ registerDefaultResolver('cwd.name', () => {
888
+ return process.cwd().split('/').pop();
889
+ });
890
+
891
+ const questions = [
892
+ {
893
+ type: 'text',
894
+ name: 'projectName',
895
+ message: 'Project name?',
896
+ defaultFrom: 'cwd.name',
897
+ required: true
898
+ },
899
+ {
900
+ type: 'text',
901
+ name: 'author',
902
+ message: 'Author?',
903
+ defaultFrom: 'git.user.name',
904
+ required: true
905
+ },
906
+ {
907
+ type: 'text',
908
+ name: 'email',
909
+ message: 'Email?',
910
+ defaultFrom: 'git.user.email',
911
+ required: true
912
+ },
913
+ {
914
+ type: 'text',
915
+ name: 'year',
916
+ message: 'Copyright year?',
917
+ defaultFrom: 'date.year'
918
+ }
919
+ ];
920
+
921
+ const prompter = new Inquirerer();
922
+ const config = await prompter.prompt({}, questions);
923
+ ```
924
+
925
+ With git configured, the prompts will show:
926
+
927
+ ```bash
928
+ Project name? (my-project-dir)
929
+ Author? (John Doe)
930
+ Email? (john@example.com)
931
+ Copyright year? (2025)
932
+ ```
933
+
934
+ All defaults automatically populated from git config, directory name, and current date!
935
+
671
936
  ## CLI Helper
672
937
 
673
938
  The `CLI` class provides integration with command-line argument parsing:
package/esm/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './commander';
2
2
  export * from './prompt';
3
3
  export * from './question';
4
+ export * from './resolvers';
package/esm/keypress.js CHANGED
@@ -18,14 +18,13 @@ export class TerminalKeypress {
18
18
  noTty;
19
19
  input;
20
20
  proc;
21
+ dataHandler = null;
21
22
  constructor(noTty = false, input = process.stdin, proc = defaultProcessWrapper) {
22
23
  this.noTty = noTty;
23
24
  this.input = input;
24
25
  this.proc = proc;
26
+ // Don't set raw mode yet; let resume() handle it when necessary
25
27
  if (this.isTTY()) {
26
- if (typeof this.input.setRawMode === 'function') {
27
- this.input.setRawMode(true);
28
- }
29
28
  this.input.resume();
30
29
  this.input.setEncoding('utf8');
31
30
  }
@@ -35,7 +34,7 @@ export class TerminalKeypress {
35
34
  return !this.noTty;
36
35
  }
37
36
  setupListeners() {
38
- this.input.on('data', (key) => {
37
+ this.dataHandler = (key) => {
39
38
  if (!this.active)
40
39
  return;
41
40
  const handlers = this.listeners[key];
@@ -43,7 +42,8 @@ export class TerminalKeypress {
43
42
  if (key === KEY_CODES.CTRL_C) { // Ctrl+C
44
43
  this.proc.exit(0);
45
44
  }
46
- });
45
+ };
46
+ this.input.on('data', this.dataHandler);
47
47
  }
48
48
  on(key, callback) {
49
49
  if (!this.listeners[key]) {
@@ -67,12 +67,18 @@ export class TerminalKeypress {
67
67
  }
68
68
  resume() {
69
69
  this.active = true;
70
+ if (this.isTTY() && typeof this.input.setRawMode === 'function') {
71
+ this.input.setRawMode(true);
72
+ }
70
73
  }
71
74
  destroy() {
72
75
  if (typeof this.input.setRawMode === 'function') {
73
76
  this.input.setRawMode(false);
74
77
  }
75
78
  this.input.pause();
76
- this.input.removeAllListeners('data');
79
+ if (this.dataHandler) {
80
+ this.input.removeListener('data', this.dataHandler);
81
+ this.dataHandler = null;
82
+ }
77
83
  }
78
84
  }
package/esm/prompt.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { red, whiteBright, yellow, gray, dim, green, cyan, white, blue } from 'yanse';
2
2
  import readline from 'readline';
3
3
  import { KEY_CODES, TerminalKeypress } from './keypress';
4
+ import { globalResolverRegistry } from './resolvers';
4
5
  export function reorderQuestionsByDeps(questions) {
5
6
  const nameToIndex = new Map();
6
7
  questions.forEach((q, idx) => nameToIndex.set(q.name, idx));
@@ -179,15 +180,17 @@ export class Inquirerer {
179
180
  useDefaults;
180
181
  globalMaxLines;
181
182
  mutateArgs;
183
+ resolverRegistry;
182
184
  handledKeys = new Set();
183
185
  constructor(options) {
184
- const { noTty = false, input = process.stdin, output = process.stdout, useDefaults = false, globalMaxLines = 10, mutateArgs = true } = options ?? {};
186
+ const { noTty = false, input = process.stdin, output = process.stdout, useDefaults = false, globalMaxLines = 10, mutateArgs = true, resolverRegistry = globalResolverRegistry } = options ?? {};
185
187
  this.useDefaults = useDefaults;
186
188
  this.noTty = noTty;
187
189
  this.output = output;
188
190
  this.mutateArgs = mutateArgs;
189
191
  this.input = input;
190
192
  this.globalMaxLines = globalMaxLines;
193
+ this.resolverRegistry = resolverRegistry;
191
194
  if (!noTty) {
192
195
  this.rl = readline.createInterface({
193
196
  input,
@@ -341,6 +344,8 @@ export class Inquirerer {
341
344
  // use local mutateArgs if defined, otherwise global mutateArgs
342
345
  const shouldMutate = options?.mutateArgs !== undefined ? options.mutateArgs : this.mutateArgs;
343
346
  let obj = shouldMutate ? argv : { ...argv };
347
+ // Resolve dynamic defaults before processing questions
348
+ await this.resolveDynamicDefaults(questions);
344
349
  // first loop through the question, and set any overrides in case other questions use objs for validation
345
350
  this.applyOverrides(argv, obj, questions);
346
351
  // Check for required arguments when no terminal is available (non-interactive mode)
@@ -408,6 +413,39 @@ export class Inquirerer {
408
413
  hasMissingRequiredArgs(questions, argv) {
409
414
  return questions.some(question => question.required && this.isEmptyAnswer(argv[question.name]));
410
415
  }
416
+ /**
417
+ * Resolves the default value for a question using the resolver system.
418
+ * Priority: defaultFrom > default > undefined
419
+ */
420
+ async resolveQuestionDefault(question) {
421
+ // Try to resolve from defaultFrom first
422
+ if ('defaultFrom' in question && question.defaultFrom) {
423
+ const resolved = await this.resolverRegistry.resolve(question.defaultFrom);
424
+ if (resolved !== undefined) {
425
+ return resolved;
426
+ }
427
+ }
428
+ // Fallback to static default
429
+ if ('default' in question) {
430
+ return question.default;
431
+ }
432
+ return undefined;
433
+ }
434
+ /**
435
+ * Resolves dynamic defaults for all questions that have defaultFrom specified.
436
+ * Updates the question.default property with the resolved value.
437
+ */
438
+ async resolveDynamicDefaults(questions) {
439
+ for (const question of questions) {
440
+ if ('defaultFrom' in question && question.defaultFrom) {
441
+ const resolved = await this.resolveQuestionDefault(question);
442
+ if (resolved !== undefined) {
443
+ // Update question.default with resolved value
444
+ question.default = resolved;
445
+ }
446
+ }
447
+ }
448
+ }
411
449
  applyDefaultValues(questions, obj) {
412
450
  questions.forEach(question => {
413
451
  if ('default' in question) {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Built-in date/time resolvers.
3
+ */
4
+ export const dateResolvers = {
5
+ 'date.year': () => new Date().getFullYear().toString(),
6
+ 'date.month': () => (new Date().getMonth() + 1).toString().padStart(2, '0'),
7
+ 'date.day': () => new Date().getDate().toString().padStart(2, '0'),
8
+ 'date.now': () => new Date().toISOString(),
9
+ 'date.iso': () => new Date().toISOString().split('T')[0], // YYYY-MM-DD
10
+ 'date.timestamp': () => Date.now().toString(),
11
+ };
@@ -0,0 +1,26 @@
1
+ import { execSync } from 'child_process';
2
+ /**
3
+ * Retrieves a git config value.
4
+ * @param key The git config key (e.g., 'user.name', 'user.email')
5
+ * @returns The config value as a string, or undefined if not found or error occurs
6
+ */
7
+ export function getGitConfig(key) {
8
+ try {
9
+ const result = execSync(`git config --global ${key}`, {
10
+ encoding: 'utf8',
11
+ stdio: ['pipe', 'pipe', 'ignore'] // Suppress stderr
12
+ });
13
+ const trimmed = result.trim();
14
+ return trimmed || undefined; // Treat empty string as undefined
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ /**
21
+ * Built-in git configuration resolvers.
22
+ */
23
+ export const gitResolvers = {
24
+ 'git.user.name': () => getGitConfig('user.name'),
25
+ 'git.user.email': () => getGitConfig('user.email'),
26
+ };
@@ -0,0 +1,98 @@
1
+ import { gitResolvers } from './git';
2
+ import { dateResolvers } from './date';
3
+ /**
4
+ * A registry for managing default value resolvers.
5
+ * Allows registration of custom resolvers and provides resolution logic.
6
+ */
7
+ export class DefaultResolverRegistry {
8
+ resolvers;
9
+ constructor(initialResolvers = {}) {
10
+ this.resolvers = { ...initialResolvers };
11
+ }
12
+ /**
13
+ * Register a custom resolver.
14
+ * @param key The resolver key (e.g., 'git.user.name')
15
+ * @param resolver The resolver function
16
+ */
17
+ register(key, resolver) {
18
+ this.resolvers[key] = resolver;
19
+ }
20
+ /**
21
+ * Unregister a resolver.
22
+ * @param key The resolver key to remove
23
+ */
24
+ unregister(key) {
25
+ delete this.resolvers[key];
26
+ }
27
+ /**
28
+ * Resolve a key to its value.
29
+ * Returns undefined if the resolver doesn't exist or if it throws an error.
30
+ * @param key The resolver key
31
+ * @returns The resolved value or undefined
32
+ */
33
+ async resolve(key) {
34
+ const resolver = this.resolvers[key];
35
+ if (!resolver) {
36
+ return undefined;
37
+ }
38
+ try {
39
+ const result = await Promise.resolve(resolver());
40
+ // Treat empty strings as undefined
41
+ return result === '' ? undefined : result;
42
+ }
43
+ catch (error) {
44
+ // Silent failure - log only in debug mode
45
+ if (process.env.DEBUG === 'inquirerer') {
46
+ console.error(`[inquirerer] Resolver '${key}' failed:`, error);
47
+ }
48
+ return undefined;
49
+ }
50
+ }
51
+ /**
52
+ * Check if a resolver exists for the given key.
53
+ * @param key The resolver key
54
+ * @returns True if the resolver exists
55
+ */
56
+ has(key) {
57
+ return key in this.resolvers;
58
+ }
59
+ /**
60
+ * Get all registered resolver keys.
61
+ * @returns Array of resolver keys
62
+ */
63
+ keys() {
64
+ return Object.keys(this.resolvers);
65
+ }
66
+ /**
67
+ * Create a copy of this registry with all current resolvers.
68
+ * @returns A new DefaultResolverRegistry instance
69
+ */
70
+ clone() {
71
+ return new DefaultResolverRegistry({ ...this.resolvers });
72
+ }
73
+ }
74
+ /**
75
+ * Global resolver registry instance with built-in resolvers.
76
+ * This is the default registry used by Inquirerer unless a custom one is provided.
77
+ */
78
+ export const globalResolverRegistry = new DefaultResolverRegistry({
79
+ ...gitResolvers,
80
+ ...dateResolvers,
81
+ });
82
+ /**
83
+ * Convenience function to register a resolver on the global registry.
84
+ * @param key The resolver key
85
+ * @param resolver The resolver function
86
+ */
87
+ export function registerDefaultResolver(key, resolver) {
88
+ globalResolverRegistry.register(key, resolver);
89
+ }
90
+ /**
91
+ * Convenience function to resolve a key using the global registry.
92
+ * @param key The resolver key
93
+ * @returns The resolved value or undefined
94
+ */
95
+ export function resolveDefault(key) {
96
+ return globalResolverRegistry.resolve(key);
97
+ }
98
+ export { getGitConfig } from './git';
@@ -0,0 +1 @@
1
+ export {};
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './commander';
2
2
  export * from './prompt';
3
3
  export * from './question';
4
+ export * from './resolvers';
package/index.js CHANGED
@@ -17,3 +17,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./commander"), exports);
18
18
  __exportStar(require("./prompt"), exports);
19
19
  __exportStar(require("./question"), exports);
20
+ __exportStar(require("./resolvers"), exports);
package/keypress.d.ts CHANGED
@@ -20,6 +20,7 @@ export declare class TerminalKeypress {
20
20
  private noTty;
21
21
  private input;
22
22
  private proc;
23
+ private dataHandler;
23
24
  constructor(noTty?: boolean, input?: Readable, proc?: ProcessWrapper);
24
25
  isTTY(): boolean;
25
26
  private setupListeners;
package/keypress.js CHANGED
@@ -21,14 +21,13 @@ class TerminalKeypress {
21
21
  noTty;
22
22
  input;
23
23
  proc;
24
+ dataHandler = null;
24
25
  constructor(noTty = false, input = process.stdin, proc = defaultProcessWrapper) {
25
26
  this.noTty = noTty;
26
27
  this.input = input;
27
28
  this.proc = proc;
29
+ // Don't set raw mode yet; let resume() handle it when necessary
28
30
  if (this.isTTY()) {
29
- if (typeof this.input.setRawMode === 'function') {
30
- this.input.setRawMode(true);
31
- }
32
31
  this.input.resume();
33
32
  this.input.setEncoding('utf8');
34
33
  }
@@ -38,7 +37,7 @@ class TerminalKeypress {
38
37
  return !this.noTty;
39
38
  }
40
39
  setupListeners() {
41
- this.input.on('data', (key) => {
40
+ this.dataHandler = (key) => {
42
41
  if (!this.active)
43
42
  return;
44
43
  const handlers = this.listeners[key];
@@ -46,7 +45,8 @@ class TerminalKeypress {
46
45
  if (key === exports.KEY_CODES.CTRL_C) { // Ctrl+C
47
46
  this.proc.exit(0);
48
47
  }
49
- });
48
+ };
49
+ this.input.on('data', this.dataHandler);
50
50
  }
51
51
  on(key, callback) {
52
52
  if (!this.listeners[key]) {
@@ -70,13 +70,19 @@ class TerminalKeypress {
70
70
  }
71
71
  resume() {
72
72
  this.active = true;
73
+ if (this.isTTY() && typeof this.input.setRawMode === 'function') {
74
+ this.input.setRawMode(true);
75
+ }
73
76
  }
74
77
  destroy() {
75
78
  if (typeof this.input.setRawMode === 'function') {
76
79
  this.input.setRawMode(false);
77
80
  }
78
81
  this.input.pause();
79
- this.input.removeAllListeners('data');
82
+ if (this.dataHandler) {
83
+ this.input.removeListener('data', this.dataHandler);
84
+ this.dataHandler = null;
85
+ }
80
86
  }
81
87
  }
82
88
  exports.TerminalKeypress = TerminalKeypress;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inquirerer",
3
- "version": "2.1.3",
3
+ "version": "2.1.5",
4
4
  "author": "Dan Lynch <pyramation@gmail.com>",
5
5
  "description": "TypeScript-first library for building beautiful CLI interfaces with interactive prompts",
6
6
  "main": "index.js",
@@ -37,7 +37,8 @@
37
37
  "keywords": [],
38
38
  "devDependencies": {
39
39
  "@types/minimist": "^1.2.5",
40
+ "clean-ansi": "0.1.1",
40
41
  "makage": "0.1.5"
41
42
  },
42
- "gitHead": "1d52c98779d1b6296627dbe3f341857b0177a9ff"
43
+ "gitHead": "00b9ec9aa30a6cdd61bfc4314974b8f2562ad791"
43
44
  }
package/prompt.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Readable, Writable } from 'stream';
2
2
  import { AutocompleteQuestion, CheckboxQuestion, ConfirmQuestion, ListQuestion, NumberQuestion, OptionValue, Question, TextQuestion, Validation } from './question';
3
+ import { DefaultResolverRegistry } from './resolvers';
3
4
  export interface ManPageInfo {
4
5
  commandName: string;
5
6
  questions: Question[];
@@ -28,6 +29,7 @@ export interface InquirererOptions {
28
29
  useDefaults?: boolean;
29
30
  globalMaxLines?: number;
30
31
  mutateArgs?: boolean;
32
+ resolverRegistry?: DefaultResolverRegistry;
31
33
  }
32
34
  export declare class Inquirerer {
33
35
  private rl;
@@ -38,6 +40,7 @@ export declare class Inquirerer {
38
40
  private useDefaults;
39
41
  private globalMaxLines;
40
42
  private mutateArgs;
43
+ private resolverRegistry;
41
44
  private handledKeys;
42
45
  constructor(options?: InquirererOptions);
43
46
  private clearScreen;
@@ -57,6 +60,16 @@ export declare class Inquirerer {
57
60
  prompt<T extends object>(argv: T, questions: Question[], options?: PromptOptions): Promise<T>;
58
61
  private handleMissingArgsError;
59
62
  private hasMissingRequiredArgs;
63
+ /**
64
+ * Resolves the default value for a question using the resolver system.
65
+ * Priority: defaultFrom > default > undefined
66
+ */
67
+ private resolveQuestionDefault;
68
+ /**
69
+ * Resolves dynamic defaults for all questions that have defaultFrom specified.
70
+ * Updates the question.default property with the resolved value.
71
+ */
72
+ private resolveDynamicDefaults;
60
73
  private applyDefaultValues;
61
74
  private applyOverrides;
62
75
  private handleOverrides;
package/prompt.js CHANGED
@@ -8,6 +8,7 @@ exports.reorderQuestionsByDeps = reorderQuestionsByDeps;
8
8
  const yanse_1 = require("yanse");
9
9
  const readline_1 = __importDefault(require("readline"));
10
10
  const keypress_1 = require("./keypress");
11
+ const resolvers_1 = require("./resolvers");
11
12
  function reorderQuestionsByDeps(questions) {
12
13
  const nameToIndex = new Map();
13
14
  questions.forEach((q, idx) => nameToIndex.set(q.name, idx));
@@ -186,15 +187,17 @@ class Inquirerer {
186
187
  useDefaults;
187
188
  globalMaxLines;
188
189
  mutateArgs;
190
+ resolverRegistry;
189
191
  handledKeys = new Set();
190
192
  constructor(options) {
191
- const { noTty = false, input = process.stdin, output = process.stdout, useDefaults = false, globalMaxLines = 10, mutateArgs = true } = options ?? {};
193
+ const { noTty = false, input = process.stdin, output = process.stdout, useDefaults = false, globalMaxLines = 10, mutateArgs = true, resolverRegistry = resolvers_1.globalResolverRegistry } = options ?? {};
192
194
  this.useDefaults = useDefaults;
193
195
  this.noTty = noTty;
194
196
  this.output = output;
195
197
  this.mutateArgs = mutateArgs;
196
198
  this.input = input;
197
199
  this.globalMaxLines = globalMaxLines;
200
+ this.resolverRegistry = resolverRegistry;
198
201
  if (!noTty) {
199
202
  this.rl = readline_1.default.createInterface({
200
203
  input,
@@ -348,6 +351,8 @@ class Inquirerer {
348
351
  // use local mutateArgs if defined, otherwise global mutateArgs
349
352
  const shouldMutate = options?.mutateArgs !== undefined ? options.mutateArgs : this.mutateArgs;
350
353
  let obj = shouldMutate ? argv : { ...argv };
354
+ // Resolve dynamic defaults before processing questions
355
+ await this.resolveDynamicDefaults(questions);
351
356
  // first loop through the question, and set any overrides in case other questions use objs for validation
352
357
  this.applyOverrides(argv, obj, questions);
353
358
  // Check for required arguments when no terminal is available (non-interactive mode)
@@ -415,6 +420,39 @@ class Inquirerer {
415
420
  hasMissingRequiredArgs(questions, argv) {
416
421
  return questions.some(question => question.required && this.isEmptyAnswer(argv[question.name]));
417
422
  }
423
+ /**
424
+ * Resolves the default value for a question using the resolver system.
425
+ * Priority: defaultFrom > default > undefined
426
+ */
427
+ async resolveQuestionDefault(question) {
428
+ // Try to resolve from defaultFrom first
429
+ if ('defaultFrom' in question && question.defaultFrom) {
430
+ const resolved = await this.resolverRegistry.resolve(question.defaultFrom);
431
+ if (resolved !== undefined) {
432
+ return resolved;
433
+ }
434
+ }
435
+ // Fallback to static default
436
+ if ('default' in question) {
437
+ return question.default;
438
+ }
439
+ return undefined;
440
+ }
441
+ /**
442
+ * Resolves dynamic defaults for all questions that have defaultFrom specified.
443
+ * Updates the question.default property with the resolved value.
444
+ */
445
+ async resolveDynamicDefaults(questions) {
446
+ for (const question of questions) {
447
+ if ('defaultFrom' in question && question.defaultFrom) {
448
+ const resolved = await this.resolveQuestionDefault(question);
449
+ if (resolved !== undefined) {
450
+ // Update question.default with resolved value
451
+ question.default = resolved;
452
+ }
453
+ }
454
+ }
455
+ }
418
456
  applyDefaultValues(questions, obj) {
419
457
  questions.forEach(question => {
420
458
  if ('default' in question) {
@@ -16,6 +16,7 @@ export interface BaseQuestion {
16
16
  name: string;
17
17
  type: string;
18
18
  default?: any;
19
+ defaultFrom?: string;
19
20
  useDefault?: boolean;
20
21
  required?: boolean;
21
22
  message?: string;
@@ -0,0 +1,5 @@
1
+ import type { ResolverRegistry } from './types';
2
+ /**
3
+ * Built-in date/time resolvers.
4
+ */
5
+ export declare const dateResolvers: ResolverRegistry;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dateResolvers = void 0;
4
+ /**
5
+ * Built-in date/time resolvers.
6
+ */
7
+ exports.dateResolvers = {
8
+ 'date.year': () => new Date().getFullYear().toString(),
9
+ 'date.month': () => (new Date().getMonth() + 1).toString().padStart(2, '0'),
10
+ 'date.day': () => new Date().getDate().toString().padStart(2, '0'),
11
+ 'date.now': () => new Date().toISOString(),
12
+ 'date.iso': () => new Date().toISOString().split('T')[0], // YYYY-MM-DD
13
+ 'date.timestamp': () => Date.now().toString(),
14
+ };
@@ -0,0 +1,11 @@
1
+ import type { ResolverRegistry } from './types';
2
+ /**
3
+ * Retrieves a git config value.
4
+ * @param key The git config key (e.g., 'user.name', 'user.email')
5
+ * @returns The config value as a string, or undefined if not found or error occurs
6
+ */
7
+ export declare function getGitConfig(key: string): string | undefined;
8
+ /**
9
+ * Built-in git configuration resolvers.
10
+ */
11
+ export declare const gitResolvers: ResolverRegistry;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gitResolvers = void 0;
4
+ exports.getGitConfig = getGitConfig;
5
+ const child_process_1 = require("child_process");
6
+ /**
7
+ * Retrieves a git config value.
8
+ * @param key The git config key (e.g., 'user.name', 'user.email')
9
+ * @returns The config value as a string, or undefined if not found or error occurs
10
+ */
11
+ function getGitConfig(key) {
12
+ try {
13
+ const result = (0, child_process_1.execSync)(`git config --global ${key}`, {
14
+ encoding: 'utf8',
15
+ stdio: ['pipe', 'pipe', 'ignore'] // Suppress stderr
16
+ });
17
+ const trimmed = result.trim();
18
+ return trimmed || undefined; // Treat empty string as undefined
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /**
25
+ * Built-in git configuration resolvers.
26
+ */
27
+ exports.gitResolvers = {
28
+ 'git.user.name': () => getGitConfig('user.name'),
29
+ 'git.user.email': () => getGitConfig('user.email'),
30
+ };
@@ -0,0 +1,62 @@
1
+ import type { DefaultResolver, ResolverRegistry } from './types';
2
+ /**
3
+ * A registry for managing default value resolvers.
4
+ * Allows registration of custom resolvers and provides resolution logic.
5
+ */
6
+ export declare class DefaultResolverRegistry {
7
+ private resolvers;
8
+ constructor(initialResolvers?: ResolverRegistry);
9
+ /**
10
+ * Register a custom resolver.
11
+ * @param key The resolver key (e.g., 'git.user.name')
12
+ * @param resolver The resolver function
13
+ */
14
+ register(key: string, resolver: DefaultResolver): void;
15
+ /**
16
+ * Unregister a resolver.
17
+ * @param key The resolver key to remove
18
+ */
19
+ unregister(key: string): void;
20
+ /**
21
+ * Resolve a key to its value.
22
+ * Returns undefined if the resolver doesn't exist or if it throws an error.
23
+ * @param key The resolver key
24
+ * @returns The resolved value or undefined
25
+ */
26
+ resolve(key: string): Promise<any>;
27
+ /**
28
+ * Check if a resolver exists for the given key.
29
+ * @param key The resolver key
30
+ * @returns True if the resolver exists
31
+ */
32
+ has(key: string): boolean;
33
+ /**
34
+ * Get all registered resolver keys.
35
+ * @returns Array of resolver keys
36
+ */
37
+ keys(): string[];
38
+ /**
39
+ * Create a copy of this registry with all current resolvers.
40
+ * @returns A new DefaultResolverRegistry instance
41
+ */
42
+ clone(): DefaultResolverRegistry;
43
+ }
44
+ /**
45
+ * Global resolver registry instance with built-in resolvers.
46
+ * This is the default registry used by Inquirerer unless a custom one is provided.
47
+ */
48
+ export declare const globalResolverRegistry: DefaultResolverRegistry;
49
+ /**
50
+ * Convenience function to register a resolver on the global registry.
51
+ * @param key The resolver key
52
+ * @param resolver The resolver function
53
+ */
54
+ export declare function registerDefaultResolver(key: string, resolver: DefaultResolver): void;
55
+ /**
56
+ * Convenience function to resolve a key using the global registry.
57
+ * @param key The resolver key
58
+ * @returns The resolved value or undefined
59
+ */
60
+ export declare function resolveDefault(key: string): Promise<any>;
61
+ export type { DefaultResolver, ResolverRegistry } from './types';
62
+ export { getGitConfig } from './git';
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGitConfig = exports.globalResolverRegistry = exports.DefaultResolverRegistry = void 0;
4
+ exports.registerDefaultResolver = registerDefaultResolver;
5
+ exports.resolveDefault = resolveDefault;
6
+ const git_1 = require("./git");
7
+ const date_1 = require("./date");
8
+ /**
9
+ * A registry for managing default value resolvers.
10
+ * Allows registration of custom resolvers and provides resolution logic.
11
+ */
12
+ class DefaultResolverRegistry {
13
+ resolvers;
14
+ constructor(initialResolvers = {}) {
15
+ this.resolvers = { ...initialResolvers };
16
+ }
17
+ /**
18
+ * Register a custom resolver.
19
+ * @param key The resolver key (e.g., 'git.user.name')
20
+ * @param resolver The resolver function
21
+ */
22
+ register(key, resolver) {
23
+ this.resolvers[key] = resolver;
24
+ }
25
+ /**
26
+ * Unregister a resolver.
27
+ * @param key The resolver key to remove
28
+ */
29
+ unregister(key) {
30
+ delete this.resolvers[key];
31
+ }
32
+ /**
33
+ * Resolve a key to its value.
34
+ * Returns undefined if the resolver doesn't exist or if it throws an error.
35
+ * @param key The resolver key
36
+ * @returns The resolved value or undefined
37
+ */
38
+ async resolve(key) {
39
+ const resolver = this.resolvers[key];
40
+ if (!resolver) {
41
+ return undefined;
42
+ }
43
+ try {
44
+ const result = await Promise.resolve(resolver());
45
+ // Treat empty strings as undefined
46
+ return result === '' ? undefined : result;
47
+ }
48
+ catch (error) {
49
+ // Silent failure - log only in debug mode
50
+ if (process.env.DEBUG === 'inquirerer') {
51
+ console.error(`[inquirerer] Resolver '${key}' failed:`, error);
52
+ }
53
+ return undefined;
54
+ }
55
+ }
56
+ /**
57
+ * Check if a resolver exists for the given key.
58
+ * @param key The resolver key
59
+ * @returns True if the resolver exists
60
+ */
61
+ has(key) {
62
+ return key in this.resolvers;
63
+ }
64
+ /**
65
+ * Get all registered resolver keys.
66
+ * @returns Array of resolver keys
67
+ */
68
+ keys() {
69
+ return Object.keys(this.resolvers);
70
+ }
71
+ /**
72
+ * Create a copy of this registry with all current resolvers.
73
+ * @returns A new DefaultResolverRegistry instance
74
+ */
75
+ clone() {
76
+ return new DefaultResolverRegistry({ ...this.resolvers });
77
+ }
78
+ }
79
+ exports.DefaultResolverRegistry = DefaultResolverRegistry;
80
+ /**
81
+ * Global resolver registry instance with built-in resolvers.
82
+ * This is the default registry used by Inquirerer unless a custom one is provided.
83
+ */
84
+ exports.globalResolverRegistry = new DefaultResolverRegistry({
85
+ ...git_1.gitResolvers,
86
+ ...date_1.dateResolvers,
87
+ });
88
+ /**
89
+ * Convenience function to register a resolver on the global registry.
90
+ * @param key The resolver key
91
+ * @param resolver The resolver function
92
+ */
93
+ function registerDefaultResolver(key, resolver) {
94
+ exports.globalResolverRegistry.register(key, resolver);
95
+ }
96
+ /**
97
+ * Convenience function to resolve a key using the global registry.
98
+ * @param key The resolver key
99
+ * @returns The resolved value or undefined
100
+ */
101
+ function resolveDefault(key) {
102
+ return exports.globalResolverRegistry.resolve(key);
103
+ }
104
+ var git_2 = require("./git");
105
+ Object.defineProperty(exports, "getGitConfig", { enumerable: true, get: function () { return git_2.getGitConfig; } });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A function that resolves a default value dynamically.
3
+ * Can be synchronous or asynchronous.
4
+ */
5
+ export type DefaultResolver = () => Promise<any> | any;
6
+ /**
7
+ * A registry of resolver functions, keyed by their resolver name.
8
+ * Example: { 'git.user.name': () => getGitConfig('user.name') }
9
+ */
10
+ export interface ResolverRegistry {
11
+ [key: string]: DefaultResolver;
12
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });