|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const axios = require('axios'); |
| 4 | +const { execFile } = require('child_process'); |
| 5 | +const { promisify } = require('util'); |
| 6 | +const execFileAsync = promisify(execFile); |
| 7 | +const EventEmitter = require('events'); |
| 8 | + |
| 9 | +class ConfigLoader extends EventEmitter { |
| 10 | + constructor(initialConfig) { |
| 11 | + super(); |
| 12 | + this.config = initialConfig; |
| 13 | + this.reloadTimer = null; |
| 14 | + this.isReloading = false; |
| 15 | + } |
| 16 | + |
| 17 | + async start() { |
| 18 | + const { configurationSources } = this.config; |
| 19 | + if (!configurationSources?.enabled) { |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + // Start periodic reload if interval is set |
| 24 | + if (configurationSources.reloadIntervalSeconds > 0) { |
| 25 | + this.reloadTimer = setInterval( |
| 26 | + () => this.reloadConfiguration(), |
| 27 | + configurationSources.reloadIntervalSeconds * 1000, |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + // Do initial load |
| 32 | + await this.reloadConfiguration(); |
| 33 | + } |
| 34 | + |
| 35 | + stop() { |
| 36 | + if (this.reloadTimer) { |
| 37 | + clearInterval(this.reloadTimer); |
| 38 | + this.reloadTimer = null; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + async reloadConfiguration() { |
| 43 | + if (this.isReloading) return; |
| 44 | + this.isReloading = true; |
| 45 | + |
| 46 | + try { |
| 47 | + const { configurationSources } = this.config; |
| 48 | + if (!configurationSources?.enabled) return; |
| 49 | + |
| 50 | + const configs = await Promise.all( |
| 51 | + configurationSources.sources |
| 52 | + .filter((source) => source.enabled) |
| 53 | + .map((source) => this.loadFromSource(source)), |
| 54 | + ); |
| 55 | + |
| 56 | + // Use merge strategy based on configuration |
| 57 | + const shouldMerge = configurationSources.merge ?? true; // Default to true for backward compatibility |
| 58 | + const newConfig = shouldMerge |
| 59 | + ? configs.reduce( |
| 60 | + (acc, curr) => { |
| 61 | + return this.deepMerge(acc, curr); |
| 62 | + }, |
| 63 | + { ...this.config }, |
| 64 | + ) |
| 65 | + : { ...this.config, ...configs[configs.length - 1] }; // Use last config for override |
| 66 | + |
| 67 | + // Emit change event if config changed |
| 68 | + if (JSON.stringify(newConfig) !== JSON.stringify(this.config)) { |
| 69 | + this.config = newConfig; |
| 70 | + this.emit('configurationChanged', this.config); |
| 71 | + } |
| 72 | + } catch (error) { |
| 73 | + console.error('Error reloading configuration:', error); |
| 74 | + this.emit('configurationError', error); |
| 75 | + } finally { |
| 76 | + this.isReloading = false; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + async loadFromSource(source) { |
| 81 | + switch (source.type) { |
| 82 | + case 'file': |
| 83 | + return this.loadFromFile(source); |
| 84 | + case 'http': |
| 85 | + return this.loadFromHttp(source); |
| 86 | + case 'git': |
| 87 | + return this.loadFromGit(source); |
| 88 | + default: |
| 89 | + throw new Error(`Unsupported configuration source type: ${source.type}`); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + async loadFromFile(source) { |
| 94 | + const configPath = path.resolve(process.cwd(), source.path); |
| 95 | + const content = await fs.promises.readFile(configPath, 'utf8'); |
| 96 | + return JSON.parse(content); |
| 97 | + } |
| 98 | + |
| 99 | + async loadFromHttp(source) { |
| 100 | + const headers = { |
| 101 | + ...source.headers, |
| 102 | + ...(source.auth?.type === 'bearer' ? { Authorization: `Bearer ${source.auth.token}` } : {}), |
| 103 | + }; |
| 104 | + |
| 105 | + const response = await axios.get(source.url, { headers }); |
| 106 | + return response.data; |
| 107 | + } |
| 108 | + |
| 109 | + async loadFromGit(source) { |
| 110 | + // Validate inputs |
| 111 | + if (!source.repository || typeof source.repository !== 'string') { |
| 112 | + throw new Error('Invalid repository URL'); |
| 113 | + } |
| 114 | + if (source.branch && typeof source.branch !== 'string') { |
| 115 | + throw new Error('Invalid branch name'); |
| 116 | + } |
| 117 | + |
| 118 | + const tempDir = path.join(process.cwd(), '.git-config-cache'); |
| 119 | + await fs.promises.mkdir(tempDir, { recursive: true }); |
| 120 | + |
| 121 | + const repoDir = path.join(tempDir, Buffer.from(source.repository).toString('base64')); |
| 122 | + |
| 123 | + // Clone or pull repository |
| 124 | + if (!fs.existsSync(repoDir)) { |
| 125 | + if (source.auth?.type === 'ssh') { |
| 126 | + process.env.GIT_SSH_COMMAND = `ssh -i ${source.auth.privateKeyPath}`; |
| 127 | + } |
| 128 | + await execFileAsync('git', ['clone', source.repository, repoDir]); |
| 129 | + } else { |
| 130 | + await execFileAsync('git', ['pull'], { cwd: repoDir }); |
| 131 | + } |
| 132 | + |
| 133 | + // Checkout specific branch if specified |
| 134 | + if (source.branch) { |
| 135 | + await execFileAsync('git', ['checkout', source.branch], { cwd: repoDir }); |
| 136 | + } |
| 137 | + |
| 138 | + // Read and parse config file |
| 139 | + const configPath = path.join(repoDir, source.path); |
| 140 | + const content = await fs.promises.readFile(configPath, 'utf8'); |
| 141 | + return JSON.parse(content); |
| 142 | + } |
| 143 | + |
| 144 | + deepMerge(target, source) { |
| 145 | + const output = { ...target }; |
| 146 | + if (isObject(target) && isObject(source)) { |
| 147 | + Object.keys(source).forEach((key) => { |
| 148 | + if (isObject(source[key])) { |
| 149 | + if (!(key in target)) { |
| 150 | + Object.assign(output, { [key]: source[key] }); |
| 151 | + } else { |
| 152 | + output[key] = this.deepMerge(target[key], source[key]); |
| 153 | + } |
| 154 | + } else { |
| 155 | + Object.assign(output, { [key]: source[key] }); |
| 156 | + } |
| 157 | + }); |
| 158 | + } |
| 159 | + return output; |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +function isObject(item) { |
| 164 | + return item && typeof item === 'object' && !Array.isArray(item); |
| 165 | +} |
| 166 | + |
| 167 | +module.exports = ConfigLoader; |
0 commit comments