import type { APIRoute } from 'astro'; import { z } from 'zod'; import { guardWrite } from '@/lib/auth'; import { importEntities } from '@/lib/repo'; import { chipSchema, deviceSchema } from '@/lib/schema'; const MAX_BYTES = 20 * 1024 * 1024; const MAX_ITEMS = 5000; const envelopeSchema = z.object({ formatVersion: z.literal(1), devices: z.array(z.unknown()).default([]), chips: z.array(z.unknown()).default([]), }); async function readPayload(request: Request): Promise { const contentType = request.headers.get('content-type') ?? ''; if (contentType.includes('multipart/form-data')) { const form = await request.formData(); const file = form.get('file'); if (file instanceof File) { if (file.size > MAX_BYTES) throw new Error('文件不能超过 20MB'); return JSON.parse(await file.text()) as unknown; } const text = String(form.get('json') ?? ''); if (!text.trim()) throw new Error('请上传文件或粘贴 JSON'); return JSON.parse(text) as unknown; } const text = await request.text(); if (text.length > MAX_BYTES) throw new Error('请求体不能超过 20MB'); if (!text.trim()) throw new Error('请求体为空'); return JSON.parse(text) as unknown; } export const POST: APIRoute = async ({ request, cookies }) => { const denied = await guardWrite(request, cookies); if (denied) return denied; let payload: unknown; try { payload = await readPayload(request); } catch (error) { return Response.json( { error: `无法读取导入内容:${error instanceof Error ? error.message : '解析失败'}` }, { status: 400 }, ); } const envelope = envelopeSchema.safeParse(payload); if (!envelope.success) { return Response.json( { error: '导入文件格式不正确,需要 { formatVersion: 1, devices: [...], chips: [...] }', issues: envelope.error.issues.map((issue) => ({ path: issue.path.join('.'), message: issue.message, })), }, { status: 400 }, ); } const { devices: rawDevices, chips: rawChips } = envelope.data; if (rawDevices.length === 0 && rawChips.length === 0) { return Response.json({ error: '没有可导入的设备或芯片' }, { status: 400 }); } if (rawDevices.length > MAX_ITEMS || rawChips.length > MAX_ITEMS) { return Response.json({ error: `单次最多导入 ${MAX_ITEMS} 条` }, { status: 400 }); } const issues: { path: string; message: string }[] = []; const devices = []; for (const [index, item] of rawDevices.entries()) { const parsed = deviceSchema.safeParse(item); if (parsed.success) { devices.push(parsed.data); } else { for (const issue of parsed.error.issues) { issues.push({ path: `devices[${index}].${issue.path.join('.')}`, message: issue.message, }); } } } const chips = []; for (const [index, item] of rawChips.entries()) { const parsed = chipSchema.safeParse(item); if (parsed.success) { chips.push(parsed.data); } else { for (const issue of parsed.error.issues) { issues.push({ path: `chips[${index}].${issue.path.join('.')}`, message: issue.message, }); } } } if (issues.length > 0) { return Response.json( { error: `导入数据校验失败(${issues.length} 处)`, issues: issues.slice(0, 200) }, { status: 400 }, ); } const counts = importEntities(devices, chips); return Response.json({ ok: true, counts }); };