CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-npmcli--config

Configuration management for the npm command-line interface with hierarchical layered configuration system.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

config-management.mddocs/

Configuration Management

Core configuration management functionality providing hierarchical configuration loading, validation, and manipulation with support for multiple configuration sources.

Capabilities

Config Class Constructor

Creates a new configuration instance with type definitions, shorthands, and environment settings.

/**
 * Create a new Config instance
 * @param options - Configuration options including definitions, shorthands, and paths
 */
constructor(options: ConfigOptions);

interface ConfigOptions {
  /** Configuration field definitions with types and defaults */
  definitions: Record<string, ConfigDefinition>;
  /** Command line shorthand mappings */
  shorthands?: Record<string, string[]>;
  /** Configuration flattening function */
  flatten?: (obj: any) => any;
  /** Path to npm installation */
  npmPath: string;
  /** Environment variables (defaults to process.env) */
  env?: Record<string, string>;
  /** Command line arguments (defaults to process.argv) */
  argv?: string[];
  /** Operating system platform (defaults to process.platform) */
  platform?: string;
  /** Node.js executable path (defaults to process.execPath) */
  execPath?: string;
  /** Current working directory (defaults to process.cwd()) */
  cwd?: string;
}

interface ConfigDefinition {
  /** Field type (String, Number, Boolean, Array, etc.) */
  type: any;
  /** Default value for the field */
  default?: any;
  /** Human-readable description */
  description?: string;
  /** Deprecation message or boolean flag */
  deprecated?: string | boolean;
}

Usage Example:

const { Config } = require('@npmcli/config');

const config = new Config({
  definitions: {
    registry: {
      type: 'url',
      default: 'https://registry.npmjs.org/',
      description: 'npm registry URL'
    },
    'save-dev': {
      type: Boolean,
      default: false,
      description: 'save to devDependencies'
    },
    access: {
      type: String,
      default: 'public',
      description: 'package access level'
    }
  },
  shorthands: {
    reg: ['--registry'],
    D: ['--save-dev']
  },
  flatten: (obj) => obj,
  npmPath: '/usr/local/lib/node_modules/npm'
});

Configuration Loading

Load configuration from all sources in the proper hierarchy order.

/**
 * Load configuration from all sources (CLI, env, files, defaults)
 * Must be called before accessing configuration values
 * @returns Promise that resolves when all configuration is loaded
 */
load(): Promise<void>;

Usage Example:

await config.load();
// Configuration is now loaded and ready to use

Configuration Access

Get configuration values with optional source specification.

/**
 * Get configuration value by key
 * @param key - Configuration key to retrieve
 * @param where - Optional source to check ('cli', 'env', 'project', etc.)
 * @returns Configuration value or undefined if not found
 */
get(key: string, where?: string): any;

/**
 * Find which configuration source contains a key
 * @param key - Configuration key to locate
 * @returns Source name or null if not found
 */
find(key: string): string | null;

/**
 * Check if a configuration value is from defaults
 * @param key - Configuration key to check
 * @returns True if value is from defaults, false otherwise
 */
isDefault(key: string): boolean;

Usage Examples:

// Get value from any source (follows precedence)
const registry = config.get('registry');

// Get value from specific source
const cliRegistry = config.get('registry', 'cli');

// Find which source provides a value
const source = config.find('registry'); // Returns 'env', 'user', etc.

// Check if using default value
const isDefault = config.isDefault('registry');

Configuration Modification

Set and delete configuration values with source specification.

/**
 * Set configuration value
 * @param key - Configuration key to set
 * @param value - Value to set
 * @param where - Target configuration source ('cli', 'env', 'user', 'global', 'project')
 */
set(key: string, value: any, where?: string): void;

/**
 * Delete configuration value from source
 * @param key - Configuration key to delete
 * @param where - Target configuration source
 */
delete(key: string, where?: string): void;

Usage Examples:

// Set value in user configuration
config.set('registry', 'https://private-registry.com/', 'user');

// Set value in project configuration
config.set('save-dev', true, 'project');

// Delete value from global configuration
config.delete('registry', 'global');

Configuration Validation

Validate configuration values and repair invalid entries.

/**
 * Validate configuration values
 * @param where - Optional source to validate ('cli', 'env', 'user', etc.)
 * @returns True if all values are valid, false otherwise
 */
validate(where?: string): boolean;

/**
 * Repair configuration problems
 * @param problems - Optional array of validation problems to fix
 */
repair(problems?: ValidationProblem[]): void;

interface ValidationProblem {
  /** Configuration path that has an issue */
  path: string;
  /** Description of the problem */
  message: string;
}

Usage Examples:

// Validate all configuration
const isValid = config.validate();

// Validate specific source
const userValid = config.validate('user');

// Repair configuration issues
if (!config.valid) {
  config.repair();
}

Configuration Persistence

Save configuration to files with proper permissions.

/**
 * Save configuration to file
 * @param where - Target configuration file ('user', 'global', 'project')
 * @returns Promise that resolves when configuration is saved
 */
save(where: string): Promise<void>;

Usage Examples:

// Save to user configuration file (~/.npmrc)
await config.save('user');

