schemas.ts 2.22 KB
import { z } from 'zod';
import { parseFigmaUrl } from './url-parser.js';

/**
 * Where the generated code should land, chosen by the user on the workbench.
 * Mirrors `GenerationTarget` in the backend's contract types.
 */
export const GenerationTargetSchema = z.object({
    mode: z.enum(['standalone', 'new-page', 'modify-slot']),
    page: z.string().optional(),
    slot: z.string().optional(),
});

/** Tech stack chosen for a standalone generation. */
export const TechStackSchema = z.object({
    framework: z.string(),
    styling: z.string().optional(),
    componentLibrary: z.string().optional(),
});

/**
 * POST /api/generate 入参 schema —— 前后端共享的「单一契约来源」。
 *
 * - figmaUrl:必填,且需通过 parseFigmaUrl(含 design/file 链接与 ?node-id=)。
 * - mode:枚举,缺省 'full'。
 * - target / stack:对象结构(standalone / new-page / modify-slot),可为 null / 缺省。
 * - 其余字段可选,缺省给出与后端一致的值(appName='my-app'、fillContainer=true)。
 *
 * 后端用 `ctx.parseJsonBody` 校验(失败映射为 400),前端提交前用同一 schema 校验,
 * 二者永远不会出现「后端拒收 / 前端照发」的错位。
 */
export const GenerateSchema = z.object({
    figmaUrl: z
        .string()
        .trim()
        .min(1, 'figmaUrl 为必填项')
        .refine(
            (u) => {
                try {
                    parseFigmaUrl(u);
                    return true;
                } catch {
                    return false;
                }
            },
            'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)',
        ),
    mode: z.enum(['full', 'code', 'with-report']).default('full'),
    outputDir: z.string().optional(),
    appName: z.string().optional().default('my-app'),
    target: GenerationTargetSchema.nullable().optional(),
    stack: TechStackSchema.nullable().optional(),
    fillContainer: z.boolean().optional().default(true),
});

/** 校验后的输出类型(含默认值 / 转换)。 */
export type GenerateInput = z.infer<typeof GenerateSchema>;
/** 客户端提交的输入类型(带默认值的字段为可选)。 */
export type GenerateRequest = z.input<typeof GenerateSchema>;