import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { test, expect, type Page } from "@playwright/test"; type PackedManifest = { packageKey: string; version: string; displayName: string; supportedIndustryTemplates: string[]; }; type PackedChecksums = { contentChecksum: string; }; type PreviewVersion = { id: string; templatePackageId: string; packageKey: string; version: string; displayName: string; status: "imported"; manifestSnapshot: PackedManifest; importedBy: { id: string; username: string; displayName: string }; importedAt: string; updatedAt: string; validationReport: Record; manifestSummary: { supportedIndustryTemplates: string[] }; artifactPath: string; archiveChecksum: string; contentChecksum: string; }; type PreviewWorkspace = { offerings: unknown[]; trustItems: unknown[]; inquiryForms: unknown[]; trustPresentation: Record; }; type PreviewBundle = { preview: Record & { workspace: PreviewWorkspace }; version: PreviewVersion; }; type MediaCase = { packageKey: string; industry: string; founder: string; }; const mediaCases: MediaCase[] = [ { packageKey: "acheng-campus-food", industry: "food", founder: "阿成" }, { packageKey: "atelier-solopreneur", industry: "personal", founder: "林予 · 示例主理人" }, { packageKey: "linjing-editorial", industry: "doors", founder: "林叙安 (Lin XUAN)" }, ]; async function buildPreviewFixture(mediaCase: MediaCase) { // 使用真实 template:pack 产物和 API preview service,避免在浏览器测试里手写演示数据。 const output = await new Promise((resolve, reject) => { const temporary = path.join( os.tmpdir(), `template-preview-media-${mediaCase.packageKey}-${mediaCase.industry}`, ); try { rmSync(temporary, { recursive: true, force: true }); mkdirSync(temporary, { recursive: true }); execFileSync( process.execPath, [ path.resolve(process.cwd(), "../../scripts/template-pack.cjs"), "--template", mediaCase.packageKey, "--out", temporary, ], { cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" }, ); const archive = readdirSync(temporary).find((file) => file.endsWith(".tar.gz")); assert.ok(archive); const root = path.join(temporary, archive.slice(0, -7)); const manifest = JSON.parse( readFileSync(path.join(root, "template.json"), "utf8"), ) as PackedManifest; const checksums = JSON.parse( readFileSync(path.join(root, "checksums.json"), "utf8"), ) as PackedChecksums; const archivePath = path.join(temporary, archive); const version: PreviewVersion = { id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`, templatePackageId: `preview-media-package-${mediaCase.packageKey}`, packageKey: manifest.packageKey, version: manifest.version, displayName: manifest.displayName, status: "imported", manifestSnapshot: manifest, importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" }, importedAt: "2026-10-21T00:00:00.000Z", updatedAt: "2026-10-21T00:00:00.000Z", validationReport: {}, manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates }, artifactPath: archivePath, archiveChecksum: "", contentChecksum: checksums.contentChecksum, }; const serialized = JSON.stringify({ version, industry: mediaCase.industry }); const stdout = execFileSync( process.execPath, [ "--input-type=module", "-e", ` import 'reflect-metadata'; import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { AdminTemplatePreviewAssetsService } from './dist/modules/admin/admin-template-preview-assets.service.js'; import { AdminTemplatePreviewService } from './dist/modules/admin/admin-template-preview.service.js'; let input = ''; for await (const chunk of process.stdin) input += chunk; const { version, industry } = JSON.parse(input); version.archiveChecksum = createHash('sha256').update(readFileSync(version.artifactPath)).digest('hex'); const service = new AdminTemplatePreviewService( { templatePackageVersion: { findUnique: async () => version }, templatePackageAuditLog: { create: async () => ({}) }, }, new AdminTemplatePreviewAssetsService(), ); process.stdout.write(JSON.stringify(await service.preview(version.id, industry, 'visual-matrix-admin'))); `, ], { cwd: path.resolve("../api"), input: serialized, encoding: "utf8", maxBuffer: 32 * 1024 * 1024, }, ); resolve(JSON.stringify({ preview: JSON.parse(stdout) as Record, version })); } catch (error) { reject(error instanceof Error ? error : new Error(String(error))); } finally { rmSync(temporary, { recursive: true, force: true }); } }); return JSON.parse(output) as PreviewBundle; } async function selectPreviewIndustry(page: Page, industry: string) { await page.getByLabel("预览行业").click(); await page .locator(".ant-select-item-option-content") .getByText(industry, { exact: true }) .click(); } test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({ page }) => { const evidenceDirectory = process.env.TEMPLATE_PREVIEW_VISUAL_EVIDENCE; let sequence = 0; for (const mediaCase of mediaCases) { sequence += 1; await test.step(`${mediaCase.packageKey}/${mediaCase.industry}`, async () => { const { preview, version } = await buildPreviewFixture(mediaCase); assert.ok(version); await page.route("**/api/**", (route) => { const url = new URL(route.request().url()); if (url.pathname.endsWith("/admin/session/current")) return route.fulfill({ json: { authenticated: true, displayName: "模板管理员", role: "owner", mustChangePassword: false, platformTemplateRole: "template_admin", }, }); return route.fulfill({ json: {} }); }); const emptyPreview = structuredClone(preview); emptyPreview.workspace.offerings = []; emptyPreview.workspace.trustItems = []; emptyPreview.workspace.inquiryForms = []; emptyPreview.workspace.trustPresentation = {}; let attempts = 0; let serveEmptyPreview = false; const writes: string[] = []; await page.route("**/api/**", async (route) => { const url = new URL(route.request().url()); if (url.pathname.endsWith("/admin/session/current")) return route.fulfill({ json: { authenticated: true, displayName: "模板管理员", role: "owner", mustChangePassword: false, platformTemplateRole: "template_admin", }, }); if (route.request().method() !== "GET") writes.push(url.pathname); if (url.pathname.endsWith("/preview")) { attempts += 1; return route.fulfill({ status: attempts === 1 ? 400 : 200, json: attempts === 1 ? { error: { code: "HTTP_400", message: "预览测试失败,请重试" } } : serveEmptyPreview ? emptyPreview : preview, }); } if (url.pathname.endsWith("/admin/templates")) return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1, }, }); if (url.pathname.endsWith("/admin/template-operations/failures")) return route.fulfill({ json: { since: "2026-09-21T00:00:00.000Z", until: "2026-10-21T00:00:00.000Z", days: 30, backfilled: true, failures: [], }, }); if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] }); return route.fulfill({ json: { name: "测试工作区" } }); }); await page.goto(`${process.env.ADMIN_URL || "http://localhost:3000"}/admin/templates`); const modal = page.getByRole("dialog"); await page.getByRole("button", { name: /预览/ }).click(); await expect(modal.getByText("预览测试失败,请重试")).toBeVisible(); await modal.getByRole("button", { name: /重试/ }).click(); await expect(modal.locator(".component-template-preview")).toContainText(mediaCase.founder); if (mediaCase.industry !== version.manifestSummary.supportedIndustryTemplates[0]) { await selectPreviewIndustry(page, mediaCase.industry); } // 覆盖此前疏漏:不仅检查数据存在,还要证明包内媒体渲染为可显示图像。 const images = modal.locator('.component-template-preview img[src^="data:image/"]'); await expect(images.first()).toBeVisible(); const imageCount = await images.count(); expect(imageCount).toBeGreaterThan(0); await expect .poll(() => Promise.all( Array.from({ length: imageCount }, (_, index) => images.nth(index).evaluate((image: HTMLImageElement) => image.naturalWidth), ), ).then((values) => Math.min(...values)), ) .toBeGreaterThan(0); // 独立 fixture 与补齐后的 legacy sample 都不应显示资源缺失。 await expect(modal.getByText("内容缺失", { exact: true })).toHaveCount(0); expect(writes).toEqual([]); if (evidenceDirectory) { mkdirSync(evidenceDirectory, { recursive: true }); // 多屏宽证据:320/375/390 均验证实际渲染,而不是只检查 DOM 存在。 for (const viewportWidth of [320, 375, 390]) { await page.setViewportSize({ width: viewportWidth, height: 812 }); await expect(modal.locator(".component-template-preview")).toBeVisible(); await page.screenshot({ path: path.join( evidenceDirectory, `${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}-${viewportWidth}.png`, ), }); } } // 清空业务记录后重新打开真实包预览,验证空态不是仅在源码中存在。 serveEmptyPreview = true; await modal.getByRole("button", { name: "关闭" }).click(); await expect(modal).toBeHidden(); await page.getByRole("button", { name: /预览/ }).click(); await expect(modal.locator(".component-template-preview .runtime-state")).toContainText( /正在整理中/, ); if (evidenceDirectory) { await page.setViewportSize({ width: 375, height: 812 }); await page.screenshot({ path: path.join( evidenceDirectory, `empty-${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}.png`, ), }); } await page.unroute("**/api/**"); }); } });