// Save to global configuration file
await config.save('global');

// Save to project configuration file (./.npmrc)
await config.save('project');

Static Properties

Access configuration type definitions and metadata.

/**
 * Static getter for configuration type definitions
 * @returns Complete type definitions object used for validation
 */
static get typeDefs(): Record<string, TypeDefinition>;

Usage Examples:

// Access type definitions for validation
const typeDefs = Config.typeDefs;
console.log(typeDefs.semver.description); // "full valid SemVer string"

// Check available types
Object.keys(Config.typeDefs).forEach(type => {
  console.log(`${type}: ${Config.typeDefs[type].description}`);
});

Configuration Properties

Access configuration state and data structures.

// Instance properties
interface Config {
  /** Boolean indicating if configuration has been loaded */
  loaded: boolean;
  
  /** Boolean indicating if all configuration is valid */
  valid: boolean;
  
  /** Flattened configuration options object */
  flat: Record<string, any>;
  
  /** Array of configuration data objects in priority order */
  list: ConfigData[];
  
  /** Map of configuration data by type */
  data: Map<string, ConfigData>;
  
  /** Map of configuration sources to types */
  sources: Map<string, string>;
  
  /** Configuration field definitions */
  definitions: Record<string, ConfigDefinition>;
  
  /** Default configuration values */
  defaults: Record<string, any>;
  
  /** Deprecated configuration keys */
  deprecated: Record<string, string | boolean>;
  
  /** Current npm installation path */
  npmPath: string;
  
  /** Global npm prefix path */
  globalPrefix: string;
  
  /** Local project prefix path */
  localPrefix: string;
  
  /** Current effective prefix (globalPrefix or localPrefix based on global setting) */
  prefix: string;
  
  /** Command line arguments */
  argv: string[];
  
  /** Environment variables */
  env: Record<string, string>;
  
  /** Raw configuration data (getter/setter) */
  raw: any;
  
  /** Load error information (getter/setter) */
  loadError: Error | null;
}

interface ConfigData {
  /** Configuration values */
  data: Record<string, any>;
  /** Source identifier */
  source: string;
}

Field Parsing

Parse and coerce configuration field values according to type definitions.

/**
 * Parse configuration field value with type coercion
 * @param field - Field definition
 * @param key - Configuration key
 * @param listElement - Whether this is an array element
 * @returns Parsed and coerced value
 */
parseField(field: any, key: string, listElement?: boolean): any;

Environment Integration

Set environment variables based on configuration values.

/**
 * Set npm_config_* environment variables based on configuration
 * Only sets variables that differ from defaults
 */
setEnvs(): void;

/**
 * Handle invalid configuration values (internal method)
 * Called when configuration validation fails for a field
 * @param key - Configuration key with invalid value
 * @param value - Invalid value that failed validation
 * @param type - Expected type or type array
 * @param source - Configuration source where invalid value was found
 * @param where - Configuration location identifier
 */
invalidHandler(key: string, value: any, type: any, source: string, where: string): void;

Usage Example:

// Set environment variables for child processes
config.setEnvs();

// Now npm_config_registry, npm_config_loglevel, etc. are set
// in process.env for child processes to inherit

Advanced Configuration Loading

Granular control over configuration loading from specific sources.

/**
 * Load default configuration values
 * Sets up built-in defaults for all configuration keys
 */
loadDefaults(): void;

/**
 * Load environment variables into configuration
 * Processes npm_config_* environment variables
 */
loadEnv(): void;

/**
 * Load command line interface configuration
 * Processes command line arguments into configuration
 */
loadCLI(): void;

/**
 * Load built-in npm configuration
 * Loads npm's internal configuration settings
 */
loadBuiltinConfig(): void;

/**
 * Load project-level configuration file (.npmrc)
 * @returns Promise that resolves when project config is loaded
 */
loadProjectConfig(): Promise<void>;

/**
 * Load user-level configuration file (~/.npmrc)
 * @returns Promise that resolves when user config is loaded
 */
loadUserConfig(): Promise<void>;

/**
 * Load global configuration file
 * @returns Promise that resolves when global config is loaded
 */
loadGlobalConfig(): Promise<void>;

/**
 * Load and set home directory path
 * Determines user home directory from environment
 */
loadHome(): void;

/**
 * Load and set global npm prefix
 * Determines global installation prefix
 */
loadGlobalPrefix(): void;

/**
 * Load and set local project prefix
 * Determines local project directory and workspace configuration
 * @returns Promise that resolves when local prefix is set
 */
loadLocalPrefix(): Promise<void>;

Usage Examples:

// Load only specific configuration sources
const config = new Config({ definitions, shorthands, flatten, npmPath });

// Load defaults first
config.loadDefaults();

// Load only environment variables
config.loadEnv();

// Load only CLI arguments
config.loadCLI();

// For advanced use cases, you might load specific files
await config.loadUserConfig();
await config.loadProjectConfig();

// Note: The main load() method calls all of these in the correct order
// These individual methods are for advanced configuration scenarios

Install with Tessl CLI

npx tessl i tessl/npm-npmcli--config

docs

config-management.md

credentials.md

errors.md

index.md

utilities.md

tile.json