225 lines
7.8 KiB
TypeScript
225 lines
7.8 KiB
TypeScript
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { dirname, join } from "node:path";
|
|
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.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)) {
|
|
copyFileSync(legacyPath, primaryPath);
|
|
copied.push(file);
|
|
} else {
|
|
const legacyMtime = statSync(legacyPath).mtimeMs;
|
|
const primaryMtime = statSync(primaryPath).mtimeMs;
|
|
if (legacyMtime > primaryMtime) {
|
|
copyFileSync(legacyPath, primaryPath);
|
|
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 function loadCorpConfigs(): CorpConfig[] {
|
|
const dirs = resolveEnterprisesDirs();
|
|
const byId = new Map<string, CorpConfig>();
|
|
|
|
for (const dir of dirs) {
|
|
for (const file of readdirSync(dir)
|
|
.filter((item) => item.endsWith(".json"))
|
|
.filter((item) => !item.startsWith("example."))) {
|
|
const content = readFileSync(join(dir, file), "utf-8");
|
|
const corp = CorpConfigSchema.parse(JSON.parse(content));
|
|
byId.set(corp.id, corp);
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
export function loadGlobalConfig(): GlobalConfig {
|
|
const file = resolveGlobalConfigFile();
|
|
if (!existsSync(file)) {
|
|
return GlobalConfigSchema.parse({});
|
|
}
|
|
|
|
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
|
|
}
|
|
|
|
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;
|
|
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
|
|
return normalized;
|
|
}
|
|
|
|
export function findCorpConfigFile(corpId: string): string | undefined {
|
|
const dirs = resolveEnterprisesDirs();
|
|
for (const dir of dirs) {
|
|
if (!existsSync(dir)) continue;
|
|
for (const file of readdirSync(dir)
|
|
.filter((item) => item.endsWith(".json"))
|
|
.filter((item) => !item.startsWith("example."))) {
|
|
const fullPath = join(dir, file);
|
|
try {
|
|
const content = readFileSync(fullPath, "utf-8");
|
|
const parsed = JSON.parse(content);
|
|
if (parsed && typeof parsed === "object" && parsed.id === corpId) {
|
|
return fullPath;
|
|
}
|
|
} catch {
|
|
// ignore malformed files
|
|
}
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
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);
|
|
writeFileSync(filePath, `${JSON.stringify(validated, null, 2)}\n`, "utf-8");
|
|
return validated;
|
|
}
|