import { app, BrowserWindow, ipcMain } from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { CH } from "../shared/ipc"; import { ARTIFACTS, LAYERS, TOOLS } from "../shared/targets"; app.setName("Packaging 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(), `pack54-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); const appRoot = app.getAppPath(); const fixtureFile = path.join(appRoot, "fixtures", "measurements.json"); let win = null; let events = []; let measurements = { appName: "PackagingLab", arch: "", appBytes: 0, asarBytes: 0, zipBytes: 0, dmgBytes: 0, measuredAt: "", note: "", }; function log(kind, detail) { events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40); broadcast(); } function broadcast() { if (win && !win.isDestroyed()) { win.webContents.send("pack:event", { at: Date.now() }); } } function loadMeasurements() { try { const raw = JSON.parse(fsSync.readFileSync(fixtureFile, "utf8")); if (typeof raw !== "object" || raw === null) return; measurements = { ...measurements, ...raw }; } catch (error) { log("measure-error", error instanceof Error ? error.message : String(error)); } } function checks() { const macRows = ARTIFACTS.filter((row) => row.platform === "macOS"); const updateRows = ARTIFACTS.filter((row) => row.updateSource); const updateIds = updateRows.map((row) => row.id); return [ { id: "layers", label: "四层模型完整", pass: LAYERS.length === 4, detail: LAYERS.map((layer) => layer.id).join(" → "), }, { id: "artifacts", label: "产物形态覆盖 14 项", pass: ARTIFACTS.length === 14, detail: String(ARTIFACTS.length), }, { id: "macos", label: "macOS 覆盖 dir/zip/dmg/pkg", pass: macRows.length === 4, detail: macRows.map((row) => row.id).join(","), }, { id: "update", label: "更新源只包含 zip/squirrel/appx/snap/flatpak", pass: updateIds.join(",") === "zip,squirrel,appx,snap,flatpak", detail: updateIds.join(","), }, { id: "app-size", label: "实测 .app 体积 > 0", pass: measurements.appBytes > 0, detail: `${measurements.appBytes} B`, }, { id: "asar", label: "实测 app.asar 体积在 0 与 app 之间", pass: measurements.asarBytes > 0 && measurements.asarBytes < measurements.appBytes, detail: `${measurements.asarBytes} B`, }, { id: "arch", label: "实测架构已记录", pass: measurements.arch.length > 0, detail: measurements.arch, }, { id: "zip", label: "实测 zip 体积 > 0", pass: measurements.zipBytes > 0, detail: `${measurements.zipBytes} B`, }, { id: "dmg", label: "实测 dmg 体积 > 0", pass: measurements.dmgBytes > 0, detail: `${measurements.dmgBytes} B`, }, { id: "tools", label: "工具对照包含 Forge / builder / packager", pass: TOOLS.length === 3, detail: TOOLS.map((tool) => tool.name).join(" / "), }, ]; } function snapshot() { const list = checks(); const passed = list.filter((check) => check.pass).length; return { platform: process.platform, electronVersion: process.versions.electron, nodeVersion: process.versions.node, layers: LAYERS.map((layer) => ({ ...layer })), artifacts: ARTIFACTS.map((row) => ({ ...row })), tools: TOOLS.map((row) => ({ ...row })), measurements: { ...measurements }, checks: list, score: Math.round((passed / list.length) * 100), events: events.map((row) => ({ ...row })), }; } function resolvePreload() { 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() { 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) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer(window, code) { let lastCaught = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)); } catch (caught) { lastCaught = caught; await delay(150); } } throw lastCaught instanceof Error ? lastCaught : new Error(String(lastCaught)); } async function waitForRenderer(window) { 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"); } async function runSmoke(window) { 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.layers === 4 && state.artifacts === 14 && state.macRows === 4 && state.updateRows === 5 && state.appBytes > 0 && state.asarBytes > 0 && state.zipBytes > 0 && state.dmgBytes > 0 && state.arch.length > 0 && state.tools === 3, ...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, dir, file) { 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) { try { const dir = path.resolve(process.cwd(), "../../../docs/assets/images/54-packaging-targets-and-artifacts"); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(600); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("matrix")`); await delay(250); await capture(window, dir, "54-01-matrix.png"); await evalRenderer(window, `window.__prepareShots("macos")`); await delay(250); await capture(window, dir, "54-02-macos.png"); await evalRenderer(window, `window.__prepareShots("tools")`); await delay(250); await capture(window, dir, "54-03-tools.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.refresh, () => { loadMeasurements(); log("refresh", "重新读取实测产物数据"); return snapshot(); }); app.whenReady().then(() => { loadMeasurements(); log("load", `measurements ${measurements.appName}`); 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(); }); //# sourceMappingURL=index.js.map