anya/config/index.ts

89 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-10-06 13:56:33 +05:30
import fs from "fs";
import { z } from "zod";
import path from "path";
export const dataDir = path.join(process.env.ANYA_DIR || "./");
export const pathInDataDir = (filename: string) => path.join(dataDir, filename);
interface PlatformIdentity {
2025-01-09 16:27:26 +05:30
platform:
2025-01-12 20:05:43 +05:30
| "discord"
| "whatsapp"
| "email"
| "events"
| "linear_key"
| "linear_email";
2024-10-06 13:56:33 +05:30
id: string; // Platform-specific user ID
}
export interface UserConfig {
name: string;
identities: PlatformIdentity[];
2024-10-07 17:26:33 +05:30
friends?: {
2024-10-06 13:56:33 +05:30
related_as: string[];
user: UserConfig;
}[];
roles: string[]; // Roles assigned to the user
}
// Define Zod schemas for validation
const PlatformIdentitySchema = z.object({
2025-01-09 16:27:26 +05:30
platform: z.enum([
"discord",
"whatsapp",
"email",
"events",
"linear_key",
"linear_email",
]),
2024-10-06 13:56:33 +05:30
id: z.string(),
});
const UserConfigSchema: z.ZodType<UserConfig> = z.lazy(() =>
z.object({
name: z.string(),
identities: z.array(PlatformIdentitySchema),
2024-10-07 17:26:33 +05:30
friends: z
2024-10-06 13:56:33 +05:30
.array(
z.object({
related_as: z.array(z.string()),
user: UserConfigSchema, // recursive schema for relatives
})
)
.optional(),
roles: z.array(z.string()),
})
);
// Schema for the full configuration file
const ConfigSchema = z.object({
users: z.array(UserConfigSchema),
rolePermissions: z.record(z.string(), z.array(z.string())),
});
2025-01-12 20:05:43 +05:30
// Mutable exports that will be updated
export let userConfigs: UserConfig[] = [];
export let rolePermissions: Record<string, string[]> = {};
2024-10-06 13:56:33 +05:30
2025-01-12 20:05:43 +05:30
// Function to load config
function loadConfig() {
try {
const userConfigPath = pathInDataDir("user-config.json");
const rawData = fs.readFileSync(userConfigPath, "utf-8");
const parsedData = JSON.parse(rawData);
const configData = ConfigSchema.parse(parsedData);
2024-10-06 13:56:33 +05:30
2025-01-12 20:05:43 +05:30
// Update the exported variables
userConfigs = configData.users;
rolePermissions = configData.rolePermissions;
} catch (error) {
console.error("Error loading config:", error);
}
}
// Initial load
loadConfig();
// Setup auto-reload every minute
setInterval(loadConfig, 60 * 1000);