config.ts 5.28 KB
import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import {
    loadConfig,
    configExists,
    emptyProfile,
    type ModelConfig,
    type FigmaConfig,
    type ProjectProfile,
} from 'coderio';
import { getOllamaConfig } from './ollama-state';
import type { ServerConfigView } from './types';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

/** Canonical location for the target-project profile (画像) managed by the UI. */
export const PROJECT_PROFILE_FILE = path.resolve(homedir(), '.coderio', 'coderio.project.json');

/**
 * Load the target-project profile (画像) that describes Project A's bespoke
 * component library / tokens / utils / conventions. Returns `null` when the
 * file does not exist, so generation falls back to generic output.
 */
export function loadProjectProfile(): ProjectProfile | null {
    if (!existsSync(PROJECT_PROFILE_FILE)) return null;
    try {
        const raw = JSON.parse(readFileSync(PROJECT_PROFILE_FILE, 'utf8')) as Partial<ProjectProfile>;
        return { ...emptyProfile(), ...raw, tokens: raw.tokens ?? [], components: raw.components ?? [], utils: raw.utils ?? [] };
    } catch {
        return null;
    }
}

/** Persist the project profile to the canonical location (used by PUT). */
export function saveProjectProfile(profile: ProjectProfile): void {
    const dir = path.dirname(PROJECT_PROFILE_FILE);
    if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
    writeFileSync(PROJECT_PROFILE_FILE, JSON.stringify(profile, null, 2), 'utf8');
}

/** A fresh seed template for the UI to present when no profile exists yet. */
export function projectProfileTemplate(): ProjectProfile {
    return emptyProfile();
}

/**
 * Minimal `.env` loader (no external dependency). Reads the first `.env` found
 * in CWD or the server package dir, populating `process.env` for keys that are
 * not already set. This keeps secrets server-side and out of the frontend.
 */
export function loadDotEnv(): void {
    const candidates = [
        path.resolve(process.cwd(), '.env'),
        path.join(__dirname, '..', '.env'),
    ];
    for (const file of candidates) {
        if (existsSync(file)) {
            try {
                const raw = readFileSync(file, 'utf8');
                for (const line of raw.split('\n')) {
                    const m = line.match(/^\s*([\w.-]+)\s*=\s*(.*)\s*$/);
                    if (!m) continue;
                    const key = m[1];
                    const val = m[2].replace(/^["']|["']$/g, '');
                    if (process.env[key] === undefined) process.env[key] = val;
                }
            } catch {
                /* ignore malformed .env */
            }
            return;
        }
    }
}

/**
 * The full credential bundle the server uses to drive the coderio engine.
 * Resolution order: environment variables > ~/.coderio/config.yaml > defaults.
 */
export interface ServerModelConfig {
    provider: string;
    model: string;
    baseUrl: string;
    apiKey: string;
    figmaToken: string;
}

export function loadServerModelConfig(): ServerModelConfig {
    const env = process.env;
    let fileModel: Partial<ModelConfig> = {};
    let fileFigma: Partial<FigmaConfig> = {};
    if (configExists()) {
        try {
            const c = loadConfig();
            fileModel = c.model ?? {};
            fileFigma = c.figma ?? {};
        } catch {
            /* ignore unreadable config */
        }
    }
    const cfg: ServerModelConfig = {
        provider: env.CODERIO_PROVIDER ?? fileModel.provider ?? 'openai',
        model: env.CODERIO_MODEL ?? fileModel.model ?? 'qwen3.8-max',
        baseUrl: env.CODERIO_BASE_URL ?? fileModel.baseUrl ?? '',
        apiKey: env.CODERIO_API_KEY ?? fileModel.apiKey ?? '',
        figmaToken: env.CODERIO_FIGMA_TOKEN ?? fileFigma.token ?? '',
    };
    // 运行时覆盖优先:前端「使用」本地模型时,ollama-state 记录下当前生效的
    // Ollama 配置(不入 coderio dist,避免重建依赖)。此处优先采用,使后续生成
    // 子进程真正走本地 Ollama 而非 config.yaml/env 的远程模型;断开后回退默认值。
    const oc = getOllamaConfig();
    if (oc) {
        cfg.provider = oc.provider;
        cfg.model = oc.model;
        cfg.baseUrl = oc.baseUrl;
        cfg.apiKey = oc.apiKey;
    }
    return cfg;
}

/** Frontend-safe view: never includes the actual secret values. */
export function configView(model: ServerModelConfig, maxConcurrent: number): ServerConfigView {
    return {
        provider: model.provider,
        model: model.model,
        baseUrl: model.baseUrl,
        apiKeySet: Boolean(model.apiKey),
        figmaTokenSet: Boolean(model.figmaToken),
        maxConcurrent,
    };
}

export function resolveServerOptions() {
    const dataDir = path.resolve(process.env.CODERIO_SERVER_DATA_DIR ?? './data');
    const outputDir = path.resolve(process.env.CODERIO_OUTPUT_DIR ?? path.join(dataDir, 'output'));
    const port = Number(process.env.CODERIO_SERVER_PORT ?? 4173);
    const host = process.env.CODERIO_SERVER_HOST ?? '0.0.0.0';
    const maxConcurrent = Math.max(1, Number(process.env.CODERIO_MAX_CONCURRENT ?? 1) || 1);
    return { dataDir, outputDir, port, host, maxConcurrent };
}