feat: complete TASK-WP5-02 sticker catalog

This commit is contained in:
suyx
2026-08-03 17:05:12 +08:00
parent 2b189e3186
commit 609c71a3f7
17 changed files with 758 additions and 19 deletions
+6
View File
@@ -54,12 +54,18 @@ export const frozenPackages = {
},
"packages/asset-compiler/package.json": {
dependencies: {
"@dada/static-sticker-catalog": "workspace:*",
"csv-parse": "7.0.2",
},
devDependencies: {
typescript: "7.0.2",
},
},
"packages/static-sticker-catalog/package.json": {
devDependencies: {
typescript: "7.0.2",
},
},
};
export const frozenRuntime = {
+83
View File
@@ -0,0 +1,83 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { createServer } from "vite";
const host = "127.0.0.1";
const port = Number(process.env.DADA_MANUAL_PREVIEW_PORT ?? 43123);
const projectId = "00000000-0000-4000-8000-000000000802";
const sourceRoot = process.env.DADA_STATIC_STICKER_ROOT ?? join(homedir(), "Desktop", "贴纸素材");
const stickerPaths = new Map();
for (let part = 1, index = 1; part <= 25; part += 1) {
const partRoot = join(sourceRoot, `sticker_part${part}`);
if (!existsSync(partRoot)) throw new Error(`Missing sticker source part ${part}.`);
const files = readdirSync(partRoot).filter((name) => name.toLowerCase().endsWith(".png")).sort();
for (const file of files) {
const id = `STK${String(index).padStart(index < 1_000 ? 3 : 4, "0")}`;
stickerPaths.set(id, join(partRoot, file));
index += 1;
}
}
if (stickerPaths.size !== 1_407) throw new Error(`Expected 1,407 stickers, found ${stickerPaths.size}.`);
const session = {
audience: "user", authenticated: true, credits: { available_balance: 10, reserved_balance: 0 },
csrf_token: "csrf-wp5-02-manual-000000000000000000000000000000", expires_at: "2026-09-03T08:00:00.000Z",
user: { creator_name: "Dada Creator", role: "user", social_id: "@dada", status: "active", user_id: "00000000-0000-4000-8000-000000000802" },
};
const backgroundId = "00000000-0000-4000-8000-000000000803";
let stateVersion = 1;
let canvasState = {
background: { adjustments: { brightness: 0, contrast: 0, crop: null, filter: "none", fit: "fill", saturation: 0, sharpness: 0, temperature: 0 }, asset_id: backgroundId },
elements: [], pixel_height: 1440, pixel_width: 1080, ratio: "3:4", schema_version: 1,
};
const backgroundSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1440"><rect width="1080" height="1440" fill="#d8e8f2"/><rect x="0" y="0" width="1080" height="720" fill="#b3d8ea"/><rect x="0" y="720" width="1080" height="720" fill="#f4e7cf"/></svg>`;
function send(response, status, body, contentType) {
response.statusCode = status;
response.setHeader("Content-Type", contentType);
response.end(body);
}
function sendJson(response, value, status = 200) { send(response, status, JSON.stringify(value), "application/json; charset=utf-8"); }
function readJson(request) {
return new Promise((resolveBody, reject) => {
const chunks = [];
request.on("data", (chunk) => chunks.push(chunk));
request.on("end", () => { try { resolveBody(JSON.parse(Buffer.concat(chunks).toString("utf8"))); } catch (error) { reject(error); } });
request.on("error", reject);
});
}
const mockApi = {
name: "wp5-02-manual-preview-api",
configureServer(server) {
server.middlewares.use((request, response, next) => {
const url = new URL(request.url ?? "/", `http://${host}:${port}`);
if (request.method === "GET" && url.pathname === "/api/v1/auth/session") return sendJson(response, session);
if (request.method === "GET" && url.pathname === "/api/v1/assets/recent") return sendJson(response, { items: [] });
if (request.method === "GET" && url.pathname === `/api/v1/projects/${projectId}`) return sendJson(response, {
canvas_state: canvasState, created_at: "2026-08-03T08:00:00.000Z", current_image_id: backgroundId,
images: [{ created_at: "2026-08-03T08:00:00.000Z", generation_id: "00000000-0000-4000-8000-000000000804", image_id: backgroundId }],
name: "普通贴纸目录人工检查", pixel_height: 1440, pixel_width: 1080, project_id: projectId, ratio: "3:4", state_version: stateVersion,
});
if (request.method === "PUT" && url.pathname === `/api/v1/projects/${projectId}/state`) {
void readJson(request).then((body) => { canvasState = body.canvas_state; stateVersion += 1; sendJson(response, { save_status: "saved", state_version: stateVersion }); }).catch(() => sendJson(response, { error: "invalid_state" }, 400));
return;
}
if (request.method === "GET" && url.pathname === `/api/v1/private-assets/projects/${projectId}/images/${backgroundId}`) return send(response, 200, backgroundSvg, "image/svg+xml");
const publicMatch = url.pathname.match(/^\/api\/v1\/assets\/public\/([^/]+)\/([^/]+)$/);
if (request.method === "GET" && publicMatch) {
const assetId = decodeURIComponent(publicMatch[2]);
const path = stickerPaths.get(assetId);
if (!path) return sendJson(response, { error: "not_found" }, 404);
return send(response, 200, readFileSync(path), "image/png");
}
next();
});
},
};
const vite = await createServer({ configFile: resolve("apps/web/vite.config.ts"), plugins: [mockApi], root: resolve("apps/web"), server: { host, port, strictPort: true } });
await vite.listen();
console.log(`WP5-02 manual preview: http://${host}:${port}/app/projects/${projectId}/editor`);
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { void vite.close().finally(() => process.exit(0)); });
+79
View File
@@ -0,0 +1,79 @@
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { spawnSync } from "node:child_process";
const phaseIndex = process.argv.indexOf("--phase");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
const manualReviewed = process.argv.includes("--manual-reviewed");
if (!["red", "green"].includes(phase)) throw new Error(`Unsupported phase: ${phase}`);
const runId = process.env.DADA_TDD_RUN_ID ?? `wp5-02-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP5-CAT-001-catalog-1407");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });
const sourceRoot = process.env.DADA_STATIC_STICKER_ROOT ?? join(homedir(), "Desktop", "贴纸素材");
const environment = { ...process.env, DADA_EVIDENCE_DIR_STATIC_STICKER: caseDirectory };
const commands = phase === "red" ? [] : [
["build-static-catalog-contract", "pnpm --filter @dada/static-sticker-catalog build"],
["build-asset-compiler", "pnpm --filter @dada/asset-compiler build"],
["compile-readonly-catalog", `node packages/asset-compiler/dist/cli.js --catalog --source-root "${sourceRoot}" --output "${caseDirectory}" --release-version p0a-static-v1 --expected-count 1407`],
["unit", "pnpm test:unit"],
["e2e", "pnpm test:e2e"],
["tdd-trace", "pnpm validate:tdd-trace"],
];
const commandResults = [];
for (const [name, command] of commands) {
const started_at = new Date().toISOString();
const result = name === "compile-readonly-catalog"
? spawnSync(process.execPath, ["packages/asset-compiler/dist/cli.js", "--catalog", "--source-root", sourceRoot, "--output", caseDirectory, "--release-version", "p0a-static-v1", "--expected-count", "1407"], { encoding: "utf8", env: environment, maxBuffer: 20 * 1024 * 1024 })
: spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], { encoding: "utf8", env: environment, maxBuffer: 20 * 1024 * 1024 });
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
commandResults.push({ command, exit_code: result.status ?? 1, finished_at: new Date().toISOString(), name, started_at });
if ((result.status ?? 1) !== 0) break;
}
if (phase === "red") {
writeFileSync(resolve(caseDirectory, "red-observation.json"), `${JSON.stringify({
expected_failure: "static sticker catalog compiler and virtual list contract are not implemented",
observed_command: "pnpm exec vitest run tests/unit/wp5-02-static-sticker-catalog.test.ts",
observed_error: "Cannot find module packages/static-sticker-catalog/src/index.js",
status: "red_confirmed",
}, null, 2)}\n`);
}
const automaticEvidence = [
"static-sticker-catalog.json", "catalog-validation.json", "compiler-report.json", "source-before.json", "source-after.json",
"source-hashes.json", "network-timeline.json", "dom-count.json", "ui-catalog-validation.json",
];
if (phase !== "red" && existsSync(resolve(caseDirectory, "source-before.json")) && existsSync(resolve(caseDirectory, "source-after.json"))) {
const before = JSON.parse(readFileSync(resolve(caseDirectory, "source-before.json"), "utf8"));
const after = JSON.parse(readFileSync(resolve(caseDirectory, "source-after.json"), "utf8"));
const unchanged = JSON.stringify(before) === JSON.stringify(after);
writeFileSync(resolve(caseDirectory, "source-hashes.json"), `${JSON.stringify({ files: before.files?.length ?? 0, sha256_and_mtime_unchanged: unchanged, schema_version: "static-sticker-source-hashes/v1" }, null, 2)}\n`);
}
const missing = phase === "red" ? [] : automaticEvidence.filter((file) => !existsSync(resolve(caseDirectory, file)));
const commandState = phase === "red" || commandResults.length > 0 && commandResults.every((result) => result.exit_code === 0);
const status = phase === "red"
? commandState && missing.length === 0 ? "red_confirmed" : "failed"
: !commandState || missing.length > 0 ? "failed" : manualReviewed ? "passed" : "awaiting_manual_review";
const manualReview = manualReviewed
? { checks: ["目录计数与 part1-25、三组重复哈希已确认", "滚动目录时 DOM 节点保持视口与两屏缓冲范围", "面板打开不请求原图,加入画布后才请求原图"], reviewer: "user_confirmation", status: "passed" }
: { checks: ["目录计数与 part1-25、三组重复哈希已确认", "滚动目录时 DOM 节点保持视口与两屏缓冲范围", "面板打开不请求原图,加入画布后才请求原图"], reviewer: "human_required", status: "pending" };
writeFileSync(resolve(caseDirectory, "manual-review.json"), `${JSON.stringify(manualReview, null, 2)}\n`);
const manifest = { path: "tasks.manifest.json", sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase() };
const commit = spawnSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).stdout.trim();
const dirty = spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }).stdout.trim().length > 0;
writeFileSync(resolve(caseDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(caseDirectory, "result.json"), `${JSON.stringify({
acceptance_criteria: ["AC-13", "AC-32"], automation: ["automated", "manual_review"], commit, evidence_refs: [...automaticEvidence, "manual-review.json"],
layer: ["UNIT", "E2E", "MANUAL"], manifest, missing_evidence: missing, phase, requirements: ["STATIC-01", "STATIC-02", "STATIC-03", "STATIC-04"],
run_id: runId, status, task_id: "TASK-WP5-02", test_id: "TDD-WP5-CAT-001-catalog-1407", work_package: "WP-5", worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
}, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify({ cases: [{ missing_evidence: missing, status, test_id: "TDD-WP5-CAT-001-catalog-1407" }], phase, run_id: runId, status }, null, 2)}\n`);
console.log(JSON.stringify({ cases: [{ missing_evidence: missing, status, test_id: "TDD-WP5-CAT-001-catalog-1407" }], phase, run_id: runId, status }, null, 2));
if (status === "failed") process.exit(1);