index.ts 2.51 KB
/**
 * Validation module.
 */

import fs from 'node:fs';
import path from 'node:path';

import type { GraphState } from '../../state';
import { METRIC_DECIMAL_PLACES } from './constants';
import { logger } from '../../utils/logger';
import { validationLoop } from './core/validation-loop';
import { commit } from './commit/index';
import { ValidationMode } from '../../types/graph-types';

/**
 * LangGraph node: run validation on the generated app and write a report into the workspace.
 * Reads validation mode from state.config.validationMode (defaults to 'full').
 * Throws error if validation fails (MAE threshold not reached) or execution errors occur.
 */
export const runValidation = async (state: GraphState): Promise<void> => {
    logger.reportPhase('校验与提交', 92);
    if (!state.protocol) {
        throw new Error('No protocol found for validation (state.protocol is missing).');
    }
    if (!state.figmaInfo?.thumbnail) {
        throw new Error('Missing Figma thumbnail URL (state.figmaInfo.thumbnail is missing).');
    }

    const mode = state.config?.validationMode ?? ValidationMode.Full;
    // Code-only mode: skip validation, only commit and exit
    if (mode === ValidationMode.CodeOnly) {
        logger.printInfoLog('仅代码模式:跳过校验,直接提交生成的代码…');
        const commitResult = await commit({ appPath: state.workspace.app });
        if (!commitResult.success) {
            logger.printWarnLog(`代码提交失败:${commitResult.message}`);
        } else {
            logger.printSuccessLog('代码已成功提交');
        }
        return;
    }

    const outputDir = path.join(state.workspace.process, 'validation');
    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, { recursive: true });
    }

    logger.printInfoLog(`开始校验循环(模式:${mode})…`);

    const result = await validationLoop({
        protocol: state.protocol,
        figmaThumbnailUrl: state.figmaInfo.thumbnail,
        outputDir,
        workspace: state.workspace,
        config: { mode },
    });

    if (result.error) {
        throw new Error(result.error);
    }

    const reportHtmlPath = path.join(outputDir, 'index.html');
    if (result.validationPassed) {
        logger.printSuccessLog(`校验通过(MAE:${result.finalMae.toFixed(METRIC_DECIMAL_PLACES)}px)`);
    } else {
        logger.printWarnLog(`校验未通过(MAE:${result.finalMae.toFixed(METRIC_DECIMAL_PLACES)}px)`);
    }
    logger.printInfoLog(`校验报告已生成:${reportHtmlPath}`);
};