import { Injectable, Logger } from '@nestjs/common'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import * as yaml from 'js-yaml'; import { AccountConfig, BotConfig, RootConfig, rootConfigSchema, } from './schema'; /** * 加载并校验 bots.yaml。 * 支持把配置里的 "env(VAR_NAME)" 解析为对应环境变量值,避免明文密码入库。 * 采用惰性加载,确保即使在其它 provider 构造期被读取也已就绪。 */ @Injectable() export class ConfigService { private readonly logger = new Logger(ConfigService.name); private config?: RootConfig; private ensureLoaded(): RootConfig { if (this.config) return this.config; const path = resolve(process.env.BOT_CONFIG_PATH ?? './config/bots.yaml'); let raw: string; try { raw = readFileSync(path, 'utf8'); } catch (err: unknown) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') { throw new Error( `配置文件不存在: ${path}\n` + `请复制示例文件并填写配置:\n` + ` cp config/bots.example.yaml config/bots.yaml\n` + `然后根据注释修改真实账号、房间等信息。`, ); } throw err; } const parsed = yaml.load(raw); const resolved = this.resolveEnvRefs(parsed); this.config = rootConfigSchema.parse(resolved); this.logger.log( `已加载配置: ${Object.keys(this.config.accounts).length} 个账号, ${this.config.rooms.length} 个管理房间`, ); return this.config; } get all(): RootConfig { return this.ensureLoaded(); } get bots(): BotConfig[] { return this.ensureLoaded().bots; } getAccount(name: string): AccountConfig { const acc = this.ensureLoaded().accounts[name]; if (!acc) { throw new Error(`未找到账号配置: ${name}`); } return acc; } get isDryRun(): boolean { return (process.env.DRY_RUN ?? 'false').toLowerCase() === 'true'; } /** 递归把字符串里的 env(VAR) 替换为 process.env.VAR。 */ private resolveEnvRefs(value: unknown): unknown { if (typeof value === 'string') { const match = value.match(/^env\((.+)\)$/); if (match) { const envVal = process.env[match[1]]; if (envVal === undefined) { throw new Error(`配置引用了未设置的环境变量: ${match[1]}`); } return envVal; } return value; } if (Array.isArray(value)) { return value.map((v) => this.resolveEnvRefs(v)); } if (value && typeof value === 'object') { return Object.fromEntries( Object.entries(value).map(([k, v]) => [k, this.resolveEnvRefs(v)]), ); } return value; } }