@utilarium/cardigantime 0.0.24 → 0.0.26-dev.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/dist/cardigantime.cjs +102 -5
- package/dist/cardigantime.cjs.map +1 -1
- package/dist/constants.js +1 -1
- package/dist/read.js +28 -2
- package/dist/read.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.js.map +1 -1
- package/dist/util/hierarchical.js +28 -2
- package/dist/util/hierarchical.js.map +1 -1
- package/dist/util/path-detection.d.ts +11 -0
- package/dist/util/path-normalization.d.ts +10 -0
- package/dist/util/path-normalization.js +49 -0
- package/dist/util/path-normalization.js.map +1 -0
- package/dist/util/path-validation.d.ts +12 -0
- package/package.json +1 -1
package/dist/constants.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Version string populated at build time with git and system information */ const VERSION = '0.0.
|
|
1
|
+
/** Version string populated at build time with git and system information */ const VERSION = '0.0.26-dev.0 (working/7f90b30 2026-01-31 11:42:20 -0800) linux x64 v24.13.0';
|
|
2
2
|
/** The program name used in CLI help and error messages */ const PROGRAM_NAME = 'cardigantime';
|
|
3
3
|
/** Default file encoding for reading configuration files */ const DEFAULT_ENCODING = 'utf8';
|
|
4
4
|
/** Default configuration file name to look for in the config directory */ const DEFAULT_CONFIG_FILE = 'config.yaml';
|
package/dist/read.js
CHANGED
|
@@ -2,6 +2,7 @@ import * as yaml from 'js-yaml';
|
|
|
2
2
|
import * as path from 'node:path';
|
|
3
3
|
import { create } from './util/storage.js';
|
|
4
4
|
import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
5
|
+
import { normalizePathInput } from './util/path-normalization.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Removes undefined values from an object to create a clean configuration.
|
|
@@ -30,8 +31,11 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
30
31
|
for (const fieldPath of pathFields){
|
|
31
32
|
const value = getNestedValue(resolvedConfig, fieldPath);
|
|
32
33
|
if (value !== undefined) {
|
|
34
|
+
// Step 1: Normalize input (convert file:// URLs, reject http/https)
|
|
35
|
+
const normalizedValue = normalizePathInput(value);
|
|
36
|
+
// Step 2: Resolve paths relative to config directory
|
|
33
37
|
const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);
|
|
34
|
-
const resolvedValue = resolvePathValue(
|
|
38
|
+
const resolvedValue = resolvePathValue(normalizedValue, configDir, shouldResolveArrayElements);
|
|
35
39
|
setNestedValue(resolvedConfig, fieldPath, resolvedValue);
|
|
36
40
|
}
|
|
37
41
|
}
|
|
@@ -70,7 +74,13 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
70
74
|
target[lastKey] = value;
|
|
71
75
|
}
|
|
72
76
|
/**
|
|
73
|
-
* Resolves a path value (string
|
|
77
|
+
* Resolves a path value (string, array, or object) relative to the config directory.
|
|
78
|
+
*
|
|
79
|
+
* Handles:
|
|
80
|
+
* - Strings: Resolved relative to configDir
|
|
81
|
+
* - Arrays: Elements resolved if resolveArrayElements is true
|
|
82
|
+
* - Objects: All string values and array elements resolved recursively
|
|
83
|
+
* - Other types: Returned unchanged
|
|
74
84
|
*/ function resolvePathValue(value, configDir, resolveArrayElements) {
|
|
75
85
|
if (typeof value === 'string') {
|
|
76
86
|
return resolveSinglePath(value, configDir);
|
|
@@ -78,6 +88,22 @@ import { loadHierarchicalConfig } from './util/hierarchical.js';
|
|
|
78
88
|
if (Array.isArray(value) && resolveArrayElements) {
|
|
79
89
|
return value.map((item)=>typeof item === 'string' ? resolveSinglePath(item, configDir) : item);
|
|
80
90
|
}
|
|
91
|
+
// NEW: Handle objects with string values
|
|
92
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
93
|
+
const resolved = {};
|
|
94
|
+
for (const [key, val] of Object.entries(value)){
|
|
95
|
+
if (typeof val === 'string') {
|
|
96
|
+
resolved[key] = resolveSinglePath(val, configDir);
|
|
97
|
+
} else if (Array.isArray(val)) {
|
|
98
|
+
// Also handle arrays within objects
|
|
99
|
+
resolved[key] = val.map((item)=>typeof item === 'string' ? resolveSinglePath(item, configDir) : item);
|
|
100
|
+
} else {
|
|
101
|
+
// Keep other types unchanged
|
|
102
|
+
resolved[key] = val;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return resolved;
|
|
106
|
+
}
|
|
81
107
|
return value;
|
|
82
108
|
}
|
|
83
109
|
/**
|
package/dist/read.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig, DiscoveredConfigDir } from './util/hierarchical';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n * \n * @param config - The configuration object to process\n * @param configDir - The directory containing the configuration file\n * @param pathFields - Array of field names (using dot notation) that contain paths to be resolved\n * @param resolvePathArray - Array of field names whose array elements should all be resolved as paths\n * @returns The configuration object with resolved paths\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(value, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Checks if a key is unsafe for prototype pollution prevention.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n * Prevents prototype pollution by rejecting dangerous property names.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string or array of strings) relative to the config directory.\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n let discoveredConfigDirs: string[] = [];\n let resolvedConfigDirs: string[] = [];\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredConfigDirs = hierarchicalResult.discoveredDirs.map(dir => dir.path);\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs.map(dir => dir.path);\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.resolvedConfigDirs.length > 0) {\n logger.verbose(`Found ${hierarchicalResult.resolvedConfigDirs.length} directories with actual configuration files`);\n hierarchicalResult.resolvedConfigDirs.forEach(dir => {\n logger.debug(` Config dir level ${dir.level}: ${dir.path}`);\n });\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in both arrays (discovered but check if it had config)\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...processedConfig,\n ...{\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs,\n resolvedConfigDirs,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger: any\n): Promise<string | null> {\n // Validate the config file name to prevent path traversal\n const configFilePath = validatePath(configFileName, configDir);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativeFileName = baseName + alternativeExt;\n const alternativePath = validatePath(alternativeFileName, configDir);\n \n logger.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(\n storage,\n resolvedConfigDir,\n options.defaults.configFile,\n logger\n );\n \n if (!configFilePath) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n return rawFileConfig;\n }\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n // Re-throw security-related errors (path validation failures)\n if (error.message && /Invalid path|path traversal|absolute path/i.test(error.message)) {\n throw error;\n }\n \n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}\n\n/**\n * Represents a configuration value with its source information.\n */\ninterface ConfigSourceInfo {\n /** The configuration value */\n value: any;\n /** Path to the configuration file that provided this value */\n sourcePath: string;\n /** Hierarchical level (0 = closest/highest precedence) */\n level: number;\n /** Short description of the source for display */\n sourceLabel: string;\n}\n\n/**\n * Tracks configuration values to their sources during hierarchical loading.\n */\ninterface ConfigSourceTracker {\n [key: string]: ConfigSourceInfo;\n}\n\n/**\n * Recursively tracks the source of configuration values from hierarchical loading.\n * \n * @param config - The configuration object to track\n * @param sourcePath - Path to the configuration file\n * @param level - Hierarchical level\n * @param prefix - Current object path prefix for nested values\n * @param tracker - The tracker object to populate\n */\nfunction trackConfigSources(\n config: any,\n sourcePath: string,\n level: number,\n prefix: string = '',\n tracker: ConfigSourceTracker = {}\n): ConfigSourceTracker {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n // For primitives and arrays, track the entire value\n tracker[prefix] = {\n value: config,\n sourcePath,\n level,\n sourceLabel: `Level ${level}: ${path.basename(path.dirname(sourcePath))}`\n };\n return tracker;\n }\n\n // For objects, recursively track each property\n for (const [key, value] of Object.entries(config)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n trackConfigSources(value, sourcePath, level, fieldPath, tracker);\n }\n\n return tracker;\n}\n\n/**\n * Merges multiple configuration source trackers with proper precedence.\n * Lower level numbers have higher precedence.\n * \n * @param trackers - Array of trackers from different config sources\n * @returns Merged tracker with proper precedence\n */\nfunction mergeConfigTrackers(trackers: ConfigSourceTracker[]): ConfigSourceTracker {\n const merged: ConfigSourceTracker = {};\n\n for (const tracker of trackers) {\n for (const [key, info] of Object.entries(tracker)) {\n // Only update if we don't have this key yet, or if this source has higher precedence (lower level)\n if (!merged[key] || info.level < merged[key].level) {\n merged[key] = info;\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Formats a configuration value for display, handling different types appropriately.\n * \n * @param value - The configuration value to format\n * @returns Formatted string representation\n */\nfunction formatConfigValue(value: any): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean') return value.toString();\n if (typeof value === 'number') return value.toString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n if (value.length <= 3) {\n return `[${value.map(formatConfigValue).join(', ')}]`;\n }\n return `[${value.slice(0, 2).map(formatConfigValue).join(', ')}, ... (${value.length} items)]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value);\n if (keys.length === 0) return '{}';\n if (keys.length <= 2) {\n return `{${keys.slice(0, 2).join(', ')}}`;\n }\n return `{${keys.slice(0, 2).join(', ')}, ... (${keys.length} keys)}`;\n }\n return String(value);\n}\n\n/**\n * Displays configuration with source tracking in a git blame-like format.\n * \n * @param config - The resolved configuration object\n * @param tracker - Configuration source tracker\n * @param discoveredDirs - Array of discovered configuration directories\n * @param logger - Logger instance for output\n */\nfunction displayConfigWithSources(\n config: any,\n tracker: ConfigSourceTracker,\n discoveredDirs: DiscoveredConfigDir[],\n logger: any\n): void {\n logger.info('\\n' + '='.repeat(80));\n logger.info('CONFIGURATION SOURCE ANALYSIS');\n logger.info('='.repeat(80));\n\n // Display discovered configuration hierarchy\n logger.info('\\nDISCOVERED CONFIGURATION HIERARCHY:');\n if (discoveredDirs.length === 0) {\n logger.info(' No configuration directories found in hierarchy');\n } else {\n discoveredDirs\n .sort((a, b) => a.level - b.level) // Sort by precedence (lower level = higher precedence)\n .forEach(dir => {\n const precedence = dir.level === 0 ? '(highest precedence)' :\n dir.level === Math.max(...discoveredDirs.map(d => d.level)) ? '(lowest precedence)' :\n '';\n logger.info(` Level ${dir.level}: ${dir.path} ${precedence}`);\n });\n }\n\n // Display resolved configuration with sources\n logger.info('\\nRESOLVED CONFIGURATION WITH SOURCES:');\n logger.info('Format: [Source] key: value\\n');\n\n const sortedKeys = Object.keys(tracker).sort();\n const maxKeyLength = Math.max(...sortedKeys.map(k => k.length), 20);\n const maxSourceLength = Math.max(...Object.values(tracker).map(info => info.sourceLabel.length), 25);\n\n for (const key of sortedKeys) {\n const info = tracker[key];\n const paddedKey = key.padEnd(maxKeyLength);\n const paddedSource = info.sourceLabel.padEnd(maxSourceLength);\n const formattedValue = formatConfigValue(info.value);\n\n logger.info(`[${paddedSource}] ${paddedKey}: ${formattedValue}`);\n }\n\n // Display summary\n logger.info('\\n' + '-'.repeat(80));\n logger.info('SUMMARY:');\n logger.info(` Total configuration keys: ${Object.keys(tracker).length}`);\n logger.info(` Configuration sources: ${discoveredDirs.length}`);\n\n // Count values by source\n const sourceCount: { [source: string]: number } = {};\n for (const info of Object.values(tracker)) {\n sourceCount[info.sourceLabel] = (sourceCount[info.sourceLabel] || 0) + 1;\n }\n\n logger.info(' Values by source:');\n for (const [source, count] of Object.entries(sourceCount)) {\n logger.info(` ${source}: ${count} value(s)`);\n }\n\n logger.info('='.repeat(80));\n}\n\n/**\n * Checks and displays the resolved configuration with detailed source tracking.\n * \n * This function provides a git blame-like view of configuration resolution,\n * showing which file and hierarchical level contributed each configuration value.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise that resolves when the configuration check is complete\n * \n * @example\n * ```typescript\n * await checkConfig(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config', 'hierarchical']\n * });\n * // Outputs detailed configuration source analysis\n * ```\n */\nexport const checkConfig = async <T extends z.ZodRawShape>(\n args: Args,\n options: Options<T>\n): Promise<void> => {\n const logger = options.logger;\n\n logger.info('Starting configuration check...');\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose(`Resolved config directory: ${resolvedConfigDir}`);\n\n let rawFileConfig: object = {};\n let discoveredDirs: DiscoveredConfigDir[] = [];\n let resolvedConfigDirs: DiscoveredConfigDir[] = [];\n let tracker: ConfigSourceTracker = {};\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Using hierarchical configuration discovery for source tracking');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredDirs = hierarchicalResult.discoveredDirs;\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs;\n\n // Build detailed source tracking by re-loading each config individually\n const trackers: ConfigSourceTracker[] = [];\n\n // Sort by level (highest level first = lowest precedence first) to match merge order\n const sortedDirs = [...resolvedConfigDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n const storage = Storage.create({ log: logger.debug });\n const configFilePath = path.join(dir.path, options.defaults.configFile);\n\n try {\n const exists = await storage.exists(configFilePath);\n if (!exists) continue;\n\n const isReadable = await storage.isFileReadable(configFilePath);\n if (!isReadable) continue;\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n const levelTracker = trackConfigSources(parsedYaml, configFilePath, dir.level);\n trackers.push(levelTracker);\n }\n } catch (error: any) {\n logger.debug(`Error loading config for source tracking from ${configFilePath}: ${error.message}`);\n }\n }\n\n // Merge trackers with proper precedence\n tracker = mergeConfigTrackers(trackers);\n\n if (hierarchicalResult.errors.length > 0) {\n logger.warn('Configuration loading warnings:');\n hierarchicalResult.errors.forEach(error => logger.warn(` ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n logger.verbose('Falling back to single directory configuration loading');\n\n // Fall back to single directory mode for source tracking\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading for source tracking');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured (this doesn't change source tracking)\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n // Build final configuration including built-in values\n const finalConfig = clean({\n ...processedConfig,\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs: discoveredDirs.map(dir => dir.path),\n resolvedConfigDirs: resolvedConfigDirs.map(dir => dir.path),\n });\n\n // Add built-in configuration to tracker\n tracker['configDirectory'] = {\n value: resolvedConfigDir,\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['discoveredConfigDirs'] = {\n value: discoveredDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['resolvedConfigDirs'] = {\n value: resolvedConfigDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n // Display the configuration with source information\n displayConfigWithSources(finalConfig, tracker, discoveredDirs, logger);\n};"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","length","resolvedConfig","fieldPath","value","getNestedValue","shouldResolveArrayElements","includes","resolvedValue","resolvePathValue","setNestedValue","path","split","reduce","current","key","isUnsafeKey","keys","lastKey","pop","some","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","pathStr","isAbsolute","resolve","validatePath","userPath","basePath","Error","normalized","normalize","startsWith","join","validateConfigDirectory","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","discoveredConfigDirs","resolvedConfigDirs","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","pathResolution","fieldOverlaps","discoveredDirs","dir","forEach","level","errors","error","warn","message","loadSingleDirectoryConfig","processedConfig","findConfigFileWithExtension","storage","configFilePath","exists","isReadable","isFileReadable","ext","extname","baseName","alternativeExt","alternativeFileName","alternativePath","altExists","altIsReadable","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","test","code","trackConfigSources","sourcePath","prefix","tracker","sourceLabel","mergeConfigTrackers","trackers","merged","info","formatConfigValue","toString","slice","String","displayConfigWithSources","repeat","sort","a","b","precedence","Math","max","d","sortedKeys","maxKeyLength","k","maxSourceLength","values","paddedKey","padEnd","paddedSource","formattedValue","sourceCount","source","count","checkConfig","sortedDirs","levelTracker","push","finalConfig"],"mappings":";;;;;AAOA;;;;;;IAOA,SAASA,MAAMC,GAAQ,EAAA;AACnB,IAAA,OAAOC,MAAAA,CAAOC,WAAW,CACrBD,MAAAA,CAAOE,OAAO,CAACH,GAAAA,CAAAA,CAAKI,MAAM,CAAC,CAAC,CAACC,CAAAA,EAAGC,CAAAA,CAAE,GAAKA,CAAAA,KAAMC,SAAAA,CAAAA,CAAAA;AAErD;AAEA;;;;;;;;IASA,SAASC,kBAAAA,CACLC,MAAW,EACXC,SAAiB,EACjBC,UAAAA,GAAuB,EAAE,EACzBC,gBAAAA,GAA6B,EAAE,EAAA;IAE/B,IAAI,CAACH,UAAU,OAAOA,MAAAA,KAAW,YAAYE,UAAAA,CAAWE,MAAM,KAAK,CAAA,EAAG;QAClE,OAAOJ,MAAAA;AACX,IAAA;AAEA,IAAA,MAAMK,cAAAA,GAAiB;AAAE,QAAA,GAAGL;AAAO,KAAA;IAEnC,KAAK,MAAMM,aAAaJ,UAAAA,CAAY;QAChC,MAAMK,KAAAA,GAAQC,eAAeH,cAAAA,EAAgBC,SAAAA,CAAAA;AAC7C,QAAA,IAAIC,UAAUT,SAAAA,EAAW;YACrB,MAAMW,0BAAAA,GAA6BN,gBAAAA,CAAiBO,QAAQ,CAACJ,SAAAA,CAAAA;YAC7D,MAAMK,aAAAA,GAAgBC,gBAAAA,CAAiBL,KAAAA,EAAON,SAAAA,EAAWQ,0BAAAA,CAAAA;AACzDI,YAAAA,cAAAA,CAAeR,gBAAgBC,SAAAA,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GA0F,OAAO,CAAC,kBAAkB,GAAG;QACzBjG,KAAAA,EAAO2C,iBAAAA;QACPoD,UAAAA,EAAY,UAAA;AACZ/B,QAAAA,KAAAA,EAAO,EAAC;QACRkC,WAAAA,EAAa;AACjB,KAAA;IAEAD,OAAO,CAAC,uBAAuB,GAAG;AAC9BjG,QAAAA,KAAAA,EAAO6D,eAAevC,GAAG,CAACwC,CAAAA,GAAAA,GAAOA,IAAIvD,IAAI,CAAA;QACzCwF,UAAAA,EAAY,UAAA;AACZ/B,QAAAA,KAAAA,EAAO,EAAC;QACRkC,WAAAA,EAAa;AACjB,KAAA;IAEAD,OAAO,CAAC,qBAAqB,GAAG;AAC5BjG,QAAAA,KAAAA,EAAO+C,mBAAmBzB,GAAG,CAACwC,CAAAA,GAAAA,GAAOA,IAAIvD,IAAI,CAAA;QAC7CwF,UAAAA,EAAY,UAAA;AACZ/B,QAAAA,KAAAA,EAAO,EAAC;QACRkC,WAAAA,EAAa;AACjB,KAAA;;IAGAS,wBAAAA,CAAyByB,WAAAA,EAAanC,SAASpC,cAAAA,EAAgBtB,MAAAA,CAAAA;AACnE;;;;"}
|
|
1
|
+
{"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig, DiscoveredConfigDir } from './util/hierarchical';\nimport { normalizePathInput } from './util/path-normalization';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n * \n * @param config - The configuration object to process\n * @param configDir - The directory containing the configuration file\n * @param pathFields - Array of field names (using dot notation) that contain paths to be resolved\n * @param resolvePathArray - Array of field names whose array elements should all be resolved as paths\n * @returns The configuration object with resolved paths\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n // Step 1: Normalize input (convert file:// URLs, reject http/https)\n const normalizedValue = normalizePathInput(value);\n \n // Step 2: Resolve paths relative to config directory\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(normalizedValue, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Checks if a key is unsafe for prototype pollution prevention.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n * Prevents prototype pollution by rejecting dangerous property names.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string, array, or object) relative to the config directory.\n * \n * Handles:\n * - Strings: Resolved relative to configDir\n * - Arrays: Elements resolved if resolveArrayElements is true\n * - Objects: All string values and array elements resolved recursively\n * - Other types: Returned unchanged\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n // NEW: Handle objects with string values\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const resolved: any = {};\n for (const [key, val] of Object.entries(value)) {\n if (typeof val === 'string') {\n resolved[key] = resolveSinglePath(val, configDir);\n } else if (Array.isArray(val)) {\n // Also handle arrays within objects\n resolved[key] = val.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n } else {\n // Keep other types unchanged\n resolved[key] = val;\n }\n }\n return resolved;\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n let discoveredConfigDirs: string[] = [];\n let resolvedConfigDirs: string[] = [];\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredConfigDirs = hierarchicalResult.discoveredDirs.map(dir => dir.path);\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs.map(dir => dir.path);\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.resolvedConfigDirs.length > 0) {\n logger.verbose(`Found ${hierarchicalResult.resolvedConfigDirs.length} directories with actual configuration files`);\n hierarchicalResult.resolvedConfigDirs.forEach(dir => {\n logger.debug(` Config dir level ${dir.level}: ${dir.path}`);\n });\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in both arrays (discovered but check if it had config)\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...processedConfig,\n ...{\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs,\n resolvedConfigDirs,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger: any\n): Promise<string | null> {\n // Validate the config file name to prevent path traversal\n const configFilePath = validatePath(configFileName, configDir);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativeFileName = baseName + alternativeExt;\n const alternativePath = validatePath(alternativeFileName, configDir);\n \n logger.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(\n storage,\n resolvedConfigDir,\n options.defaults.configFile,\n logger\n );\n \n if (!configFilePath) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n return rawFileConfig;\n }\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n // Re-throw security-related errors (path validation failures)\n if (error.message && /Invalid path|path traversal|absolute path/i.test(error.message)) {\n throw error;\n }\n \n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}\n\n/**\n * Represents a configuration value with its source information.\n */\ninterface ConfigSourceInfo {\n /** The configuration value */\n value: any;\n /** Path to the configuration file that provided this value */\n sourcePath: string;\n /** Hierarchical level (0 = closest/highest precedence) */\n level: number;\n /** Short description of the source for display */\n sourceLabel: string;\n}\n\n/**\n * Tracks configuration values to their sources during hierarchical loading.\n */\ninterface ConfigSourceTracker {\n [key: string]: ConfigSourceInfo;\n}\n\n/**\n * Recursively tracks the source of configuration values from hierarchical loading.\n * \n * @param config - The configuration object to track\n * @param sourcePath - Path to the configuration file\n * @param level - Hierarchical level\n * @param prefix - Current object path prefix for nested values\n * @param tracker - The tracker object to populate\n */\nfunction trackConfigSources(\n config: any,\n sourcePath: string,\n level: number,\n prefix: string = '',\n tracker: ConfigSourceTracker = {}\n): ConfigSourceTracker {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n // For primitives and arrays, track the entire value\n tracker[prefix] = {\n value: config,\n sourcePath,\n level,\n sourceLabel: `Level ${level}: ${path.basename(path.dirname(sourcePath))}`\n };\n return tracker;\n }\n\n // For objects, recursively track each property\n for (const [key, value] of Object.entries(config)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n trackConfigSources(value, sourcePath, level, fieldPath, tracker);\n }\n\n return tracker;\n}\n\n/**\n * Merges multiple configuration source trackers with proper precedence.\n * Lower level numbers have higher precedence.\n * \n * @param trackers - Array of trackers from different config sources\n * @returns Merged tracker with proper precedence\n */\nfunction mergeConfigTrackers(trackers: ConfigSourceTracker[]): ConfigSourceTracker {\n const merged: ConfigSourceTracker = {};\n\n for (const tracker of trackers) {\n for (const [key, info] of Object.entries(tracker)) {\n // Only update if we don't have this key yet, or if this source has higher precedence (lower level)\n if (!merged[key] || info.level < merged[key].level) {\n merged[key] = info;\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Formats a configuration value for display, handling different types appropriately.\n * \n * @param value - The configuration value to format\n * @returns Formatted string representation\n */\nfunction formatConfigValue(value: any): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean') return value.toString();\n if (typeof value === 'number') return value.toString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n if (value.length <= 3) {\n return `[${value.map(formatConfigValue).join(', ')}]`;\n }\n return `[${value.slice(0, 2).map(formatConfigValue).join(', ')}, ... (${value.length} items)]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value);\n if (keys.length === 0) return '{}';\n if (keys.length <= 2) {\n return `{${keys.slice(0, 2).join(', ')}}`;\n }\n return `{${keys.slice(0, 2).join(', ')}, ... (${keys.length} keys)}`;\n }\n return String(value);\n}\n\n/**\n * Displays configuration with source tracking in a git blame-like format.\n * \n * @param config - The resolved configuration object\n * @param tracker - Configuration source tracker\n * @param discoveredDirs - Array of discovered configuration directories\n * @param logger - Logger instance for output\n */\nfunction displayConfigWithSources(\n config: any,\n tracker: ConfigSourceTracker,\n discoveredDirs: DiscoveredConfigDir[],\n logger: any\n): void {\n logger.info('\\n' + '='.repeat(80));\n logger.info('CONFIGURATION SOURCE ANALYSIS');\n logger.info('='.repeat(80));\n\n // Display discovered configuration hierarchy\n logger.info('\\nDISCOVERED CONFIGURATION HIERARCHY:');\n if (discoveredDirs.length === 0) {\n logger.info(' No configuration directories found in hierarchy');\n } else {\n discoveredDirs\n .sort((a, b) => a.level - b.level) // Sort by precedence (lower level = higher precedence)\n .forEach(dir => {\n const precedence = dir.level === 0 ? '(highest precedence)' :\n dir.level === Math.max(...discoveredDirs.map(d => d.level)) ? '(lowest precedence)' :\n '';\n logger.info(` Level ${dir.level}: ${dir.path} ${precedence}`);\n });\n }\n\n // Display resolved configuration with sources\n logger.info('\\nRESOLVED CONFIGURATION WITH SOURCES:');\n logger.info('Format: [Source] key: value\\n');\n\n const sortedKeys = Object.keys(tracker).sort();\n const maxKeyLength = Math.max(...sortedKeys.map(k => k.length), 20);\n const maxSourceLength = Math.max(...Object.values(tracker).map(info => info.sourceLabel.length), 25);\n\n for (const key of sortedKeys) {\n const info = tracker[key];\n const paddedKey = key.padEnd(maxKeyLength);\n const paddedSource = info.sourceLabel.padEnd(maxSourceLength);\n const formattedValue = formatConfigValue(info.value);\n\n logger.info(`[${paddedSource}] ${paddedKey}: ${formattedValue}`);\n }\n\n // Display summary\n logger.info('\\n' + '-'.repeat(80));\n logger.info('SUMMARY:');\n logger.info(` Total configuration keys: ${Object.keys(tracker).length}`);\n logger.info(` Configuration sources: ${discoveredDirs.length}`);\n\n // Count values by source\n const sourceCount: { [source: string]: number } = {};\n for (const info of Object.values(tracker)) {\n sourceCount[info.sourceLabel] = (sourceCount[info.sourceLabel] || 0) + 1;\n }\n\n logger.info(' Values by source:');\n for (const [source, count] of Object.entries(sourceCount)) {\n logger.info(` ${source}: ${count} value(s)`);\n }\n\n logger.info('='.repeat(80));\n}\n\n/**\n * Checks and displays the resolved configuration with detailed source tracking.\n * \n * This function provides a git blame-like view of configuration resolution,\n * showing which file and hierarchical level contributed each configuration value.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise that resolves when the configuration check is complete\n * \n * @example\n * ```typescript\n * await checkConfig(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config', 'hierarchical']\n * });\n * // Outputs detailed configuration source analysis\n * ```\n */\nexport const checkConfig = async <T extends z.ZodRawShape>(\n args: Args,\n options: Options<T>\n): Promise<void> => {\n const logger = options.logger;\n\n logger.info('Starting configuration check...');\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose(`Resolved config directory: ${resolvedConfigDir}`);\n\n let rawFileConfig: object = {};\n let discoveredDirs: DiscoveredConfigDir[] = [];\n let resolvedConfigDirs: DiscoveredConfigDir[] = [];\n let tracker: ConfigSourceTracker = {};\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Using hierarchical configuration discovery for source tracking');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredDirs = hierarchicalResult.discoveredDirs;\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs;\n\n // Build detailed source tracking by re-loading each config individually\n const trackers: ConfigSourceTracker[] = [];\n\n // Sort by level (highest level first = lowest precedence first) to match merge order\n const sortedDirs = [...resolvedConfigDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n const storage = Storage.create({ log: logger.debug });\n const configFilePath = path.join(dir.path, options.defaults.configFile);\n\n try {\n const exists = await storage.exists(configFilePath);\n if (!exists) continue;\n\n const isReadable = await storage.isFileReadable(configFilePath);\n if (!isReadable) continue;\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n const levelTracker = trackConfigSources(parsedYaml, configFilePath, dir.level);\n trackers.push(levelTracker);\n }\n } catch (error: any) {\n logger.debug(`Error loading config for source tracking from ${configFilePath}: ${error.message}`);\n }\n }\n\n // Merge trackers with proper precedence\n tracker = mergeConfigTrackers(trackers);\n\n if (hierarchicalResult.errors.length > 0) {\n logger.warn('Configuration loading warnings:');\n hierarchicalResult.errors.forEach(error => logger.warn(` ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n logger.verbose('Falling back to single directory configuration loading');\n\n // Fall back to single directory mode for source tracking\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading for source tracking');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured (this doesn't change source tracking)\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n // Build final configuration including built-in values\n const finalConfig = clean({\n ...processedConfig,\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs: discoveredDirs.map(dir => dir.path),\n resolvedConfigDirs: resolvedConfigDirs.map(dir => dir.path),\n });\n\n // Add built-in configuration to tracker\n tracker['configDirectory'] = {\n value: resolvedConfigDir,\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['discoveredConfigDirs'] = {\n value: discoveredDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['resolvedConfigDirs'] = {\n value: resolvedConfigDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n // Display the configuration with source information\n displayConfigWithSources(finalConfig, tracker, discoveredDirs, logger);\n};"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","length","resolvedConfig","fieldPath","value","getNestedValue","normalizedValue","normalizePathInput","shouldResolveArrayElements","includes","resolvedValue","resolvePathValue","setNestedValue","path","split","reduce","current","key","isUnsafeKey","keys","lastKey","pop","some","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","resolved","val","pathStr","isAbsolute","resolve","validatePath","userPath","basePath","Error","normalized","normalize","startsWith","join","validateConfigDirectory","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","discoveredConfigDirs","resolvedConfigDirs","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","pathResolution","fieldOverlaps","discoveredDirs","dir","forEach","level","errors","error","warn","message","loadSingleDirectoryConfig","processedConfig","findConfigFileWithExtension","storage","configFilePath","exists","isReadable","isFileReadable","ext","extname","baseName","alternativeExt","alternativeFileName","alternativePath","altExists","altIsReadable","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","test","code","trackConfigSources","sourcePath","prefix","tracker","sourceLabel","mergeConfigTrackers","trackers","merged","info","formatConfigValue","toString","slice","String","displayConfigWithSources","repeat","sort","a","b","precedence","Math","max","d","sortedKeys","maxKeyLength","k","maxSourceLength","values","paddedKey","padEnd","paddedSource","formattedValue","sourceCount","source","count","checkConfig","sortedDirs","levelTracker","push","finalConfig"],"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EAAgBtB,MAAAA,CAAAA;AACnE;;;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -94,6 +94,17 @@ export interface PathResolutionOptions {
|
|
|
94
94
|
pathFields?: string[];
|
|
95
95
|
/** Array of field names whose array elements should all be resolved as paths */
|
|
96
96
|
resolvePathArray?: string[];
|
|
97
|
+
/**
|
|
98
|
+
* Whether to validate that resolved paths exist on the filesystem
|
|
99
|
+
* @default false
|
|
100
|
+
*/
|
|
101
|
+
validateExists?: boolean;
|
|
102
|
+
/**
|
|
103
|
+
* Whether to warn about config values that look like paths but aren't in pathFields
|
|
104
|
+
* Looks for values containing './' or '../' that might be unresolved paths
|
|
105
|
+
* @default true
|
|
106
|
+
*/
|
|
107
|
+
warnUnmarkedPaths?: boolean;
|
|
97
108
|
}
|
|
98
109
|
/**
|
|
99
110
|
* Default configuration options for Cardigantime.
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\nimport { SecurityValidationConfig } from \"./security/types\";\n\n// Re-export MCP types for convenience\nexport type {\n MCPConfigSource,\n FileConfigSource,\n ConfigSource,\n ResolvedConfig,\n MCPInvocationContext,\n} from \"./mcp/types\";\n\n/**\n * Available features that can be enabled in Cardigantime.\n * Currently supports:\n * - 'config': Configuration file reading and validation\n * - 'hierarchical': Hierarchical configuration discovery and layering\n */\nexport type Feature = 'config' | 'hierarchical';\n\n/**\n * Supported configuration file formats.\n * \n * - 'yaml': YAML format (.yaml, .yml)\n * - 'json': JSON format (.json)\n * - 'javascript': JavaScript module (.js, .mjs, .cjs)\n * - 'typescript': TypeScript module (.ts, .mts, .cts)\n */\nexport enum ConfigFormat {\n YAML = 'yaml',\n JSON = 'json',\n JavaScript = 'javascript',\n TypeScript = 'typescript'\n}\n\n/**\n * Interface for format-specific configuration parsers.\n * Each parser is responsible for loading and parsing configuration from a specific format.\n * \n * @template T - The type of the parsed configuration object\n */\nexport interface ConfigParser<T = unknown> {\n /** The format this parser handles */\n format: ConfigFormat;\n /** File extensions this parser supports (e.g., ['.yaml', '.yml']) */\n extensions: string[];\n /** \n * Parses configuration content from a file.\n * \n * @param content - The raw file content as a string\n * @param filePath - The absolute path to the configuration file\n * @returns Promise resolving to the parsed configuration object\n * @throws {Error} When parsing fails or content is invalid\n */\n parse(content: string, filePath: string): Promise<T>;\n}\n\n/**\n * Metadata about where a configuration value came from.\n * Used for tracking configuration sources and debugging.\n * \n * @deprecated Use FileConfigSource from ./mcp/types instead.\n * This type is kept for backward compatibility and will be removed in a future version.\n */\nexport interface LegacyConfigSource {\n /** The format of the configuration file */\n format: ConfigFormat;\n /** Absolute path to the configuration file */\n filePath: string;\n /** The parsed configuration content */\n content: unknown;\n /** Timestamp when the configuration was loaded */\n loadedAt: Date;\n}\n\n/**\n * Defines how array fields should be merged in hierarchical configurations.\n * \n * - 'override': Higher precedence arrays completely replace lower precedence arrays (default)\n * - 'append': Higher precedence array elements are appended to lower precedence arrays\n * - 'prepend': Higher precedence array elements are prepended to lower precedence arrays\n */\nexport type ArrayOverlapMode = 'override' | 'append' | 'prepend';\n\n/**\n * Configuration for how fields should be merged in hierarchical configurations.\n * Maps field names (using dot notation) to their overlap behavior.\n * \n * @example\n * ```typescript\n * const fieldOverlaps: FieldOverlapOptions = {\n * 'features': 'append', // features arrays will be combined by appending\n * 'api.endpoints': 'prepend', // nested endpoint arrays will be combined by prepending\n * 'excludePatterns': 'override' // excludePatterns arrays will replace each other (default behavior)\n * };\n * ```\n */\nexport interface FieldOverlapOptions {\n [fieldPath: string]: ArrayOverlapMode;\n}\n\n/**\n * Configuration for resolving relative paths in configuration values.\n * Paths specified in these fields will be resolved relative to the configuration file's directory.\n */\nexport interface PathResolutionOptions {\n /** Array of field names (using dot notation) that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n}\n\n/**\n * Default configuration options for Cardigantime.\n * These define the basic behavior of configuration loading.\n */\nexport interface DefaultOptions {\n /** Directory path where configuration files are located */\n configDirectory: string;\n /** Name of the configuration file (e.g., 'config.yaml', 'app.yml') */\n configFile: string;\n /** Whether the configuration directory must exist. If true, throws error if directory doesn't exist */\n isRequired: boolean;\n /** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */\n encoding: string;\n /** Configuration for resolving relative paths in configuration values */\n pathResolution?: PathResolutionOptions;\n /** \n * Configuration for how array fields should be merged in hierarchical mode.\n * Only applies when the 'hierarchical' feature is enabled.\n * If not specified, all arrays use 'override' behavior (default).\n */\n fieldOverlaps?: FieldOverlapOptions;\n /** \n * Security validation configuration (optional, uses development profile by default).\n * Enable security features to validate CLI arguments and config file values.\n */\n security?: Partial<SecurityValidationConfig>;\n /**\n * Optional source metadata for tracking where configuration came from.\n * Populated automatically when configuration is loaded.\n * \n * @deprecated Use the new ConfigSource union type from ./mcp/types instead.\n */\n source?: LegacyConfigSource;\n /**\n * Allow executable configuration files (JavaScript/TypeScript).\n * \n * **SECURITY WARNING**: Executable configs run with full Node.js permissions\n * in the same process as your application. Only enable this if you trust\n * the configuration files being loaded.\n * \n * When disabled (default), JavaScript and TypeScript config files will be\n * ignored with a warning message.\n * \n * @default false\n */\n allowExecutableConfig?: boolean;\n}\n\n/**\n * Complete options object passed to Cardigantime functions.\n * Combines defaults, features, schema shape, and logger.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Options<T extends z.ZodRawShape> {\n /** Default configuration options */\n defaults: DefaultOptions,\n /** Array of enabled features */\n features: Feature[],\n /** Zod schema shape for validating user configuration */\n configShape: T;\n /** Logger instance for debugging and error reporting */\n logger: Logger;\n}\n\n/**\n * Logger interface for Cardigantime's internal logging.\n * Compatible with popular logging libraries like Winston, Bunyan, etc.\n */\nexport interface Logger {\n /** Debug-level logging for detailed troubleshooting information */\n debug: (message: string, ...args: any[]) => void;\n /** Info-level logging for general information */\n info: (message: string, ...args: any[]) => void;\n /** Warning-level logging for non-critical issues */\n warn: (message: string, ...args: any[]) => void;\n /** Error-level logging for critical problems */\n error: (message: string, ...args: any[]) => void;\n /** Verbose-level logging for extensive detail */\n verbose: (message: string, ...args: any[]) => void;\n /** Silly-level logging for maximum detail */\n silly: (message: string, ...args: any[]) => void;\n}\n\n/**\n * Main Cardigantime interface providing configuration management functionality.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Cardigantime<T extends z.ZodRawShape> {\n /** \n * Adds Cardigantime's CLI options to a Commander.js command.\n * This includes options like --config-directory for runtime config path overrides.\n */\n configure: (command: Command) => Promise<Command>;\n /** Sets a custom logger for debugging and error reporting */\n setLogger: (logger: Logger) => void;\n /** \n * Reads configuration from files and merges with CLI arguments.\n * Returns a fully typed configuration object.\n */\n read: (args: Args) => Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>>;\n /** \n * Validates the merged configuration against the Zod schema.\n * Throws ConfigurationError if validation fails.\n */\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;\n /** \n * Generates a configuration file with default values in the specified directory.\n * Creates the directory if it doesn't exist and writes a config file with all default values populated.\n */\n generateConfig: (configDirectory?: string) => Promise<void>;\n /** \n * Checks and displays the resolved configuration with detailed source tracking.\n * Shows which file and hierarchical level contributed each configuration value in a git blame-like format.\n */\n checkConfig: (args: Args) => Promise<void>;\n}\n\n/**\n * Parsed command-line arguments object, typically from Commander.js opts().\n * Keys correspond to CLI option names with values from user input.\n */\nexport interface Args {\n [key: string]: any;\n}\n\n/**\n * Base Zod schema for core Cardigantime configuration.\n * Contains the minimum required configuration fields.\n */\nexport const ConfigSchema = z.object({\n /** The resolved configuration directory path */\n configDirectory: z.string(),\n /** Array of all directory paths that were discovered during hierarchical search */\n discoveredConfigDirs: z.array(z.string()),\n /** Array of directory paths that actually contained valid configuration files */\n resolvedConfigDirs: z.array(z.string()),\n});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n\n// ============================================================================\n// Configuration Discovery Types\n// ============================================================================\n\n/**\n * Defines a configuration file naming pattern.\n * Used to discover configuration files in various standard locations.\n * \n * Patterns support placeholders:\n * - `{app}` - The application name (e.g., 'protokoll', 'myapp')\n * - `{ext}` - The file extension (e.g., 'yaml', 'json', 'ts')\n * \n * @example\n * ```typescript\n * // Pattern: \"{app}.config.{ext}\" with app=\"myapp\" and ext=\"yaml\"\n * // Results in: \"myapp.config.yaml\"\n * \n * const pattern: ConfigNamingPattern = {\n * pattern: '{app}.config.{ext}',\n * priority: 1,\n * hidden: false\n * };\n * ```\n */\nexport interface ConfigNamingPattern {\n /**\n * Pattern template with `{app}` and `{ext}` placeholders.\n * \n * Examples:\n * - `\"{app}.config.{ext}\"` → `\"protokoll.config.yaml\"`\n * - `\".{app}/config.{ext}\"` → `\".protokoll/config.yaml\"`\n * - `\".{app}rc.{ext}\"` → `\".protokollrc.json\"`\n * - `\".{app}rc\"` → `\".protokollrc\"` (no extension)\n */\n pattern: string;\n\n /**\n * Search priority (lower number = checked first).\n * When multiple config files exist, lower priority patterns take precedence.\n */\n priority: number;\n\n /**\n * Whether this pattern results in a hidden file or directory.\n * Hidden patterns start with a dot (e.g., `.myapp/`, `.myapprc`).\n */\n hidden: boolean;\n}\n\n/**\n * Options for configuring how configuration files are discovered.\n * \n * @example\n * ```typescript\n * const options: ConfigDiscoveryOptions = {\n * appName: 'myapp',\n * extensions: ['yaml', 'yml', 'json'],\n * searchHidden: true,\n * // Use custom patterns instead of defaults\n * patterns: [\n * { pattern: '{app}.config.{ext}', priority: 1, hidden: false }\n * ]\n * };\n * ```\n */\nexport interface ConfigDiscoveryOptions {\n /**\n * The application name used in pattern expansion.\n * This value replaces `{app}` placeholders in naming patterns.\n */\n appName: string;\n\n /**\n * Custom naming patterns to use for discovery.\n * If not provided, uses the standard patterns defined in STANDARD_PATTERNS.\n */\n patterns?: ConfigNamingPattern[];\n\n /**\n * File extensions to search for.\n * These replace the `{ext}` placeholder in patterns.\n * If not provided, defaults to supported format extensions.\n * \n * @example ['yaml', 'yml', 'json', 'js', 'ts']\n */\n extensions?: string[];\n\n /**\n * Whether to search for hidden files and directories.\n * When false, patterns with `hidden: true` are skipped.\n * \n * @default true\n */\n searchHidden?: boolean;\n\n /**\n * Whether to check for multiple config files and emit a warning.\n * When enabled, discovery continues after finding the first match\n * to detect and warn about additional config files that would be ignored.\n * \n * @default true\n */\n warnOnMultipleConfigs?: boolean;\n}\n\n/**\n * Result of discovering a configuration file.\n * Contains the file path and the pattern that matched.\n */\nexport interface DiscoveredConfig {\n /**\n * The resolved file path to the configuration file.\n * Can be a file path (e.g., 'app.config.yaml') or include\n * a directory (e.g., '.app/config.yaml').\n */\n path: string;\n\n /**\n * The absolute path to the configuration file.\n */\n absolutePath: string;\n\n /**\n * The pattern that matched this configuration file.\n */\n pattern: ConfigNamingPattern;\n}\n\n/**\n * Warning information when multiple config files are found.\n * This helps users identify and remove unused config files.\n */\nexport interface MultipleConfigWarning {\n /**\n * The configuration that will be used (highest priority).\n */\n used: DiscoveredConfig;\n\n /**\n * Configurations that were found but will be ignored.\n */\n ignored: DiscoveredConfig[];\n}\n\n/**\n * Full result of configuration discovery, including warnings.\n */\nexport interface DiscoveryResult {\n /**\n * The discovered configuration file, or null if none found.\n */\n config: DiscoveredConfig | null;\n\n /**\n * Warning about multiple config files, if any were found.\n */\n multipleConfigWarning?: MultipleConfigWarning;\n}\n\n// ============================================================================\n// Hierarchical Configuration Types\n// ============================================================================\n\n/**\n * Controls how hierarchical configuration lookup behaves.\n * \n * - `'enabled'` - Walk up the directory tree and merge configs (default behavior).\n * Configurations from parent directories are merged with child configurations,\n * with child values taking precedence.\n * \n * - `'disabled'` - Use only the config found in the starting directory.\n * No parent directory traversal occurs. Useful for isolated projects or\n * MCP configurations that should be self-contained.\n * \n * - `'root-only'` - Walk up to find the first config, but don't merge with others.\n * This mode finds the \"closest\" config file without merging parent configs.\n * Useful when you want automatic config discovery but not inheritance.\n * \n * - `'explicit'` - Only merge configs that are explicitly referenced.\n * The base config can specify which parent configs to extend via an\n * `extends` field. No automatic directory traversal.\n * \n * @example\n * ```typescript\n * // In a child config that wants to be isolated:\n * // protokoll.config.yaml\n * hierarchical:\n * mode: disabled\n * \n * // This config will NOT inherit from parent directories\n * ```\n */\nexport type HierarchicalMode = 'enabled' | 'disabled' | 'root-only' | 'explicit';\n\n/**\n * Files or directories that indicate a project root.\n * When encountered during directory traversal, hierarchical lookup stops.\n * \n * @example\n * ```typescript\n * const markers: RootMarker[] = [\n * { type: 'file', name: 'package.json' },\n * { type: 'directory', name: '.git' },\n * { type: 'file', name: 'pnpm-workspace.yaml' },\n * ];\n * ```\n */\nexport interface RootMarker {\n /** Type of the marker */\n type: 'file' | 'directory';\n /** Name of the file or directory that indicates a root */\n name: string;\n}\n\n/**\n * Default root markers used when none are specified.\n * These indicate common project root boundaries.\n */\nexport const DEFAULT_ROOT_MARKERS: RootMarker[] = [\n { type: 'file', name: 'package.json' },\n { type: 'directory', name: '.git' },\n { type: 'file', name: 'pnpm-workspace.yaml' },\n { type: 'file', name: 'lerna.json' },\n { type: 'file', name: 'nx.json' },\n { type: 'file', name: 'rush.json' },\n];\n\n/**\n * Configuration options for hierarchical config behavior.\n * Can be set in the configuration file or programmatically.\n * \n * @example\n * ```typescript\n * // Configuration file (protokoll.config.yaml):\n * hierarchical:\n * mode: enabled\n * maxDepth: 5\n * stopAt:\n * - node_modules\n * - vendor\n * rootMarkers:\n * - type: file\n * name: package.json\n * ```\n * \n * @example\n * ```typescript\n * // Programmatic configuration:\n * const options: HierarchicalOptions = {\n * mode: 'disabled', // No parent config merging\n * };\n * \n * // For MCP servers:\n * const mcpOptions: HierarchicalOptions = {\n * mode: 'root-only',\n * rootMarkers: [{ type: 'file', name: 'mcp.json' }],\n * };\n * ```\n */\nexport interface HierarchicalOptions {\n /**\n * The hierarchical lookup mode.\n * Controls whether and how parent directories are searched.\n * \n * @default 'enabled'\n */\n mode?: HierarchicalMode;\n\n /**\n * Maximum number of parent directories to traverse.\n * Prevents unbounded traversal in deep directory structures.\n * \n * @default 10\n */\n maxDepth?: number;\n\n /**\n * Directory names where traversal should stop.\n * When a directory with one of these names is encountered as a parent,\n * traversal stops even if no config was found.\n * \n * @example ['node_modules', 'vendor', '.cache']\n */\n stopAt?: string[];\n\n /**\n * Files or directories that indicate a project root.\n * When a directory contains one of these markers, it's treated as a root\n * and traversal stops after processing that directory.\n * \n * If not specified, uses DEFAULT_ROOT_MARKERS.\n * Set to empty array to disable root marker detection.\n */\n rootMarkers?: RootMarker[];\n\n /**\n * Whether to stop at the first root marker found.\n * When true, traversal stops immediately when a root marker is found.\n * When false, the directory with the root marker is included but no further.\n * \n * @default true\n */\n stopAtRoot?: boolean;\n}\n\n// ============================================================================\n// Directory Traversal Security Types\n// ============================================================================\n\n/**\n * Defines security boundaries for directory traversal.\n * Used to prevent configuration lookup from accessing sensitive directories.\n * \n * @example\n * ```typescript\n * const boundaries: TraversalBoundary = {\n * forbidden: ['/etc', '/usr', '/var'],\n * boundaries: [process.env.HOME ?? '/home'],\n * maxAbsoluteDepth: 20,\n * maxRelativeDepth: 10,\n * };\n * ```\n */\nexport interface TraversalBoundary {\n /**\n * Directories that are never allowed to be accessed.\n * Traversal is blocked if the path is at or within these directories.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['/etc', '/usr', '/var', '/sys', '/proc', '$HOME/.ssh']\n */\n forbidden: string[];\n\n /**\n * Soft boundary directories - traversal stops at these unless explicitly allowed.\n * These represent natural project boundaries.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['$HOME', '/tmp', '/private/tmp']\n */\n boundaries: string[];\n\n /**\n * Maximum absolute depth from the filesystem root.\n * Prevents extremely deep traversal regardless of starting point.\n * Depth is counted as the number of path segments from root.\n * \n * @example 20 means paths like /a/b/c/.../t (20 levels deep) are allowed\n * @default 20\n */\n maxAbsoluteDepth: number;\n\n /**\n * Maximum relative depth from the starting directory.\n * Limits how far up the directory tree traversal can go.\n * \n * @example 10 means traversal can go up 10 directories from the start\n * @default 10\n */\n maxRelativeDepth: number;\n}\n\n/**\n * Result of a traversal boundary check.\n */\nexport interface TraversalCheckResult {\n /** Whether the path is allowed */\n allowed: boolean;\n \n /** Reason for blocking (if not allowed) */\n reason?: string;\n \n /** The boundary that was violated (if any) */\n violatedBoundary?: string;\n}\n\n/**\n * Options for configuring traversal security behavior.\n */\nexport interface TraversalSecurityOptions {\n /**\n * Custom traversal boundaries to use instead of defaults.\n */\n boundaries?: Partial<TraversalBoundary>;\n\n /**\n * Allow traversal beyond safe boundaries.\n * \n * **SECURITY WARNING**: Setting this to true bypasses security checks\n * and allows traversal into sensitive directories. Only use this in\n * trusted scenarios where you control all configuration files.\n * \n * @default false\n */\n allowUnsafeTraversal?: boolean;\n\n /**\n * Whether to log warnings when boundaries are overridden.\n * \n * @default true\n */\n warnOnOverride?: boolean;\n}\n"],"names":["ConfigFormat","ConfigSchema","z","object","configDirectory","string","discoveredConfigDirs","array","resolvedConfigDirs","DEFAULT_ROOT_MARKERS","type","name"],"mappings":";;AAuBA;;;;;;;IAQO,IAAKA,YAAAA,iBAAAA,SAAAA,YAAAA,EAAAA;;;;;AAAAA,IAAAA,OAAAA,YAAAA;AAKX,CAAA,CAAA,EAAA;AA8MD;;;AAGC,IACM,MAAMC,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;qDAEjCC,eAAAA,EAAiBF,CAAAA,CAAEG,MAAM,EAAA;AACzB,wFACAC,oBAAAA,EAAsBJ,CAAAA,CAAEK,KAAK,CAACL,EAAEG,MAAM,EAAA,CAAA;AACtC,sFACAG,kBAAAA,EAAoBN,CAAAA,CAAEK,KAAK,CAACL,EAAEG,MAAM,EAAA;AACxC,CAAA;AA6NA;;;UAIaI,oBAAAA,GAAqC;AAC9C,IAAA;QAAEC,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAe,KAAA;AACrC,IAAA;QAAED,IAAAA,EAAM,WAAA;QAAaC,IAAAA,EAAM;AAAO,KAAA;AAClC,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAsB,KAAA;AAC5C,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAa,KAAA;AACnC,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAU,KAAA;AAChC,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAY;;;;;"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { ZodObject } from \"zod\";\n\nimport { z } from \"zod\";\nimport { SecurityValidationConfig } from \"./security/types\";\n\n// Re-export MCP types for convenience\nexport type {\n MCPConfigSource,\n FileConfigSource,\n ConfigSource,\n ResolvedConfig,\n MCPInvocationContext,\n} from \"./mcp/types\";\n\n/**\n * Available features that can be enabled in Cardigantime.\n * Currently supports:\n * - 'config': Configuration file reading and validation\n * - 'hierarchical': Hierarchical configuration discovery and layering\n */\nexport type Feature = 'config' | 'hierarchical';\n\n/**\n * Supported configuration file formats.\n * \n * - 'yaml': YAML format (.yaml, .yml)\n * - 'json': JSON format (.json)\n * - 'javascript': JavaScript module (.js, .mjs, .cjs)\n * - 'typescript': TypeScript module (.ts, .mts, .cts)\n */\nexport enum ConfigFormat {\n YAML = 'yaml',\n JSON = 'json',\n JavaScript = 'javascript',\n TypeScript = 'typescript'\n}\n\n/**\n * Interface for format-specific configuration parsers.\n * Each parser is responsible for loading and parsing configuration from a specific format.\n * \n * @template T - The type of the parsed configuration object\n */\nexport interface ConfigParser<T = unknown> {\n /** The format this parser handles */\n format: ConfigFormat;\n /** File extensions this parser supports (e.g., ['.yaml', '.yml']) */\n extensions: string[];\n /** \n * Parses configuration content from a file.\n * \n * @param content - The raw file content as a string\n * @param filePath - The absolute path to the configuration file\n * @returns Promise resolving to the parsed configuration object\n * @throws {Error} When parsing fails or content is invalid\n */\n parse(content: string, filePath: string): Promise<T>;\n}\n\n/**\n * Metadata about where a configuration value came from.\n * Used for tracking configuration sources and debugging.\n * \n * @deprecated Use FileConfigSource from ./mcp/types instead.\n * This type is kept for backward compatibility and will be removed in a future version.\n */\nexport interface LegacyConfigSource {\n /** The format of the configuration file */\n format: ConfigFormat;\n /** Absolute path to the configuration file */\n filePath: string;\n /** The parsed configuration content */\n content: unknown;\n /** Timestamp when the configuration was loaded */\n loadedAt: Date;\n}\n\n/**\n * Defines how array fields should be merged in hierarchical configurations.\n * \n * - 'override': Higher precedence arrays completely replace lower precedence arrays (default)\n * - 'append': Higher precedence array elements are appended to lower precedence arrays\n * - 'prepend': Higher precedence array elements are prepended to lower precedence arrays\n */\nexport type ArrayOverlapMode = 'override' | 'append' | 'prepend';\n\n/**\n * Configuration for how fields should be merged in hierarchical configurations.\n * Maps field names (using dot notation) to their overlap behavior.\n * \n * @example\n * ```typescript\n * const fieldOverlaps: FieldOverlapOptions = {\n * 'features': 'append', // features arrays will be combined by appending\n * 'api.endpoints': 'prepend', // nested endpoint arrays will be combined by prepending\n * 'excludePatterns': 'override' // excludePatterns arrays will replace each other (default behavior)\n * };\n * ```\n */\nexport interface FieldOverlapOptions {\n [fieldPath: string]: ArrayOverlapMode;\n}\n\n/**\n * Configuration for resolving relative paths in configuration values.\n * Paths specified in these fields will be resolved relative to the configuration file's directory.\n */\nexport interface PathResolutionOptions {\n /** Array of field names (using dot notation) that contain paths to be resolved */\n pathFields?: string[];\n /** Array of field names whose array elements should all be resolved as paths */\n resolvePathArray?: string[];\n /** \n * Whether to validate that resolved paths exist on the filesystem\n * @default false\n */\n validateExists?: boolean;\n /**\n * Whether to warn about config values that look like paths but aren't in pathFields\n * Looks for values containing './' or '../' that might be unresolved paths\n * @default true\n */\n warnUnmarkedPaths?: boolean;\n}\n\n/**\n * Default configuration options for Cardigantime.\n * These define the basic behavior of configuration loading.\n */\nexport interface DefaultOptions {\n /** Directory path where configuration files are located */\n configDirectory: string;\n /** Name of the configuration file (e.g., 'config.yaml', 'app.yml') */\n configFile: string;\n /** Whether the configuration directory must exist. If true, throws error if directory doesn't exist */\n isRequired: boolean;\n /** File encoding for reading configuration files (e.g., 'utf8', 'ascii') */\n encoding: string;\n /** Configuration for resolving relative paths in configuration values */\n pathResolution?: PathResolutionOptions;\n /** \n * Configuration for how array fields should be merged in hierarchical mode.\n * Only applies when the 'hierarchical' feature is enabled.\n * If not specified, all arrays use 'override' behavior (default).\n */\n fieldOverlaps?: FieldOverlapOptions;\n /** \n * Security validation configuration (optional, uses development profile by default).\n * Enable security features to validate CLI arguments and config file values.\n */\n security?: Partial<SecurityValidationConfig>;\n /**\n * Optional source metadata for tracking where configuration came from.\n * Populated automatically when configuration is loaded.\n * \n * @deprecated Use the new ConfigSource union type from ./mcp/types instead.\n */\n source?: LegacyConfigSource;\n /**\n * Allow executable configuration files (JavaScript/TypeScript).\n * \n * **SECURITY WARNING**: Executable configs run with full Node.js permissions\n * in the same process as your application. Only enable this if you trust\n * the configuration files being loaded.\n * \n * When disabled (default), JavaScript and TypeScript config files will be\n * ignored with a warning message.\n * \n * @default false\n */\n allowExecutableConfig?: boolean;\n}\n\n/**\n * Complete options object passed to Cardigantime functions.\n * Combines defaults, features, schema shape, and logger.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Options<T extends z.ZodRawShape> {\n /** Default configuration options */\n defaults: DefaultOptions,\n /** Array of enabled features */\n features: Feature[],\n /** Zod schema shape for validating user configuration */\n configShape: T;\n /** Logger instance for debugging and error reporting */\n logger: Logger;\n}\n\n/**\n * Logger interface for Cardigantime's internal logging.\n * Compatible with popular logging libraries like Winston, Bunyan, etc.\n */\nexport interface Logger {\n /** Debug-level logging for detailed troubleshooting information */\n debug: (message: string, ...args: any[]) => void;\n /** Info-level logging for general information */\n info: (message: string, ...args: any[]) => void;\n /** Warning-level logging for non-critical issues */\n warn: (message: string, ...args: any[]) => void;\n /** Error-level logging for critical problems */\n error: (message: string, ...args: any[]) => void;\n /** Verbose-level logging for extensive detail */\n verbose: (message: string, ...args: any[]) => void;\n /** Silly-level logging for maximum detail */\n silly: (message: string, ...args: any[]) => void;\n}\n\n/**\n * Main Cardigantime interface providing configuration management functionality.\n * \n * @template T - The Zod schema shape type for configuration validation\n */\nexport interface Cardigantime<T extends z.ZodRawShape> {\n /** \n * Adds Cardigantime's CLI options to a Commander.js command.\n * This includes options like --config-directory for runtime config path overrides.\n */\n configure: (command: Command) => Promise<Command>;\n /** Sets a custom logger for debugging and error reporting */\n setLogger: (logger: Logger) => void;\n /** \n * Reads configuration from files and merges with CLI arguments.\n * Returns a fully typed configuration object.\n */\n read: (args: Args) => Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>>;\n /** \n * Validates the merged configuration against the Zod schema.\n * Throws ConfigurationError if validation fails.\n */\n validate: (config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>) => Promise<void>;\n /** \n * Generates a configuration file with default values in the specified directory.\n * Creates the directory if it doesn't exist and writes a config file with all default values populated.\n */\n generateConfig: (configDirectory?: string) => Promise<void>;\n /** \n * Checks and displays the resolved configuration with detailed source tracking.\n * Shows which file and hierarchical level contributed each configuration value in a git blame-like format.\n */\n checkConfig: (args: Args) => Promise<void>;\n}\n\n/**\n * Parsed command-line arguments object, typically from Commander.js opts().\n * Keys correspond to CLI option names with values from user input.\n */\nexport interface Args {\n [key: string]: any;\n}\n\n/**\n * Base Zod schema for core Cardigantime configuration.\n * Contains the minimum required configuration fields.\n */\nexport const ConfigSchema = z.object({\n /** The resolved configuration directory path */\n configDirectory: z.string(),\n /** Array of all directory paths that were discovered during hierarchical search */\n discoveredConfigDirs: z.array(z.string()),\n /** Array of directory paths that actually contained valid configuration files */\n resolvedConfigDirs: z.array(z.string()),\n});\n\n/**\n * Base configuration type derived from the core schema.\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n\n// ============================================================================\n// Configuration Discovery Types\n// ============================================================================\n\n/**\n * Defines a configuration file naming pattern.\n * Used to discover configuration files in various standard locations.\n * \n * Patterns support placeholders:\n * - `{app}` - The application name (e.g., 'protokoll', 'myapp')\n * - `{ext}` - The file extension (e.g., 'yaml', 'json', 'ts')\n * \n * @example\n * ```typescript\n * // Pattern: \"{app}.config.{ext}\" with app=\"myapp\" and ext=\"yaml\"\n * // Results in: \"myapp.config.yaml\"\n * \n * const pattern: ConfigNamingPattern = {\n * pattern: '{app}.config.{ext}',\n * priority: 1,\n * hidden: false\n * };\n * ```\n */\nexport interface ConfigNamingPattern {\n /**\n * Pattern template with `{app}` and `{ext}` placeholders.\n * \n * Examples:\n * - `\"{app}.config.{ext}\"` → `\"protokoll.config.yaml\"`\n * - `\".{app}/config.{ext}\"` → `\".protokoll/config.yaml\"`\n * - `\".{app}rc.{ext}\"` → `\".protokollrc.json\"`\n * - `\".{app}rc\"` → `\".protokollrc\"` (no extension)\n */\n pattern: string;\n\n /**\n * Search priority (lower number = checked first).\n * When multiple config files exist, lower priority patterns take precedence.\n */\n priority: number;\n\n /**\n * Whether this pattern results in a hidden file or directory.\n * Hidden patterns start with a dot (e.g., `.myapp/`, `.myapprc`).\n */\n hidden: boolean;\n}\n\n/**\n * Options for configuring how configuration files are discovered.\n * \n * @example\n * ```typescript\n * const options: ConfigDiscoveryOptions = {\n * appName: 'myapp',\n * extensions: ['yaml', 'yml', 'json'],\n * searchHidden: true,\n * // Use custom patterns instead of defaults\n * patterns: [\n * { pattern: '{app}.config.{ext}', priority: 1, hidden: false }\n * ]\n * };\n * ```\n */\nexport interface ConfigDiscoveryOptions {\n /**\n * The application name used in pattern expansion.\n * This value replaces `{app}` placeholders in naming patterns.\n */\n appName: string;\n\n /**\n * Custom naming patterns to use for discovery.\n * If not provided, uses the standard patterns defined in STANDARD_PATTERNS.\n */\n patterns?: ConfigNamingPattern[];\n\n /**\n * File extensions to search for.\n * These replace the `{ext}` placeholder in patterns.\n * If not provided, defaults to supported format extensions.\n * \n * @example ['yaml', 'yml', 'json', 'js', 'ts']\n */\n extensions?: string[];\n\n /**\n * Whether to search for hidden files and directories.\n * When false, patterns with `hidden: true` are skipped.\n * \n * @default true\n */\n searchHidden?: boolean;\n\n /**\n * Whether to check for multiple config files and emit a warning.\n * When enabled, discovery continues after finding the first match\n * to detect and warn about additional config files that would be ignored.\n * \n * @default true\n */\n warnOnMultipleConfigs?: boolean;\n}\n\n/**\n * Result of discovering a configuration file.\n * Contains the file path and the pattern that matched.\n */\nexport interface DiscoveredConfig {\n /**\n * The resolved file path to the configuration file.\n * Can be a file path (e.g., 'app.config.yaml') or include\n * a directory (e.g., '.app/config.yaml').\n */\n path: string;\n\n /**\n * The absolute path to the configuration file.\n */\n absolutePath: string;\n\n /**\n * The pattern that matched this configuration file.\n */\n pattern: ConfigNamingPattern;\n}\n\n/**\n * Warning information when multiple config files are found.\n * This helps users identify and remove unused config files.\n */\nexport interface MultipleConfigWarning {\n /**\n * The configuration that will be used (highest priority).\n */\n used: DiscoveredConfig;\n\n /**\n * Configurations that were found but will be ignored.\n */\n ignored: DiscoveredConfig[];\n}\n\n/**\n * Full result of configuration discovery, including warnings.\n */\nexport interface DiscoveryResult {\n /**\n * The discovered configuration file, or null if none found.\n */\n config: DiscoveredConfig | null;\n\n /**\n * Warning about multiple config files, if any were found.\n */\n multipleConfigWarning?: MultipleConfigWarning;\n}\n\n// ============================================================================\n// Hierarchical Configuration Types\n// ============================================================================\n\n/**\n * Controls how hierarchical configuration lookup behaves.\n * \n * - `'enabled'` - Walk up the directory tree and merge configs (default behavior).\n * Configurations from parent directories are merged with child configurations,\n * with child values taking precedence.\n * \n * - `'disabled'` - Use only the config found in the starting directory.\n * No parent directory traversal occurs. Useful for isolated projects or\n * MCP configurations that should be self-contained.\n * \n * - `'root-only'` - Walk up to find the first config, but don't merge with others.\n * This mode finds the \"closest\" config file without merging parent configs.\n * Useful when you want automatic config discovery but not inheritance.\n * \n * - `'explicit'` - Only merge configs that are explicitly referenced.\n * The base config can specify which parent configs to extend via an\n * `extends` field. No automatic directory traversal.\n * \n * @example\n * ```typescript\n * // In a child config that wants to be isolated:\n * // protokoll.config.yaml\n * hierarchical:\n * mode: disabled\n * \n * // This config will NOT inherit from parent directories\n * ```\n */\nexport type HierarchicalMode = 'enabled' | 'disabled' | 'root-only' | 'explicit';\n\n/**\n * Files or directories that indicate a project root.\n * When encountered during directory traversal, hierarchical lookup stops.\n * \n * @example\n * ```typescript\n * const markers: RootMarker[] = [\n * { type: 'file', name: 'package.json' },\n * { type: 'directory', name: '.git' },\n * { type: 'file', name: 'pnpm-workspace.yaml' },\n * ];\n * ```\n */\nexport interface RootMarker {\n /** Type of the marker */\n type: 'file' | 'directory';\n /** Name of the file or directory that indicates a root */\n name: string;\n}\n\n/**\n * Default root markers used when none are specified.\n * These indicate common project root boundaries.\n */\nexport const DEFAULT_ROOT_MARKERS: RootMarker[] = [\n { type: 'file', name: 'package.json' },\n { type: 'directory', name: '.git' },\n { type: 'file', name: 'pnpm-workspace.yaml' },\n { type: 'file', name: 'lerna.json' },\n { type: 'file', name: 'nx.json' },\n { type: 'file', name: 'rush.json' },\n];\n\n/**\n * Configuration options for hierarchical config behavior.\n * Can be set in the configuration file or programmatically.\n * \n * @example\n * ```typescript\n * // Configuration file (protokoll.config.yaml):\n * hierarchical:\n * mode: enabled\n * maxDepth: 5\n * stopAt:\n * - node_modules\n * - vendor\n * rootMarkers:\n * - type: file\n * name: package.json\n * ```\n * \n * @example\n * ```typescript\n * // Programmatic configuration:\n * const options: HierarchicalOptions = {\n * mode: 'disabled', // No parent config merging\n * };\n * \n * // For MCP servers:\n * const mcpOptions: HierarchicalOptions = {\n * mode: 'root-only',\n * rootMarkers: [{ type: 'file', name: 'mcp.json' }],\n * };\n * ```\n */\nexport interface HierarchicalOptions {\n /**\n * The hierarchical lookup mode.\n * Controls whether and how parent directories are searched.\n * \n * @default 'enabled'\n */\n mode?: HierarchicalMode;\n\n /**\n * Maximum number of parent directories to traverse.\n * Prevents unbounded traversal in deep directory structures.\n * \n * @default 10\n */\n maxDepth?: number;\n\n /**\n * Directory names where traversal should stop.\n * When a directory with one of these names is encountered as a parent,\n * traversal stops even if no config was found.\n * \n * @example ['node_modules', 'vendor', '.cache']\n */\n stopAt?: string[];\n\n /**\n * Files or directories that indicate a project root.\n * When a directory contains one of these markers, it's treated as a root\n * and traversal stops after processing that directory.\n * \n * If not specified, uses DEFAULT_ROOT_MARKERS.\n * Set to empty array to disable root marker detection.\n */\n rootMarkers?: RootMarker[];\n\n /**\n * Whether to stop at the first root marker found.\n * When true, traversal stops immediately when a root marker is found.\n * When false, the directory with the root marker is included but no further.\n * \n * @default true\n */\n stopAtRoot?: boolean;\n}\n\n// ============================================================================\n// Directory Traversal Security Types\n// ============================================================================\n\n/**\n * Defines security boundaries for directory traversal.\n * Used to prevent configuration lookup from accessing sensitive directories.\n * \n * @example\n * ```typescript\n * const boundaries: TraversalBoundary = {\n * forbidden: ['/etc', '/usr', '/var'],\n * boundaries: [process.env.HOME ?? '/home'],\n * maxAbsoluteDepth: 20,\n * maxRelativeDepth: 10,\n * };\n * ```\n */\nexport interface TraversalBoundary {\n /**\n * Directories that are never allowed to be accessed.\n * Traversal is blocked if the path is at or within these directories.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['/etc', '/usr', '/var', '/sys', '/proc', '$HOME/.ssh']\n */\n forbidden: string[];\n\n /**\n * Soft boundary directories - traversal stops at these unless explicitly allowed.\n * These represent natural project boundaries.\n * Paths can include environment variable placeholders like `$HOME`.\n * \n * @example ['$HOME', '/tmp', '/private/tmp']\n */\n boundaries: string[];\n\n /**\n * Maximum absolute depth from the filesystem root.\n * Prevents extremely deep traversal regardless of starting point.\n * Depth is counted as the number of path segments from root.\n * \n * @example 20 means paths like /a/b/c/.../t (20 levels deep) are allowed\n * @default 20\n */\n maxAbsoluteDepth: number;\n\n /**\n * Maximum relative depth from the starting directory.\n * Limits how far up the directory tree traversal can go.\n * \n * @example 10 means traversal can go up 10 directories from the start\n * @default 10\n */\n maxRelativeDepth: number;\n}\n\n/**\n * Result of a traversal boundary check.\n */\nexport interface TraversalCheckResult {\n /** Whether the path is allowed */\n allowed: boolean;\n \n /** Reason for blocking (if not allowed) */\n reason?: string;\n \n /** The boundary that was violated (if any) */\n violatedBoundary?: string;\n}\n\n/**\n * Options for configuring traversal security behavior.\n */\nexport interface TraversalSecurityOptions {\n /**\n * Custom traversal boundaries to use instead of defaults.\n */\n boundaries?: Partial<TraversalBoundary>;\n\n /**\n * Allow traversal beyond safe boundaries.\n * \n * **SECURITY WARNING**: Setting this to true bypasses security checks\n * and allows traversal into sensitive directories. Only use this in\n * trusted scenarios where you control all configuration files.\n * \n * @default false\n */\n allowUnsafeTraversal?: boolean;\n\n /**\n * Whether to log warnings when boundaries are overridden.\n * \n * @default true\n */\n warnOnOverride?: boolean;\n}\n"],"names":["ConfigFormat","ConfigSchema","z","object","configDirectory","string","discoveredConfigDirs","array","resolvedConfigDirs","DEFAULT_ROOT_MARKERS","type","name"],"mappings":";;AAuBA;;;;;;;IAQO,IAAKA,YAAAA,iBAAAA,SAAAA,YAAAA,EAAAA;;;;;AAAAA,IAAAA,OAAAA,YAAAA;AAKX,CAAA,CAAA,EAAA;AAyND;;;AAGC,IACM,MAAMC,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;qDAEjCC,eAAAA,EAAiBF,CAAAA,CAAEG,MAAM,EAAA;AACzB,wFACAC,oBAAAA,EAAsBJ,CAAAA,CAAEK,KAAK,CAACL,EAAEG,MAAM,EAAA,CAAA;AACtC,sFACAG,kBAAAA,EAAoBN,CAAAA,CAAEK,KAAK,CAACL,EAAEG,MAAM,EAAA;AACxC,CAAA;AA6NA;;;UAIaI,oBAAAA,GAAqC;AAC9C,IAAA;QAAEC,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAe,KAAA;AACrC,IAAA;QAAED,IAAAA,EAAM,WAAA;QAAaC,IAAAA,EAAM;AAAO,KAAA;AAClC,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAsB,KAAA;AAC5C,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAa,KAAA;AACnC,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAU,KAAA;AAChC,IAAA;QAAED,IAAAA,EAAM,MAAA;QAAQC,IAAAA,EAAM;AAAY;;;;;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as path from 'node:path';
|
|
2
2
|
import * as yaml from 'js-yaml';
|
|
3
3
|
import { create } from './storage.js';
|
|
4
|
+
import { normalizePathInput } from './path-normalization.js';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Resolves relative paths in configuration values relative to the configuration file's directory.
|
|
@@ -14,8 +15,11 @@ import { create } from './storage.js';
|
|
|
14
15
|
for (const fieldPath of pathFields){
|
|
15
16
|
const value = getNestedValue(resolvedConfig, fieldPath);
|
|
16
17
|
if (value !== undefined) {
|
|
18
|
+
// Step 1: Normalize input (convert file:// URLs, reject http/https)
|
|
19
|
+
const normalizedValue = normalizePathInput(value);
|
|
20
|
+
// Step 2: Resolve paths relative to config directory
|
|
17
21
|
const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);
|
|
18
|
-
const resolvedValue = resolvePathValue(
|
|
22
|
+
const resolvedValue = resolvePathValue(normalizedValue, configDir, shouldResolveArrayElements);
|
|
19
23
|
setNestedValue(resolvedConfig, fieldPath, resolvedValue);
|
|
20
24
|
}
|
|
21
25
|
}
|
|
@@ -51,7 +55,13 @@ function setNestedValue(obj, path, value) {
|
|
|
51
55
|
target[lastKey] = value;
|
|
52
56
|
}
|
|
53
57
|
/**
|
|
54
|
-
* Resolves a path value (string
|
|
58
|
+
* Resolves a path value (string, array, or object) relative to the config directory.
|
|
59
|
+
*
|
|
60
|
+
* Handles:
|
|
61
|
+
* - Strings: Resolved relative to configDir
|
|
62
|
+
* - Arrays: Elements resolved if resolveArrayElements is true
|
|
63
|
+
* - Objects: All string values and array elements resolved recursively
|
|
64
|
+
* - Other types: Returned unchanged
|
|
55
65
|
*/ function resolvePathValue(value, configDir, resolveArrayElements) {
|
|
56
66
|
if (typeof value === 'string') {
|
|
57
67
|
return resolveSinglePath(value, configDir);
|
|
@@ -59,6 +69,22 @@ function setNestedValue(obj, path, value) {
|
|
|
59
69
|
if (Array.isArray(value) && resolveArrayElements) {
|
|
60
70
|
return value.map((item)=>typeof item === 'string' ? resolveSinglePath(item, configDir) : item);
|
|
61
71
|
}
|
|
72
|
+
// NEW: Handle objects with string values
|
|
73
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
74
|
+
const resolved = {};
|
|
75
|
+
for (const [key, val] of Object.entries(value)){
|
|
76
|
+
if (typeof val === 'string') {
|
|
77
|
+
resolved[key] = resolveSinglePath(val, configDir);
|
|
78
|
+
} else if (Array.isArray(val)) {
|
|
79
|
+
// Also handle arrays within objects
|
|
80
|
+
resolved[key] = val.map((item)=>typeof item === 'string' ? resolveSinglePath(item, configDir) : item);
|
|
81
|
+
} else {
|
|
82
|
+
// Keep other types unchanged
|
|
83
|
+
resolved[key] = val;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return resolved;
|
|
87
|
+
}
|
|
62
88
|
return value;
|
|
63
89
|
}
|
|
64
90
|
/**
|