Files
persionalBrand/apps/taro/test/browser/template-preview-media.spec.ts
T
que01 4f0b50c7f1 fix: 收口模板契约与安全门禁
统一模板包 visual 契约并补齐完成证据;修复 release 版本一致性、管理员 token 撤销、CORS 与默认品牌配置;收敛依赖安全风险并完成全量回归验证。
2026-10-18 22:05:31 +08:00

263 lines
9.8 KiB
TypeScript

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;
packageKey: string;
version: string;
displayName: string;
status: "imported";
manifestSnapshot: PackedManifest;
importedBy: { displayName: string };
validationReport: Record<string, unknown>;
manifestSummary: { supportedIndustryTemplates: string[] };
artifactPath: string;
archiveChecksum: string;
contentChecksum: string;
};
type PreviewWorkspace = {
offerings: unknown[];
trustItems: unknown[];
inquiryForms: unknown[];
trustPresentation: Record<string, unknown>;
};
type PreviewBundle = {
preview: Record<string, unknown> & { 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: "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<string>((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}`,
packageKey: manifest.packageKey,
version: manifest.version,
displayName: manifest.displayName,
status: "imported",
manifestSnapshot: manifest,
importedBy: { displayName: "模板管理员" },
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<string, unknown>, 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.addInitScript(() => {
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
});
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 (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/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 });
await page.screenshot({
path: path.join(
evidenceDirectory,
`${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}.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.screenshot({
path: path.join(
evidenceDirectory,
`empty-${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}.png`,
),
});
}
await page.unroute("**/api/**");
});
}
});