Files
seal-use/src/core/config/loader.ts
T

274 lines
9.9 KiB
TypeScript

import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
import { writeSecureFile } from "../secure-file.js";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
const USER_DIR_ENV = "SEAL_USE_USER_ENTERPRISES_DIR";
const LEGACY_USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR";
const GLOBAL_CONFIG_ENV = "SEAL_USE_CONFIG_FILE";
const LEGACY_GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE";
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-use", "enterprises");
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises");
const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-use", "config.json");
const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json");
export function syncLegacyEnterprisesDir(
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
): { copied: string[]; deletedLegacyDir: boolean } {
if (!existsSync(legacyDir)) {
return { copied: [], deletedLegacyDir: false };
}
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
const copied: string[] = [];
let legacyFiles: string[] = [];
try {
legacyFiles = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
} catch {
return { copied: [], deletedLegacyDir: false };
}
for (const file of legacyFiles) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath)) {
writeSecureFile(primaryPath, readFileSync(legacyPath));
copied.push(file);
} else {
const legacyMtime = statSync(legacyPath).mtimeMs;
const primaryMtime = statSync(primaryPath).mtimeMs;
if (legacyMtime > primaryMtime) {
writeSecureFile(primaryPath, readFileSync(legacyPath));
copied.push(file);
}
}
}
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;
const now = Date.now();
let hasNewerFileInLegacy = false;
let hasRecentlyModifiedFile = false;
for (const file of readdirSync(legacyDir)) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
const stat = statSync(legacyPath);
if (now - stat.mtimeMs < SEVEN_DAYS_MS) {
hasRecentlyModifiedFile = true;
}
if (file.endsWith(".json") && existsSync(primaryPath)) {
if (stat.mtimeMs > statSync(primaryPath).mtimeMs) {
hasNewerFileInLegacy = true;
}
}
}
const dirStat = statSync(legacyDir);
const dirRecentlyModified = now - dirStat.mtimeMs < SEVEN_DAYS_MS;
let deletedLegacyDir = false;
if (!hasNewerFileInLegacy && !hasRecentlyModifiedFile && !dirRecentlyModified) {
rmSync(legacyDir, { recursive: true, force: true });
deletedLegacyDir = true;
}
return { copied, deletedLegacyDir };
}
export type CorpConfigLoadIssue = { dir: string; file: string; reason: string };
let lastCorpLoadIssues: CorpConfigLoadIssue[] = [];
// Files already warned about this process: loadCorpConfigs runs several times
// per invocation (selection, dispatch, tool handlers), so warn each file once.
const warnedCorpFiles = new Set<string>();
/**
* Issues from the most recent loadCorpConfigs() call. A malformed file must not
* abort the directory: the remaining enterprises stay usable and the caller
* reports the bad file by name instead of failing every command with a bare
* JSON parse error.
*/
export function getLastCorpConfigLoadIssues(): CorpConfigLoadIssue[] {
return lastCorpLoadIssues;
}
export function loadCorpConfigs(): CorpConfig[] {
return loadCorpConfigEntries().map((entry) => entry.config);
}
function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
const dirs = resolveEnterprisesDirs();
const byId = new Map<string, { config: CorpConfig; path: string }>();
const issues: CorpConfigLoadIssue[] = [];
for (const dir of dirs) {
for (const file of readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
let corp: CorpConfig;
try {
const content = readFileSync(fullPath, "utf-8");
corp = CorpConfigSchema.parse(JSON.parse(content));
} catch (error) {
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
continue;
}
byId.set(corp.id, { config: corp, path: fullPath });
}
}
lastCorpLoadIssues = issues;
const fresh = issues.filter((issue) => {
const key = `${issue.dir}/${issue.file}`;
if (warnedCorpFiles.has(key)) return false;
warnedCorpFiles.add(key);
return true;
});
if (fresh.length) {
console.error(
`⚠️ 跳过 ${fresh.length} 个无法解析的企业配置: ${fresh.map((item) => `${item.dir}/${item.file}`).join(", ")}`
);
console.error(`👉 Next action: seal-use doctor (检查配置文件格式与权限)`);
}
return Array.from(byId.values());
}
export function resolveEnterprisesDir(): string | undefined {
return resolveEnterprisesDirs()[0];
}
function resolveEnterprisesDirs(): string[] {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return existsSync(configured) ? [configured] : [];
const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim();
let userDirs: string[];
if (configuredUserDir) {
userDirs = existsSync(configuredUserDir) ? [configuredUserDir] : [];
} else {
try {
syncLegacyEnterprisesDir();
} catch {}
userDirs = existsSync(PRIMARY_USER_ENTERPRISES_DIR)
? [PRIMARY_USER_ENTERPRISES_DIR]
: (existsSync(LEGACY_USER_ENTERPRISES_DIR) ? [LEGACY_USER_ENTERPRISES_DIR] : [PRIMARY_USER_ENTERPRISES_DIR]);
}
const globalConfig = loadGlobalConfig();
const testDir = globalConfig.testEnterprisesDir?.trim();
const candidates = testDir ? [testDir, ...userDirs] : userDirs;
const uniqueExisting: string[] = [];
for (const d of candidates) {
if (existsSync(d) && !uniqueExisting.includes(d)) {
uniqueExisting.push(d);
}
}
return uniqueExisting;
}
export function resolveWritableEnterprisesDir(): string {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return configured;
const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim();
if (configuredUserDir) return configuredUserDir;
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
if (testDir && existsSync(testDir)) return testDir;
return PRIMARY_USER_ENTERPRISES_DIR;
}
export function getEnterprisesDirCandidates(): string[] {
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
return [
`${CONFIG_ENV}=<path>`,
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
PRIMARY_USER_ENTERPRISES_DIR,
LEGACY_USER_ENTERPRISES_DIR
];
}
export function resolveGlobalConfigFile(): string {
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
if (configured) return configured;
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
return PRIMARY_GLOBAL_CONFIG_FILE;
}
let lastGlobalConfigIssue: { file: string; reason: string } | undefined;
/**
* Issue from the most recent loadGlobalConfig() call, if the configured file
* existed but could not be parsed. `doctor` reads this to surface the bad file;
* commands otherwise continue on defaults instead of failing outright.
*/
export function getLastGlobalConfigIssue(): { file: string; reason: string } | undefined {
return lastGlobalConfigIssue;
}
export function loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
lastGlobalConfigIssue = undefined;
if (!existsSync(file)) {
return GlobalConfigSchema.parse({});
}
try {
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
} catch (error) {
// A hand-edited config.json must not brick every command: fall back to
// defaults so the user can still run `seal-use config paths` / `corps list`
// to find and fix the file.
const reason = error instanceof Error ? error.message : String(error);
lastGlobalConfigIssue = { file, reason };
console.error(`⚠️ 全局配置无法解析,已回退默认值: ${file} (${reason})`);
console.error(`👉 Next action: seal-use config paths (检查配置文件)`);
return GlobalConfigSchema.parse({});
}
}
export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
const file = configured || PRIMARY_GLOBAL_CONFIG_FILE;
writeSecureFile(file, `${JSON.stringify(normalized, null, 2)}\n`);
return normalized;
}
export function findCorpConfigFile(corpId: string): string | undefined {
return loadCorpConfigEntries().find((entry) => entry.config.id === corpId)?.path;
}
export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): CorpConfig {
const filePath = findCorpConfigFile(corpId);
if (!filePath) {
throw new Error(`Enterprise config not found: ${corpId}`);
}
const raw = JSON.parse(readFileSync(filePath, "utf-8"));
const merged = { ...raw, ...patch };
for (const key of Object.keys(patch) as Array<keyof CorpConfig>) {
if (patch[key] === undefined) {
delete merged[key];
}
}
const validated = CorpConfigSchema.parse(merged);
writeSecureFile(filePath, `${JSON.stringify(validated, null, 2)}\n`);
return validated;
}