1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
| class ConfigLoader { private layers: Map<ConfigLevel, ConfigLayer> = new Map(); private schema: ConfigSchema[] = []; private cache: Map<string, any> = new Map(); constructor(schema: ConfigSchema[]) { this.schema = schema; } async loadAll(options: LoadOptions): Promise<void> { await this.loadDefaultLayer(); if (options.globalConfigPath) { await this.loadGlobalLayer(options.globalConfigPath); } if (options.projectConfigPath) { await this.loadProjectLayer(options.projectConfigPath); } await this.loadEnvironmentLayer(); if (options.cliArgs) { await this.loadCommandLineLayer(options.cliArgs); } this.validate(); this.buildCache(); } private async loadDefaultLayer(): Promise<void> { const defaultData = this.schema.reduce((acc, field) => { if (field.default !== undefined) { acc[field.key] = field.default; } return acc; }, {} as Record<string, any>); this.layers.set(ConfigLevel.Default, { level: ConfigLevel.Default, source: 'builtin', data: defaultData, priority: 0, loadedAt: new Date(), }); } private async loadGlobalLayer(configPath: string): Promise<void> { try { const content = await fs.promises.readFile(configPath, 'utf-8'); const data = yaml.parse(content); this.layers.set(ConfigLevel.Global, { level: ConfigLevel.Global, source: configPath, data: this.interpolateEnvVars(data), priority: 1, loadedAt: new Date(), }); } catch (error) { console.debug('Global config not found:', configPath); } } private async loadProjectLayer(configPath: string): Promise<void> { try { const content = await fs.promises.readFile(configPath, 'utf-8'); const data = yaml.parse(content); this.layers.set(ConfigLevel.Project, { level: ConfigLevel.Project, source: configPath, data: this.interpolateEnvVars(data), priority: 2, loadedAt: new Date(), }); } catch (error) { console.debug('Project config not found:', configPath); } } private async loadEnvironmentLayer(): Promise<void> { const envData: Record<string, any> = {}; const prefix = 'OPENCLAW_'; for (const [key, value] of Object.entries(process.env)) { if (key.startsWith(prefix)) { const configKey = key.substring(prefix.length).toLowerCase(); envData[configKey] = this.parseEnvValue(value); } } this.layers.set(ConfigLevel.Environment, { level: ConfigLevel.Environment, source: 'environment', data: envData, priority: 3, loadedAt: new Date(), }); } private async loadCommandLineLayer(args: string[]): Promise<void> { const cliData: Record<string, any> = {}; for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg.startsWith('--')) { const [key, value] = arg.substring(2).split('='); const configKey = key.toLowerCase(); cliData[configKey] = value !== undefined ? this.parseCliValue(value) : true; } } this.layers.set(ConfigLevel.CommandLine, { level: ConfigLevel.CommandLine, source: 'cli', data: cliData, priority: 4, loadedAt: new Date(), }); } private interpolateEnvVars(data: Record<string, any>): Record<string, any> { return JSON.parse(JSON.stringify(data, (key, value) => { if (typeof value === 'string' && value.includes('${')) { return value.replace(/\$\{([^}]+)\}/g, (_, varName) => { return process.env[varName] || value; }); } return value; })); } private parseEnvValue(value: string): any { if (value === 'true') return true; if (value === 'false') return false; if (/^\d+$/.test(value)) return parseInt(value); if (/^\d+\.\d+$/.test(value)) return parseFloat(value); return value; } private parseCliValue(value: string): any { if (value === 'true') return true; if (value === 'false') return false; if (/^\d+$/.test(value)) return parseInt(value); return value; } private validate(): void { const config = this.getMergedConfig(); for (const field of this.schema) { if (field.required && config[field.key] === undefined) { throw new ConfigError( `Missing required config: ${field.key}` ); } const value = config[field.key]; if (value !== undefined && !this.checkType(value, field.type)) { throw new ConfigError( `Invalid type for ${field.key}: expected ${field.type}, got ${typeof value}` ); } if (typeof value === 'number') { if (field.min !== undefined && value < field.min) { throw new ConfigError( `${field.key} must be >= ${field.min}` ); } if (field.max !== undefined && value > field.max) { throw new ConfigError( `${field.key} must be <= ${field.max}` ); } } if (field.enum && !field.enum.includes(value)) { throw new ConfigError( `${field.key} must be one of: ${field.enum.join(', ')}` ); } } } private checkType(value: any, type: string): boolean { switch (type) { case 'string': return typeof value === 'string'; case 'number': return typeof value === 'number'; case 'boolean': return typeof value === 'boolean'; case 'object': return typeof value === 'object' && value !== null; case 'array': return Array.isArray(value); default: return true; } } private buildCache(): void { const config = this.getMergedConfig(); for (const [key, value] of Object.entries(config)) { this.cache.set(key, value); } } private getMergedConfig(): Record<string, any> { const result: Record<string, any> = {}; const sortedLayers = Array.from(this.layers.values()) .sort((a, b) => a.priority - b.priority); for (const layer of sortedLayers) { Object.assign(result, layer.data); } return result; } get<T>(key: string, defaultValue?: T): T { if (this.cache.has(key)) { return this.cache.get(key); } if (defaultValue !== undefined) { return defaultValue; } throw new ConfigError(`Config not found: ${key}`); } getSource(key: string): string | undefined { const sortedLayers = Array.from(this.layers.values()) .sort((a, b) => b.priority - a.priority); for (const layer of sortedLayers) { if (key in layer.data) { return layer.source; } } return undefined; } getAll(): Record<string, any> { return Object.fromEntries(this.cache); } }
interface LoadOptions { globalConfigPath?: string; projectConfigPath?: string; cliArgs?: string[]; }
class ConfigError extends Error { constructor(message: string) { super(message); this.name = 'ConfigError'; } }
|