0
# Configuration Management
1
2
Core configuration management functionality providing hierarchical configuration loading, validation, and manipulation with support for multiple configuration sources.
3
4
## Capabilities
5
6
### Config Class Constructor
7
8
Creates a new configuration instance with type definitions, shorthands, and environment settings.
9
10
```javascript { .api }
11
/**
12
* Create a new Config instance
13
* @param options - Configuration options including definitions, shorthands, and paths
14
*/
15
constructor(options: ConfigOptions);
16
17
interface ConfigOptions {
18
/** Configuration field definitions with types and defaults */
19
definitions: Record<string, ConfigDefinition>;
20
/** Command line shorthand mappings */
21
shorthands?: Record<string, string[]>;
22
/** Configuration flattening function */
23
flatten?: (obj: any) => any;
24
/** Path to npm installation */
25
npmPath: string;
26
/** Environment variables (defaults to process.env) */
27
env?: Record<string, string>;
28
/** Command line arguments (defaults to process.argv) */
29
argv?: string[];
30
/** Operating system platform (defaults to process.platform) */
31
platform?: string;
32
/** Node.js executable path (defaults to process.execPath) */
33
execPath?: string;
34
/** Current working directory (defaults to process.cwd()) */
35
cwd?: string;
36
}
37
38
interface ConfigDefinition {
39
/** Field type (String, Number, Boolean, Array, etc.) */
40
type: any;
41
/** Default value for the field */
42
default?: any;
43
/** Human-readable description */
44
description?: string;
45
/** Deprecation message or boolean flag */
46
deprecated?: string | boolean;
47
}
48
```
49
50
**Usage Example:**
51
52
```javascript
53
const { Config } = require('@npmcli/config');
54
55
const config = new Config({
56
definitions: {
57
registry: {
58
type: 'url',
59
default: 'https://registry.npmjs.org/',
60
description: 'npm registry URL'
61
},
62
'save-dev': {
63
type: Boolean,
64
default: false,
65
description: 'save to devDependencies'
66
},
67
access: {
68
type: String,
69
default: 'public',
70
description: 'package access level'
71
}
72
},
73
shorthands: {
74
reg: ['--registry'],
75
D: ['--save-dev']
76
},
77
flatten: (obj) => obj,
78
npmPath: '/usr/local/lib/node_modules/npm'
79
});
80
```
81
82
### Configuration Loading
83
84
Load configuration from all sources in the proper hierarchy order.
85
86
```javascript { .api }
87
/**
88
* Load configuration from all sources (CLI, env, files, defaults)
89
* Must be called before accessing configuration values
90
* @returns Promise that resolves when all configuration is loaded
91
*/
92
load(): Promise<void>;
93
```
94
95
**Usage Example:**
96
97
```javascript
98
await config.load();
99
// Configuration is now loaded and ready to use
100
```
101
102
### Configuration Access
103
104
Get configuration values with optional source specification.
105
106
```javascript { .api }
107
/**
108
* Get configuration value by key
109
* @param key - Configuration key to retrieve
110
* @param where - Optional source to check ('cli', 'env', 'project', etc.)
111
* @returns Configuration value or undefined if not found
112
*/
113
get(key: string, where?: string): any;
114
115
/**
116
* Find which configuration source contains a key
117
* @param key - Configuration key to locate
118
* @returns Source name or null if not found
119
*/
120
find(key: string): string | null;
121
122
/**
123
* Check if a configuration value is from defaults
124
* @param key - Configuration key to check
125
* @returns True if value is from defaults, false otherwise
126
*/
127
isDefault(key: string): boolean;
128
```
129
130
**Usage Examples:**
131
132
```javascript
133
// Get value from any source (follows precedence)
134
const registry = config.get('registry');
135
136
// Get value from specific source
137
const cliRegistry = config.get('registry', 'cli');
138
139
// Find which source provides a value
140
const source = config.find('registry'); // Returns 'env', 'user', etc.
141
142
// Check if using default value
143
const isDefault = config.isDefault('registry');
144
```
145
146
### Configuration Modification
147
148
Set and delete configuration values with source specification.
149
150
```javascript { .api }
151
/**
152
* Set configuration value
153
* @param key - Configuration key to set
154
* @param value - Value to set
155
* @param where - Target configuration source ('cli', 'env', 'user', 'global', 'project')
156
*/
157
set(key: string, value: any, where?: string): void;
158
159
/**
160
* Delete configuration value from source
161
* @param key - Configuration key to delete
162
* @param where - Target configuration source
163
*/
164
delete(key: string, where?: string): void;
165
```
166
167
**Usage Examples:**
168
169
```javascript
170
// Set value in user configuration
171
config.set('registry', 'https://private-registry.com/', 'user');
172
173
// Set value in project configuration
174
config.set('save-dev', true, 'project');
175
176
// Delete value from global configuration
177
config.delete('registry', 'global');
178
```
179
180
### Configuration Validation
181
182
Validate configuration values and repair invalid entries.
183
184
```javascript { .api }
185
/**
186
* Validate configuration values
187
* @param where - Optional source to validate ('cli', 'env', 'user', etc.)
188
* @returns True if all values are valid, false otherwise
189
*/
190
validate(where?: string): boolean;
191
192
/**
193
* Repair configuration problems
194
* @param problems - Optional array of validation problems to fix
195
*/
196
repair(problems?: ValidationProblem[]): void;
197
198
interface ValidationProblem {
199
/** Configuration path that has an issue */
200
path: string;
201
/** Description of the problem */
202
message: string;
203
}
204
```
205
206
**Usage Examples:**
207
208
```javascript
209
// Validate all configuration
210
const isValid = config.validate();
211
212
// Validate specific source
213
const userValid = config.validate('user');
214
215
// Repair configuration issues
216
if (!config.valid) {
217
config.repair();
218
}
219
```
220
221
### Configuration Persistence
222
223
Save configuration to files with proper permissions.
224
225
```javascript { .api }
226
/**
227
* Save configuration to file
228
* @param where - Target configuration file ('user', 'global', 'project')
229
* @returns Promise that resolves when configuration is saved
230
*/
231
save(where: string): Promise<void>;
232
```
233
234
**Usage Examples:**
235
236
```javascript
237
// Save to user configuration file (~/.npmrc)
238
await config.save('user');
239
240
// Save to global configuration file
241
await config.save('global');
242
243
// Save to project configuration file (./.npmrc)
244
await config.save('project');
245
```
246
247
### Static Properties
248
249
Access configuration type definitions and metadata.
250
251
```javascript { .api }
252
/**
253
* Static getter for configuration type definitions
254
* @returns Complete type definitions object used for validation
255
*/
256
static get typeDefs(): Record<string, TypeDefinition>;
257
```
258
259
**Usage Examples:**
260
261
```javascript
262
// Access type definitions for validation
263
const typeDefs = Config.typeDefs;
264
console.log(typeDefs.semver.description); // "full valid SemVer string"
265
266
// Check available types
267
Object.keys(Config.typeDefs).forEach(type => {
268
console.log(`${type}: ${Config.typeDefs[type].description}`);
269
});
270
```
271
272
### Configuration Properties
273
274
Access configuration state and data structures.
275
276
```javascript { .api }
277
// Instance properties
278
interface Config {
279
/** Boolean indicating if configuration has been loaded */
280
loaded: boolean;
281
282
/** Boolean indicating if all configuration is valid */
283
valid: boolean;
284
285
/** Flattened configuration options object */
286
flat: Record<string, any>;
287
288
/** Array of configuration data objects in priority order */
289
list: ConfigData[];
290
291
/** Map of configuration data by type */
292
data: Map<string, ConfigData>;
293
294
/** Map of configuration sources to types */
295
sources: Map<string, string>;
296
297
/** Configuration field definitions */
298
definitions: Record<string, ConfigDefinition>;
299
300
/** Default configuration values */
301
defaults: Record<string, any>;
302
303
/** Deprecated configuration keys */
304
deprecated: Record<string, string | boolean>;
305
306
/** Current npm installation path */
307
npmPath: string;
308
309
/** Global npm prefix path */
310
globalPrefix: string;
311
312
/** Local project prefix path */
313
localPrefix: string;
314
315
/** Current effective prefix (globalPrefix or localPrefix based on global setting) */
316
prefix: string;
317
318
/** Command line arguments */
319
argv: string[];
320
321
/** Environment variables */
322
env: Record<string, string>;
323
324
/** Raw configuration data (getter/setter) */
325
raw: any;
326
327
/** Load error information (getter/setter) */
328
loadError: Error | null;
329
}
330
331
interface ConfigData {
332
/** Configuration values */
333
data: Record<string, any>;
334
/** Source identifier */
335
source: string;
336
}
337
```
338
339
### Field Parsing
340
341
Parse and coerce configuration field values according to type definitions.
342
343
```javascript { .api }
344
/**
345
* Parse configuration field value with type coercion
346
* @param field - Field definition
347
* @param key - Configuration key
348
* @param listElement - Whether this is an array element
349
* @returns Parsed and coerced value
350
*/
351
parseField(field: any, key: string, listElement?: boolean): any;
352
```
353
354
### Environment Integration
355
356
Set environment variables based on configuration values.
357
358
```javascript { .api }
359
/**
360
* Set npm_config_* environment variables based on configuration
361
* Only sets variables that differ from defaults
362
*/
363
setEnvs(): void;
364
365
/**
366
* Handle invalid configuration values (internal method)
367
* Called when configuration validation fails for a field
368
* @param key - Configuration key with invalid value
369
* @param value - Invalid value that failed validation
370
* @param type - Expected type or type array
371
* @param source - Configuration source where invalid value was found
372
* @param where - Configuration location identifier
373
*/
374
invalidHandler(key: string, value: any, type: any, source: string, where: string): void;
375
```
376
377
**Usage Example:**
378
379
```javascript
380
// Set environment variables for child processes
381
config.setEnvs();
382
383
// Now npm_config_registry, npm_config_loglevel, etc. are set
384
// in process.env for child processes to inherit
385
```
386
387
### Advanced Configuration Loading
388
389
Granular control over configuration loading from specific sources.
390
391
```javascript { .api }
392
/**
393
* Load default configuration values
394
* Sets up built-in defaults for all configuration keys
395
*/
396
loadDefaults(): void;
397
398
/**
399
* Load environment variables into configuration
400
* Processes npm_config_* environment variables
401
*/
402
loadEnv(): void;
403
404
/**
405
* Load command line interface configuration
406
* Processes command line arguments into configuration
407
*/
408
loadCLI(): void;
409
410
/**
411
* Load built-in npm configuration
412
* Loads npm's internal configuration settings
413
*/
414
loadBuiltinConfig(): void;
415
416
/**
417
* Load project-level configuration file (.npmrc)
418
* @returns Promise that resolves when project config is loaded
419
*/
420
loadProjectConfig(): Promise<void>;
421
422
/**
423
* Load user-level configuration file (~/.npmrc)
424
* @returns Promise that resolves when user config is loaded
425
*/
426
loadUserConfig(): Promise<void>;
427
428
/**
429
* Load global configuration file
430
* @returns Promise that resolves when global config is loaded
431
*/
432
loadGlobalConfig(): Promise<void>;
433
434
/**
435
* Load and set home directory path
436
* Determines user home directory from environment
437
*/
438
loadHome(): void;
439
440
/**
441
* Load and set global npm prefix
442
* Determines global installation prefix
443
*/
444
loadGlobalPrefix(): void;
445
446
/**
447
* Load and set local project prefix
448
* Determines local project directory and workspace configuration
449
* @returns Promise that resolves when local prefix is set
450
*/
451
loadLocalPrefix(): Promise<void>;
452
```
453
454
**Usage Examples:**
455
456
```javascript
457
// Load only specific configuration sources
458
const config = new Config({ definitions, shorthands, flatten, npmPath });
459
460
// Load defaults first
461
config.loadDefaults();
462
463
// Load only environment variables
464
config.loadEnv();
465
466
// Load only CLI arguments
467
config.loadCLI();
468
469
// For advanced use cases, you might load specific files
470
await config.loadUserConfig();
471
await config.loadProjectConfig();
472
473
// Note: The main load() method calls all of these in the correct order
474
// These individual methods are for advanced configuration scenarios
475
```