import { join } from 'path'; import { z } from 'zod'; import { getLogger } from '@stock-bot/logger'; import { ConfigError, ConfigValidationError } from './errors'; import { EnvLoader } from './loaders/env.loader'; import { FileLoader } from './loaders/file.loader'; import type { ConfigLoader, ConfigManagerOptions, ConfigSchema, DeepPartial, Environment, } from './types'; export type { ConfigManagerOptions } from './types'; export class ConfigManager> { private readonly logger = getLogger('config-manager'); private config: T | null = null; private loaders: ConfigLoader[]; private environment: Environment; private schema?: ConfigSchema; constructor(options: ConfigManagerOptions = {}, defaultSchema?: ConfigSchema) { this.environment = options.environment || this.detectEnvironment(); this.schema = defaultSchema; if (options.loaders) { this.loaders = options.loaders; } else { const configPath = options.configPath || join(process.cwd(), 'config'); this.loaders = [new FileLoader(configPath, this.environment), new EnvLoader('')]; } } initialize(schema?: ConfigSchema): T { if (this.config) { return this.config; } if (schema) { this.schema = schema; } const sortedLoaders = [...this.loaders].sort((a, b) => a.priority - b.priority); const configs: Record[] = []; for (const loader of sortedLoaders) { const config = loader.load(); if (config && Object.keys(config).length > 0) { configs.push(config); } } const mergedConfig = this.merge(...configs) as T; if ( typeof mergedConfig === 'object' && mergedConfig !== null && !('environment' in mergedConfig) ) { (mergedConfig as Record)['environment'] = this.environment; } if (this.schema) { try { this.config = this.schema.parse(mergedConfig) as T; } catch (error) { if (error instanceof z.ZodError) { const errorDetails = error.errors.map(err => ({ path: err.path.join('.'), message: err.message, code: err.code, })); this.logger.error('Configuration validation failed:', errorDetails); throw new ConfigValidationError('Configuration validation failed', error.errors); } throw error; } } else { this.config = mergedConfig; } return this.config; } get(): T { if (!this.config) { throw new ConfigError('Configuration not initialized. Call initialize() first.'); } return this.config; } getValue(path: string): R { const config = this.get(); const keys = path.split('.'); let value: unknown = config; for (const key of keys) { if (value && typeof value === 'object' && key in value) { value = (value as Record)[key]; } else { throw new ConfigError(`Configuration key not found: ${path}`); } } return value as R; } has(path: string): boolean { try { this.getValue(path); return true; } catch { return false; } } set(updates: DeepPartial): void { if (!this.config) { throw new ConfigError('Configuration not initialized. Call initialize() first.'); } const updated = this.merge( this.config as Record, updates as Record ) as T; if (this.schema) { try { this.config = this.schema.parse(updated) as T; } catch (error) { if (error instanceof z.ZodError) { throw new ConfigValidationError( 'Configuration validation failed after update', error.errors ); } throw error; } } else { this.config = updated; } } getEnvironment(): Environment { return this.environment; } reset(): void { this.config = null; } validate(schema: S): z.infer { const config = this.get(); return schema.parse(config); } private detectEnvironment(): Environment { const env = process.env.NODE_ENV?.toLowerCase(); switch (env) { case 'production': case 'prod': return 'production'; case 'qa': return 'qa'; case 'test': return 'test'; case 'development': case 'dev': default: return 'development'; } } /** * Deep merge tracking only active ancestor objects so valid shared DAG references * (e.g. redis = database.dragonfly) are preserved rather than replaced with '[Circular]'. */ private merge(...objects: Record[]): Record { const ancestors = new WeakSet(); const mergeRecursive = (...objs: Record[]): Record => { const result: Record = {}; for (const obj of objs) { for (const [key, value] of Object.entries(obj)) { if (value === null || value === undefined) { result[key] = value; } else if ( typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) ) { if (ancestors.has(value)) { result[key] = '[Circular]'; continue; } ancestors.add(value); try { result[key] = mergeRecursive( (result[key] && typeof result[key] === 'object' && !Array.isArray(result[key]) ? (result[key] as Record) : {}), value as Record ); } finally { ancestors.delete(value); } } else { result[key] = value; } } } return result; }; return mergeRecursive(...objects); } }