import { app, BrowserWindow, ipcMain } from "electron"; import crypto from "node:crypto"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { CH, PLAN, buildMacFeed, buildWinFeed, compareVersions, parseLatest, summarize, type Artifact, type Check, type Snapshot, type StepResult, } from "../shared/ipc"; app.setName("Release Pipeline Lab"); const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1"; const isShots = process.argv.includes("--shots"); const tempData = isSmoke || isShots ? path.join(os.tmpdir(), `pipe57-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); const appRoot = app.getAppPath(); const artifactDir = path.join(appRoot, "fixtures", "artifacts"); const outDir = path.join(app.getPath("userData"), "release-out"); const reportPath = path.join(outDir, "report.json"); const currentVersion = "1.0.0"; const targetVersion = "1.2.0"; let win: BrowserWindow | null = null; let events: Array<{ at: number; kind: string; detail: string }> = []; let steps: StepResult[] = []; let artifacts: Artifact[] = []; let feedPreview = ""; let injectFailure = false; function log(kind: string, detail: string): void { events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40); broadcast(); } function broadcast(): void { if (win && !win.isDestroyed()) { win.webContents.send("pipeline:event", { at: Date.now() }); } } function sha256(buffer: Buffer): string { return crypto.createHash("sha256").update(buffer).digest("hex"); } function loadArtifacts(): Artifact[] { return ["App-1.2.0.dmg", "App-1.2.0.zip", "RELEASES"].map((name) => { const buffer = fsSync.readFileSync(path.join(artifactDir, name)); return { name, bytes: buffer.byteLength, sha256: sha256(buffer) }; }); } function resetSteps(): void { steps = PLAN.map((step) => ({ id: step.id, title: step.title, status: "pending", ms: 0, log: "", })); } function runStep(id: string, work: () => string): boolean { const step = steps.find((row) => row.id === id); if (!step) return false; step.status = "running"; const start = performance.now(); try { const detail = work(); step.status = "pass"; step.log = detail; step.ms = Math.round((performance.now() - start) * 100) / 100; log(id, detail); return true; } catch (error) { step.status = "fail"; step.log = error instanceof Error ? error.message : String(error); step.ms = Math.round((performance.now() - start) * 100) / 100; log(`${id}-fail`, step.log); return false; } } function runPipeline(): void { resetSteps(); artifacts = loadArtifacts(); feedPreview = ""; fsSync.mkdirSync(outDir, { recursive: true }); fsSync.rmSync(reportPath, { force: true }); if ( !runStep("preflight", () => { if (!process.versions.electron.startsWith("45.")) { throw new Error("BAD_ELECTRON_VERSION"); } if (!process.versions.node.startsWith("24.")) { throw new Error("BAD_NODE_VERSION"); } if (artifacts.length !== 3) throw new Error("MISSING_ARTIFACTS"); return `${artifacts.length} artifacts · electron ${process.versions.electron}`; }) ) { return; } if ( !runStep("checksum", () => { const empty = artifacts.filter((row) => row.sha256.length !== 64); if (empty.length) throw new Error("BAD_HASH"); return artifacts .map((row) => `${row.name}:${row.sha256.slice(0, 8)}`) .join(" "); }) ) { return; } if ( !runStep("metadata", () => { if (injectFailure) throw new Error("INJECTED_FAILURE"); const zip = artifacts.find((row) => row.name.endsWith(".zip")); if (!zip) throw new Error("MISSING_ZIP"); feedPreview = buildMacFeed({ version: targetVersion, zipName: zip.name, sha256: zip.sha256, notes: "修复崩溃;改进发布流程。", }); const win = buildWinFeed({ version: targetVersion, sha1: "a".repeat(40), size: 123456, }); fsSync.writeFileSync(path.join(outDir, "releases.json"), feedPreview); fsSync.writeFileSync(path.join(outDir, "RELEASES"), win); return "releases.json + RELEASES"; }) ) { return; } if ( !runStep("feed", () => { const latest = parseLatest(feedPreview); if (compareVersions(latest, currentVersion) <= 0) { throw new Error("NO_UPDATE"); } return `${currentVersion} → ${latest}`; }) ) { return; } runStep("report", () => { const summary = summarize(steps); const report = { targetVersion, currentVersion, generatedAt: new Date().toISOString(), artifacts, steps, feedDecision: "update", summary, }; fsSync.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); return reportPath; }); log("pipeline", `${summarize(steps).passed}/${steps.length} passed`); } function checks(): Check[] { const summary = summarize(steps); let report: { steps?: unknown[]; artifacts?: Array<{ sha256?: string }>; } = {}; try { report = JSON.parse(fsSync.readFileSync(reportPath, "utf8")); } catch { report = {}; } const firstHashes = artifacts.map((row) => row.sha256).join(","); const reloadHashes = artifacts .map((row) => sha256(fsSync.readFileSync(path.join(artifactDir, row.name)))) .join(","); return [ { id: "plan", label: "流水线包含 5 个步骤", pass: PLAN.length === 5 && steps.length === 5, detail: PLAN.map((step) => step.id).join(" → "), }, { id: "artifacts", label: "3 个产物已加载", pass: artifacts.length === 3, detail: String(artifacts.length), }, { id: "hashes", label: "3 个 SHA-256 均为 64 位", pass: artifacts.every((row) => row.sha256.length === 64), detail: String( artifacts.filter((row) => row.sha256.length === 64).length, ), }, { id: "metadata", label: "releases.json 可解析且版本为 1.2.0", pass: (() => { try { return parseLatest(feedPreview) === targetVersion; } catch { return false; } })(), detail: targetVersion, }, { id: "decision", label: "feed 决策为 update", pass: summary.failed === 0 && steps.find((step) => step.id === "feed")?.status === "pass", detail: `${currentVersion} → ${targetVersion}`, }, { id: "report", label: "report.json 已写入", pass: fsSync.existsSync(reportPath), detail: reportPath, }, { id: "report-steps", label: "报告中包含 5 个步骤", pass: Array.isArray(report.steps) && report.steps.length === 5, detail: String(report.steps?.length ?? 0), }, { id: "report-hashes", label: "报告中包含 3 个哈希", pass: Array.isArray(report.artifacts) && report.artifacts.length === 3 && report.artifacts.every((row) => (row.sha256 ?? "").length === 64), detail: String(report.artifacts?.length ?? 0), }, { id: "deterministic", label: "重复计算哈希一致", pass: firstHashes.length > 0 && firstHashes === reloadHashes, detail: "sha256 stable", }, { id: "offline", label: "只做本地计算,不联网、不签名", pass: true, detail: "offline", }, ]; } function snapshot(): Snapshot { const list = checks(); const passed = list.filter((check) => check.pass).length; return { platform: process.platform, electronVersion: process.versions.electron, nodeVersion: process.versions.node, currentVersion, targetVersion, steps: steps.map((step) => ({ ...step })), artifacts: artifacts.map((row) => ({ ...row })), feedPreview, reportPath, reportSummary: summarize(steps), injectFailure, checks: list, score: Math.round((passed / list.length) * 100), events: events.map((row) => ({ ...row })), }; } function resolvePreload(): string { const candidates = [ path.join(__dirname, "preload.cjs"), path.join(__dirname, "../preload/index.cjs"), path.join(__dirname, "preload.js"), ]; return ( candidates.find((candidate) => fsSync.existsSync(candidate)) ?? candidates[0] ?? "" ); } function createWindow(): BrowserWindow { const window = new BrowserWindow({ width: 1100, height: 860, show: false, title: "发布流水线实验室", backgroundColor: "#ffffff", webPreferences: { preload: resolvePreload(), contextIsolation: true, sandbox: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, experimentalFeatures: false, webviewTag: false, spellcheck: false, backgroundThrottling: true, }, }); const contents = window.webContents; contents.setWindowOpenHandler(() => ({ action: "deny" })); contents.on("will-navigate", (event, url) => { if (!url.startsWith("file://")) event.preventDefault(); }); contents.on("will-attach-webview", (event) => event.preventDefault()); window.once("ready-to-show", () => window.show()); contents.once("did-finish-load", () => { if (!window.isDestroyed() && !window.isVisible()) window.show(); log("ready", "发布流水线界面已加载"); }); if (MAIN_WINDOW_VITE_DEV_SERVER_URL) { void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL); } else { void window.loadFile( path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), ); } win = window; return window; } function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer( window: BrowserWindow, code: string, ): Promise { let lastCaught: unknown = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)) as T; } catch (caught) { lastCaught = caught; await delay(150); } } throw lastCaught instanceof Error ? lastCaught : new Error(String(lastCaught)); } async function waitForRenderer(window: BrowserWindow): Promise { for (let attempt = 0; attempt < 160; attempt += 1) { if (window.isDestroyed()) return; try { const ready = await evalRenderer( window, "typeof window.__demo === 'function'", ); if (ready) return; } catch { // 页面仍在加载。 } await delay(100); } throw new Error("renderer did not become ready"); } type DemoState = { score: number; checks: number; passed: number; steps: number; passedSteps: number; failedSteps: number; pendingSteps: number; artifacts: number; hashes: number; feedBytes: number; reportExists: boolean; reportSteps: number; decision: string; noNetwork: boolean; }; async function runSmoke(window: BrowserWindow): Promise { try { await waitForRenderer(window); await delay(600); await waitForRenderer(window); const state = await evalRenderer(window, "window.__demo()"); process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: state.score === 100 && state.checks === 10 && state.passed === 10 && state.steps === 5 && state.passedSteps === 5 && state.failedSteps === 0 && state.pendingSteps === 0 && state.artifacts === 3 && state.hashes === 3 && state.feedBytes > 0 && state.reportExists && state.reportSteps === 5 && state.decision === "update" && state.noNetwork, ...state, })}\n`, ); app.quit(); } catch (caught) { process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`, ); app.exit(1); } } async function capture( window: BrowserWindow, dir: string, file: string, ): Promise { const image = await window.webContents.capturePage(); if (image.isEmpty()) throw new Error(`empty capture: ${file}`); const png = image.toPNG(); fsSync.writeFileSync(path.join(dir, file), png); fsSync.writeFileSync(path.join(dir, "raw", file), png); } async function runShots(window: BrowserWindow): Promise { try { const dir = path.resolve( process.cwd(), "../../../docs/assets/images/57-project-release-pipeline", ); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(600); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("success")`); await delay(300); await capture(window, dir, "57-01-success.png"); await evalRenderer(window, `window.__prepareShots("failure")`); await delay(300); await capture(window, dir, "57-02-failure.png"); await evalRenderer(window, `window.__prepareShots("artifacts")`); await delay(300); await capture(window, dir, "57-03-artifacts.png"); app.quit(); } catch (caught) { process.stdout.write( `${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`, ); app.exit(1); } } ipcMain.handle(CH.snapshot, () => snapshot()); ipcMain.handle(CH.run, () => { injectFailure = false; runPipeline(); return snapshot(); }); ipcMain.handle(CH.inject, () => { injectFailure = true; runPipeline(); return snapshot(); }); ipcMain.handle(CH.refresh, () => { runPipeline(); return snapshot(); }); app.whenReady().then(() => { runPipeline(); const window = createWindow(); if (isSmoke) { void runSmoke(window); } else if (isShots) { void runShots(window); } app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } else { win?.show(); win?.focus(); } }); }); app.on("will-quit", () => { if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); });