Commit fa81b8af by liimin

feat(shared): 提取前后端共享契约与 zod 校验

将 Figma URL 解析与 GenerateSchema 统一收敛到新的 @coderio/shared 包,
后端通过 parseJsonBody 按 schema 校验并将失败映射为 400,前端提交前
用同一 schema 校验,避免前后端契约漂移。同时把各包依赖改为 pnpm
catalog 统一管理版本。
1 parent 6f8605f7
...@@ -9,11 +9,13 @@ ...@@ -9,11 +9,13 @@
"start": "tsx src/index.ts" "start": "tsx src/index.ts"
}, },
"dependencies": { "dependencies": {
"coderio": "workspace:*" "coderio": "workspace:*",
"@coderio/shared": "workspace:*",
"zod": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.0.0", "@types/node": "catalog:",
"tsx": "^4.21.0", "tsx": "catalog:",
"typescript": "^5.6.0" "typescript": "catalog:"
} }
} }
...@@ -27,6 +27,11 @@ export interface ServerCtx { ...@@ -27,6 +27,11 @@ export interface ServerCtx {
broadcast: (event: string, data: unknown) => void; broadcast: (event: string, data: unknown) => void;
sendJson: (res: ServerResponse, code: number, obj: unknown) => void; sendJson: (res: ServerResponse, code: number, obj: unknown) => void;
readJsonBody: <T = Record<string, unknown>>(req: IncomingMessage) => Promise<T>; readJsonBody: <T = Record<string, unknown>>(req: IncomingMessage) => Promise<T>;
/** 读取请求体并按 zod schema 校验;失败抛 `ValidationError`(全局映射为 400)。 */
parseJsonBody: <S extends import('zod').ZodTypeAny>(
req: IncomingMessage,
schema: S,
) => Promise<import('zod').z.infer<S>>;
computeStatus: () => SystemStatus; computeStatus: () => SystemStatus;
/** 是否由后端托管 UI(COD_SERVE_WEB !== '0')。 */ /** 是否由后端托管 UI(COD_SERVE_WEB !== '0')。 */
SERVE_WEB: boolean; SERVE_WEB: boolean;
......
import path from 'node:path'; import path from 'node:path';
import { parseFigmaUrl } from 'coderio'; import { GenerateSchema } from '@coderio/shared';
import type { Route } from './context'; import type { Route } from './context';
import type { GenerateRequest, Job } from '../types'; import type { Job } from '../types';
/** POST /api/generate:核心入口,提交一次 Figma 转代码任务。 */ /**
* POST /api/generate:核心入口,提交一次 Figma 转代码任务。
* 入参 schema(GenerateSchema)由 @coderio/shared 统一提供,前后端共用同一契约。
*/
export const generateRoutes: Route[] = [ export const generateRoutes: Route[] = [
{ {
method: 'POST', method: 'POST',
path: '/api/generate', path: '/api/generate',
handle: async ({ ctx, req, res }) => { handle: async ({ ctx, req, res }) => {
let body: GenerateRequest; // 读体 + zod 校验一体完成;失败抛 ValidationError(全局返回 400)
try { const body = await ctx.parseJsonBody(req, GenerateSchema);
body = await ctx.readJsonBody<GenerateRequest>(req); const { figmaUrl, mode, outputDir, appName, target, stack, fillContainer } = body;
} catch {
ctx.sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const figmaUrl = (body.figmaUrl || '').trim();
if (!figmaUrl) {
ctx.sendJson(res, 400, { error: 'figmaUrl 为必填项' });
return;
}
try {
// 校验 Figma URL 合法性(需含 design/file 链接与 ?node-id=)
parseFigmaUrl(figmaUrl);
} catch {
ctx.sendJson(res, 400, {
error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)',
});
return;
}
// 规范化生成模式(full / code / with-report),非法值回退到 full
const mode =
body.mode && ['full', 'code', 'with-report'].includes(body.mode)
? body.mode
: 'full';
// 构造 Job 对象:默认 queued 状态,记录输出目录、应用名、目标栈等参数 // 构造 Job 对象:默认 queued 状态,记录输出目录、应用名、目标栈等参数
const job: Job = { const job: Job = {
id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
status: 'queued', status: 'queued',
figmaUrl, figmaUrl,
mode, mode,
outputDir: body.outputDir ? path.resolve(body.outputDir) : ctx.opts.outputDir, outputDir: outputDir ? path.resolve(outputDir) : ctx.opts.outputDir,
appName: body.appName || 'my-app', appName,
target: body.target ?? null, target: target ?? null,
stack: body.stack ?? null, stack: stack ?? null,
fillContainer: body.fillContainer ?? true, fillContainer,
resultDir: null, resultDir: null,
reportPath: null, reportPath: null,
error: null, error: null,
......
...@@ -16,6 +16,7 @@ import type { ...@@ -16,6 +16,7 @@ import type {
import { createRouter } from './routes/router'; import { createRouter } from './routes/router';
import { routes } from './routes'; import { routes } from './routes';
import { WEB_DIST } from './http-utils'; import { WEB_DIST } from './http-utils';
import { ValidationError, readAndParse, formatIssues } from './validation';
import type { ServerCtx } from './routes/context'; import type { ServerCtx } from './routes/context';
// 开发模式(COD_SERVE_WEB=0)下后端不托管 UI。 // 开发模式(COD_SERVE_WEB=0)下后端不托管 UI。
...@@ -102,6 +103,12 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -102,6 +103,12 @@ export function createApp(deps: ServerDeps): AppHandle {
const readJsonBody = async <T = Record<string, unknown>>(req: IncomingMessage): Promise<T> => const readJsonBody = async <T = Record<string, unknown>>(req: IncomingMessage): Promise<T> =>
JSON.parse((await readBody(req)) || '{}') as T; JSON.parse((await readBody(req)) || '{}') as T;
/** 读取请求体并按 zod schema 校验;解析失败或 schema 不通过都抛 `ValidationError`。 */
const parseJsonBody = <S extends import('zod').ZodTypeAny>(
req: IncomingMessage,
schema: S,
): Promise<import('zod').z.infer<S>> => readAndParse(readBody, req, schema);
// 聚合系统状态快照:job 统计、orchestrator、engine、环境信息 // 聚合系统状态快照:job 统计、orchestrator、engine、环境信息
const computeStatus = (): SystemStatus => { const computeStatus = (): SystemStatus => {
const jobsList = store.list(); const jobsList = store.list();
...@@ -158,6 +165,7 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -158,6 +165,7 @@ export function createApp(deps: ServerDeps): AppHandle {
broadcast, broadcast,
sendJson, sendJson,
readJsonBody, readJsonBody,
parseJsonBody,
computeStatus, computeStatus,
SERVE_WEB, SERVE_WEB,
WEB_DIST: SERVE_WEB ? WEB_DIST : undefined, WEB_DIST: SERVE_WEB ? WEB_DIST : undefined,
...@@ -175,7 +183,12 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -175,7 +183,12 @@ export function createApp(deps: ServerDeps): AppHandle {
res.end('Not Found'); res.end('Not Found');
} }
} catch (err) { } catch (err) {
// 全局兜底:任意未捕获异常返回 500 // 参数校验失败:映射为 400,并附带结构化的 zod issues
if (err instanceof ValidationError) {
sendJson(res, 400, { error: '请求参数校验失败', issues: formatIssues(err.issues) });
return;
}
// 全局兜底:其余未捕获异常返回 500
sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }); sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
} }
}); });
......
import { z, type ZodTypeAny } from 'zod';
/**
* 请求参数校验失败。
* 由 `parseJsonBody` / `parseWith` 在 zod `safeParse` 不通过时抛出,
* 全局路由分发器捕获后映射为 HTTP 400,并在响应体中附带结构化的 `issues`。
*/
export class ValidationError extends Error {
readonly issues: z.ZodIssue[];
constructor(issues: z.ZodIssue[]) {
super('请求参数校验失败');
this.name = 'ValidationError';
this.issues = issues;
}
}
/**
* 用 zod schema 校验一个「已解析为对象」的 JSON 值。
* 成功返回解析后(含默认值/转换)的数据;失败抛出 `ValidationError`。
*/
export function parseWith<S extends ZodTypeAny>(json: unknown, schema: S): z.infer<S> {
const result = schema.safeParse(json);
if (!result.success) throw new ValidationError(result.error.issues);
return result.data;
}
/** 把 zod issues 整理成可返回前端的精简结构(path + message)。 */
export function formatIssues(issues: z.ZodIssue[]): { path: string; message: string }[] {
return issues.map((i) => ({
path: i.path.join('.') || '(root)',
message: i.message,
}));
}
/**
* 读取请求体字符串并按 zod schema 校验。
* 复用于所有需要 JSON 入参的路由:解析失败或 schema 不通过都抛 `ValidationError`。
*/
export async function readAndParse<S extends ZodTypeAny>(
readBody: (req: import('node:http').IncomingMessage) => Promise<string>,
req: import('node:http').IncomingMessage,
schema: S,
): Promise<z.infer<S>> {
const text = await readBody(req);
let json: unknown;
try {
json = text ? JSON.parse(text) : {};
} catch {
throw new ValidationError([
{ code: 'custom', path: [], message: 'Invalid JSON body' } as z.ZodIssue,
]);
}
return parseWith(json, schema);
}
...@@ -10,29 +10,30 @@ ...@@ -10,29 +10,30 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-label": "^2.1.1", "@coderio/shared": "workspace:*",
"@radix-ui/react-select": "^2.1.4", "@radix-ui/react-label": "catalog:",
"@radix-ui/react-slot": "^1.1.1", "@radix-ui/react-select": "catalog:",
"@radix-ui/react-tabs": "^1.1.2", "@radix-ui/react-slot": "catalog:",
"class-variance-authority": "^0.7.1", "@radix-ui/react-tabs": "catalog:",
"clsx": "^2.1.1", "class-variance-authority": "catalog:",
"lucide-react": "^0.460.0", "clsx": "catalog:",
"react": "^18.3.1", "lucide-react": "catalog:",
"react-dom": "^18.3.1", "react": "catalog:",
"react-router-dom": "^6.28.0", "react-dom": "catalog:",
"sonner": "^1.7.0", "react-router-dom": "catalog:",
"tailwind-merge": "^2.5.5" "sonner": "catalog:",
"tailwind-merge": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.10.0", "@types/node": "catalog:",
"@types/react": "^18.3.12", "@types/react": "catalog:",
"@types/react-dom": "^18.3.1", "@types/react-dom": "catalog:",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "catalog:",
"autoprefixer": "^10.4.20", "autoprefixer": "catalog:",
"postcss": "^8.4.49", "postcss": "catalog:",
"tailwindcss": "^3.4.15", "tailwindcss": "catalog:",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "catalog:",
"typescript": "^5.6.3", "typescript": "catalog:",
"vite": "^5.4.11" "vite": "catalog:"
} }
} }
...@@ -35,17 +35,9 @@ export interface ServerConfigView { ...@@ -35,17 +35,9 @@ export interface ServerConfigView {
maxConcurrent: number; maxConcurrent: number;
} }
export interface GenerateRequest { // 与后端共享的「单一契约来源」:直接复用 @coderio/shared 的 GenerateSchema 推导出的输入类型,
figmaUrl: string; // 不再手写一份、与后端漂移。
mode?: ValidationMode; export type GenerateRequest = import('@coderio/shared').GenerateRequest;
outputDir?: string;
appName?: string;
target?: GenerationTarget | null;
/** 生成前选定的技术栈(独立预览时生效;项目模式由「项目接入」画像决定,此处为 null)。 */
stack?: TechStack | null;
/** 生成的页面是否撑满容器(默认 true;固定宽度设计稿可选 false 居中)。 */
fillContainer?: boolean;
}
/** 一次生成所选的技术栈组合。 */ /** 一次生成所选的技术栈组合。 */
export interface TechStack { export interface TechStack {
......
...@@ -20,6 +20,7 @@ import { ...@@ -20,6 +20,7 @@ import {
Boxes, Boxes,
} from 'lucide-react'; } from 'lucide-react';
import { api, onSSE, checkBackendHealth } from '@/lib/api'; import { api, onSSE, checkBackendHealth } from '@/lib/api';
import { GenerateSchema } from '@coderio/shared';
import { cancelJob, deleteJob, startPreview as startPreviewAction, clearAllJobs } from '@/lib/jobActions'; import { cancelJob, deleteJob, startPreview as startPreviewAction, clearAllJobs } from '@/lib/jobActions';
import type { Job, LogEntry, LogLevel, PreviewState, ProjectRunState, ValidationMode, GenerationTarget, GenerationTargetMode, ProjectProfile, TechStack } from '@/lib/types'; import type { Job, LogEntry, LogLevel, PreviewState, ProjectRunState, ValidationMode, GenerationTarget, GenerationTargetMode, ProjectProfile, TechStack } from '@/lib/types';
import { STACK_PRESETS } from '@/components/project/profile-presets'; import { STACK_PRESETS } from '@/components/project/profile-presets';
...@@ -134,12 +135,7 @@ export default function Workbench() { ...@@ -134,12 +135,7 @@ export default function Workbench() {
}, []); }, []);
const handleSubmit = async () => { const handleSubmit = async () => {
if (!figmaUrl.trim()) return toast.error('请填写 Figma 链接'); const payload = {
if (!figmaUrl.includes('node-id=')) return toast.error('Figma 链接必须包含 ?node-id= 参数');
if (!backendReady) return toast.error('后端启动中,请稍候…', { description: '引擎与数据库初始化完成后即可生成' });
setSubmitting(true);
try {
const res = await api.generate({
figmaUrl: figmaUrl.trim(), figmaUrl: figmaUrl.trim(),
mode, mode,
target, target,
...@@ -147,7 +143,17 @@ export default function Workbench() { ...@@ -147,7 +143,17 @@ export default function Workbench() {
stack: target.mode === 'standalone' ? stack : null, stack: target.mode === 'standalone' ? stack : null,
// 默认撑满容器;固定宽度设计稿可取消 // 默认撑满容器;固定宽度设计稿可取消
fillContainer, fillContainer,
}); };
// 提交前用与后端同一套 schema 校验,避免「后端拒收 / 前端照发」错位
const parsed = GenerateSchema.safeParse(payload);
if (!parsed.success) {
const issue = parsed.error.issues[0];
return toast.error(issue?.message ?? '参数校验失败');
}
if (!backendReady) return toast.error('后端启动中,请稍候…', { description: '引擎与数据库初始化完成后即可生成' });
setSubmitting(true);
try {
const res = await api.generate(parsed.data);
toast.success('已提交生成任务', { description: res.message }); toast.success('已提交生成任务', { description: res.message });
} catch (e) { } catch (e) {
toast.error('提交失败', { description: e instanceof Error ? e.message : String(e) }); toast.error('提交失败', { description: e instanceof Error ? e.message : String(e) });
......
...@@ -16,7 +16,10 @@ ...@@ -16,7 +16,10 @@
"typecheck": "tsc -p tsconfig.json --noEmit" "typecheck": "tsc -p tsconfig.json --noEmit"
}, },
"dependencies": { "dependencies": {
"@langchain/openai": "^1.2.4", "@langchain/openai": "catalog:",
"@langchain/core": "^1.1.19" "@langchain/core": "catalog:"
},
"devDependencies": {
"typescript": "catalog:"
} }
} }
...@@ -36,8 +36,7 @@ ...@@ -36,8 +36,7 @@
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
"test:coverage": "vitest run --coverage", "test:coverage": "vitest run --coverage",
"test:coverage:ui": "vitest --ui --coverage", "test:coverage:ui": "vitest --ui --coverage"
"prepare": "husky"
}, },
"keywords": [ "keywords": [
"figma", "figma",
...@@ -61,20 +60,21 @@ ...@@ -61,20 +60,21 @@
"author": "", "author": "",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@langchain/core": "^1.1.17", "@langchain/core": "catalog:",
"@langchain/langgraph": "^1.1.2", "@langchain/langgraph": "catalog:",
"@langchain/langgraph-checkpoint-sqlite": "^1.0.0", "@langchain/langgraph-checkpoint-sqlite": "catalog:",
"@langchain/openai": "^1.2.3", "@langchain/openai": "catalog:",
"@types/pixelmatch": "^5.2.6", "@types/pixelmatch": "catalog:",
"axios": "^1.13.2", "axios": "catalog:",
"@coderio/ai-client": "workspace:*", "@coderio/ai-client": "workspace:*",
"better-sqlite3": "^11.10.0", "@coderio/shared": "workspace:*",
"chalk": "^5.4.1", "better-sqlite3": "catalog:",
"commander": "^12.1.0", "chalk": "catalog:",
"evoltagent": "1.1.5", "commander": "catalog:",
"js-yaml": "^4.1.1", "evoltagent": "catalog:",
"pixelmatch": "^7.1.0", "js-yaml": "catalog:",
"prompts": "^2.4.2" "pixelmatch": "catalog:",
"prompts": "catalog:"
}, },
"peerDependencies": { "peerDependencies": {
"playwright": "^1.57.0", "playwright": "^1.57.0",
...@@ -89,19 +89,19 @@ ...@@ -89,19 +89,19 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "catalog:",
"@types/node": "^22.10.2", "@types/node": "catalog:",
"@types/prompts": "^2.4.9", "@types/prompts": "catalog:",
"@vitest/coverage-v8": "^2.1.9", "@vitest/coverage-v8": "catalog:",
"eslint": "^9.17.0", "eslint": "catalog:",
"husky": "^9.1.7", "husky": "catalog:",
"lint-staged": "^16.2.7", "lint-staged": "catalog:",
"prettier": "^3.4.2", "prettier": "catalog:",
"tsup": "^8.3.5", "tsup": "catalog:",
"tsx": "^4.21.0", "tsx": "catalog:",
"typescript": "^5.7.2", "typescript": "catalog:",
"typescript-eslint": "^8.18.1", "typescript-eslint": "catalog:",
"vitest": "^2.1.9" "vitest": "catalog:"
}, },
"engines": { "engines": {
"node": ">=18.0.0 <25.0.0" "node": ">=18.0.0 <25.0.0"
......
...@@ -7,19 +7,8 @@ ...@@ -7,19 +7,8 @@
/* URL and File Information */ /* URL and File Information */
/** // FigmaUrlInfo 现统一定义于 @coderio/shared(见 packages/shared);此处再导出以兼容内部引用。
* Parsed Figma URL information export type { FigmaUrlInfo } from '@coderio/shared';
*/
export interface FigmaUrlInfo {
/** The ID of the Figma file */
fileId: string | null;
/** The name of the Figma file */
name: string;
/** The ID of the Figma node */
nodeId: string | null;
/** The name of the project */
projectName: string | null;
}
/* Color and Visual Properties */ /* Color and Visual Properties */
......
import { FigmaUrlInfo } from '../types/figma-types'; // `parseFigmaUrl` / `FigmaUrlInfo` 现统一定义于 @coderio/shared(前端与后端共享的单一来源,
// 且不依赖引擎原生模块)。此处再导出以兼容 coderio 内部 34 处相对引用与公共 API。
/** export { parseFigmaUrl, type FigmaUrlInfo } from '@coderio/shared';
* Parse Figma URL and extract fileId, name, and nodeId in one pass
* @param url - Figma URL to parse
* @returns Object containing fileId, name, and nodeId
* @example
* parseFigmaUrl('https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495')
* // Returns: { fileId: 'aONcu8L82l1PdcT304Q8Za', name: 'intern', nodeId: '0-495' }
*/
export const parseFigmaUrl = (url: string): FigmaUrlInfo => {
let fileId: string | null = null;
let name = 'untitled';
let nodeId: string | null = null;
try {
const urlObj = new URL(decodeURIComponent(url));
const pathParts = urlObj.pathname.split('/').filter(Boolean);
if (pathParts.length >= 3) {
fileId = pathParts[pathParts.length - 2] || null;
const fileName = pathParts[pathParts.length - 1];
name = slugifyFigmaName(fileName ?? 'untitled');
name = name.length > 20 ? name.substring(0, 20) : name;
}
nodeId = urlObj.searchParams.get('node-id') || null;
nodeId = nodeId ? nodeId.replace(/-/g, ':') : null;
} catch {}
if (!fileId || !nodeId) {
throw new Error('Invalid Figma URL');
}
return { fileId, name, nodeId, projectName: `${name}_${nodeId.replace(/:/g, '_')}` };
};
/**
* Turn a Figma file name into a filesystem / package-safe slug.
*
* The Figma URL is already percent-decoded once by `new URL(decodeURIComponent(url))`,
* but some URLs are double-encoded (e.g. `%25E3%2580%2590` instead of `%E3%80%90`).
* We fully decode the name first, then keep unicode letters/digits and replace every
* other character (spaces, brackets, `%`, etc.) with a single underscore.
*/
function slugifyFigmaName(raw: string): string {
let decoded = raw;
try {
let prev: string;
do {
prev = decoded;
decoded = decodeURIComponent(prev);
} while (decoded !== prev);
} catch {
/* leave as the last successfully decoded value */
}
const slug = decoded
.normalize('NFKC')
.replace(/[^\p{L}\p{N}]+/gu, '_')
.replace(/^_+|_+$/g, '')
.toLowerCase();
return slug || 'untitled';
}
{
"name": "@coderio/shared",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"zod": "catalog:"
},
"devDependencies": {
"typescript": "catalog:"
}
}
export * from './url-parser.js';
export * from './schemas.js';
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>;
/**
* Parsed Figma URL information.
*
* Shared between the orchestration backend (apps/server) and the web UI so both
* validate Figma links with the exact same logic. The implementation is pure
* (only `URL` / `decodeURIComponent`) and has no dependency on the `coderio`
* engine, so it is safe to bundle into the browser without leaking native deps.
*/
export interface FigmaUrlInfo {
/** The ID of the Figma file */
fileId: string | null;
/** The name of the Figma file */
name: string;
/** The ID of the Figma node */
nodeId: string | null;
/** The name of the project */
projectName: string | null;
}
/**
* Parse Figma URL and extract fileId, name, and nodeId in one pass.
* @example
* parseFigmaUrl('https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495')
* // Returns: { fileId: 'aONcu8L82l1PdcT304Q8Za', name: 'intern', nodeId: '0-495' }
*/
export const parseFigmaUrl = (url: string): FigmaUrlInfo => {
let fileId: string | null = null;
let name = 'untitled';
let nodeId: string | null = null;
try {
const urlObj = new URL(decodeURIComponent(url));
const pathParts = urlObj.pathname.split('/').filter(Boolean);
if (pathParts.length >= 3) {
fileId = pathParts[pathParts.length - 2] || null;
const fileName = pathParts[pathParts.length - 1];
name = slugifyFigmaName(fileName ?? 'untitled');
name = name.length > 20 ? name.substring(0, 20) : name;
}
nodeId = urlObj.searchParams.get('node-id') || null;
nodeId = nodeId ? nodeId.replace(/-/g, ':') : null;
} catch {}
if (!fileId || !nodeId) {
throw new Error('Invalid Figma URL');
}
return { fileId, name, nodeId, projectName: `${name}_${nodeId.replace(/:/g, '_')}` };
};
/**
* Turn a Figma file name into a filesystem / package-safe slug.
*
* The Figma URL is already percent-decoded once by `new URL(decodeURIComponent(url))`,
* but some URLs are double-encoded (e.g. `%25E3%2580%2590` instead of `%E3%80%90`).
* We fully decode the name first, then keep unicode letters/digits and replace every
* other character (spaces, brackets, `%`, etc.) with a single underscore.
*/
function slugifyFigmaName(raw: string): string {
let decoded = raw;
try {
let prev: string;
do {
prev = decoded;
decoded = decodeURIComponent(prev);
} while (decoded !== prev);
} catch {
/* leave as the last successfully decoded value */
}
const slug = decoded
.normalize('NFKC')
.replace(/[^\p{L}\p{N}]+/gu, '_')
.replace(/^_+|_+$/g, '')
.toLowerCase();
return slug || 'untitled';
}
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022", "DOM"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": false,
"sourceMap": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
This diff could not be displayed because it is too large.
packages: packages:
- 'packages/*' - 'packages/*'
- 'apps/*' - 'apps/*'
# pnpm catalog:整个 workspace 所有「外部依赖」的单一版本源(要求 pnpm >= 9)。
# 各 package.json 用 "catalog:" 引用,统一升级只需改这里;
# 只有内部包互引(如 @coderio/ai-client、coderio)才用 "workspace:*"。
catalog:
# ── 语言 / 运行时基础 ──
typescript: ^5.7.2
'@types/node': ^22.10.2
tsx: ^4.21.0
zod: ^3.23.8
# ── web 运行时(React / UI 组件库)──
react: ^18.3.1
'react-dom': ^18.3.1
'@types/react': ^18.3.12
'@types/react-dom': ^18.3.1
'react-router-dom': ^6.28.0
'@radix-ui/react-label': ^2.1.1
'@radix-ui/react-select': ^2.1.4
'@radix-ui/react-slot': ^1.1.1
'@radix-ui/react-tabs': ^1.1.21
'class-variance-authority': ^0.7.1
clsx: ^2.1.1
'tailwind-merge': ^2.5.5
'lucide-react': ^0.460.0
sonner: ^1.7.0
# ── web 构建链 ──
vite: ^5.4.11
'@vitejs/plugin-react': ^4.3.4
tailwindcss: ^3.4.15
autoprefixer: ^10.4.20
postcss: ^8.4.49
'tailwindcss-animate': ^1.0.7
# ── AI / LangChain 链(coderio + ai-client 共享,版本已统一)──
'@langchain/core': ^1.1.19
'@langchain/openai': ^1.2.4
'@langchain/langgraph': ^1.1.2
'@langchain/langgraph-checkpoint-sqlite': ^1.0.0
# ── coderio 引擎运行时 ──
axios: ^1.13.2
'better-sqlite3': ^11.10.0
chalk: ^5.4.1
commander: ^12.1.0
evoltagent: 1.1.5
'js-yaml': ^4.1.1
pixelmatch: ^7.1.0
prompts: ^2.4.2
# ── coderio 类型 / 构建 / 测试 / 质量工具链 ──
'@types/pixelmatch': ^5.2.6
'@types/js-yaml': ^4.0.9
'@types/prompts': ^2.4.9
tsup: ^8.3.5
vitest: ^2.1.9
'@vitest/coverage-v8': ^2.1.9
eslint: ^9.17.0
'typescript-eslint': ^8.18.1
prettier: ^3.4.2
husky: ^9.1.7
'lint-staged': ^16.2.7
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!