AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: streamline release automation
tianma-if8c2da0684507
diff --git a/docs/release.md b/docs/release.mdnew file mode 100644index 00000000..350bd8c4--- /dev/null+++ b/docs/release.md@@ -0,0 +1,69 @@+# Release Guide++EdgeEver releases are prepared with a single local command. The command validates+the repository, creates the tracking Issue, updates versions, prepares and audits+native assets in a Draft Release, publishes the Release, and installs the final+macOS DMG.++## Prerequisites++- Run the command on macOS from a clean `main` branch that exactly matches+ `origin/main`.+- Authenticate GitHub CLI with access to `tianma-if/edgeever`.+- Commit all user-facing changes before starting the release.+- Ensure every English change bullet has a corresponding Chinese bullet.++## Command++```bash+bun run release -- \+ --issue-title "Improve the release workflow" \+ --label enhancement \+ --change-en "Run required release checks in parallel." \+ --change-zh "并行执行发布所需检查。"+```++Repeat `--change-en` and `--change-zh` in matching pairs when a Release contains+multiple changes. Repeat `--label` when the tracking Issue needs multiple labels.++Use `--dry-run` to inspect the native rebuild plan and generated bilingual notes+without changing local or GitHub state. `--skip-install` skips the post-release+DMG installation and is intended for exceptional or non-macOS runs; normal+maintainer releases should install and launch the published application.++## Automated Flow++1. Verify `main`, the working tree, GitHub authentication, the latest formal+ Release, and the local/remote commit relationship.+2. Run Web type checking, mobile type checking, the Web production build, and+ release-planning tests concurrently.+3. Use `scripts/plan-native-release.mjs` to determine whether desktop and Android+ assets must be rebuilt or can be reused. Only affected native versions are+ updated.+4. Create a bilingual tracking Issue, commit the version changes to `main`, push,+ and create a Draft Release with bilingual notes.+5. Dispatch the desktop and Android asset workflows concurrently, wait for both,+ and verify filenames, sizes, and checksums before publication.+6. Publish the Release and wait only for the required desktop and Android+ post-publication audits.+7. Print the Demo deployment run or workflow URL. Demo deployment continues in+ the background and does not delay release completion.+8. Link and close the tracking Issue, download the final DMG, verify its checksum+ and signature, replace `/Applications/EdgeEver.app`, and launch it.++The release version commit includes the standard GitHub Actions skip marker.+Draft asset workflows are dispatched explicitly, so this avoids an unnecessary+push-triggered Android build without skipping required release builds.++## Failure and Resume Behavior++- A validation or Draft asset failure leaves the Release unpublished.+- If the process stops after the version commit and Draft creation, rerun the+ same command. A Draft whose version and target match the current `main` commit+ is resumed instead of creating another Issue, commit, or Release.+- A failed post-publication native audit attempts to return the Release to Draft+ and leaves the Issue open for correction.+- A failed application replacement restores the previous app from the macOS+ Trash backup when possible.+- Demo deployment status is intentionally independent of Release completion;+ use the printed Actions URL to inspect or retry it.diff --git a/docs/release.zh-CN.md b/docs/release.zh-CN.mdnew file mode 100644index 00000000..24eb5902--- /dev/null+++ b/docs/release.zh-CN.md@@ -0,0 +1,62 @@+# Release 发布指南++EdgeEver 使用一条本地命令准备 Release。该命令会检查仓库、创建跟踪 Issue、+更新版本、在 Draft Release 中准备并审计原生资产、正式发布 Release,并安装最终+的 macOS DMG。++## 前置条件++- 在 macOS 上执行,当前必须是干净的 `main` 分支,并且与 `origin/main` 完全一致。+- GitHub CLI 已完成认证,并且有权访问 `tianma-if/edgeever`。+- 开始发布前,所有面向用户的改动都已提交。+- 每条英文更新说明都必须有对应的中文说明。++## 命令++```bash+bun run release -- \+ --issue-title "Improve the release workflow" \+ --label enhancement \+ --change-en "Run required release checks in parallel." \+ --change-zh "并行执行发布所需检查。"+```++如果一个 Release 包含多项改动,请成对重复传入 `--change-en` 和+`--change-zh`。跟踪 Issue 需要多个 Label 时,可以重复传入 `--label`。++使用 `--dry-run` 可以只查看原生端重建计划和生成的双语说明,不修改本地或+GitHub 状态。`--skip-install` 会跳过发布后的 DMG 安装,仅适用于特殊情况或+非 macOS 环境;维护者正常发布时仍应安装并启动已发布的应用。++## 自动化流程++1. 检查 `main`、工作区、GitHub 认证、上一个正式 Release,以及本地与远端的+ 提交关系。+2. 并行执行 Web 类型检查、移动端类型检查、Web 生产构建和 Release 规划测试。+3. 使用 `scripts/plan-native-release.mjs` 判断桌面端和 Android 资产需要重建+ 还是可以复用,并且只更新受影响原生端的版本。+4. 创建双语跟踪 Issue,将版本变更提交并推送到 `main`,然后创建带双语说明的+ Draft Release。+5. 并行触发桌面端和 Android 资产工作流,等待两者完成,并在正式发布前检查+ 文件名、大小和校验和。+6. 正式发布 Release,且只等待必要的桌面端和 Android 发布后资产审计。+7. 输出 Demo 部署任务或工作流链接。Demo 在后台继续部署,不再延迟 Release+ 完成。+8. 回链并关闭跟踪 Issue,下载最终 DMG,验证校验和与签名,覆盖+ `/Applications/EdgeEver.app` 并启动。++版本发布提交会包含 GitHub Actions 的标准跳过标记。Draft 资产工作流由脚本+显式触发,因此可以避免一次不必要的 push 触发 Android 构建,同时不会跳过+正式发布所需的构建。++## 失败与续跑++- 本地验证或 Draft 资产失败时,Release 会保持未发布状态。+- 如果流程在版本提交和 Draft 创建后中断,重新执行同一条命令即可。脚本会识别+ 版本和目标提交都与当前 `main` 匹配的 Draft,不会重复创建 Issue、提交或+ Release。+- 发布后的原生资产审计失败时,脚本会尝试把 Release 恢复为 Draft,并保留+ Issue 供后续修复。+- 替换应用失败时,脚本会尽可能从 macOS 废纸篓备份恢复上一版应用。+- Demo 部署状态有意与 Release 完成状态解耦;可以通过脚本输出的 Actions 链接+ 查看或重试。diff --git a/package.json b/package.jsonindex 53624d07..e8137283 100644--- a/package.json+++ b/package.json@@ -34,7 +34,8 @@"build:desktop": "EDGE_EVER_DESKTOP_BUILD=1 bun run build:web && bun run build:desktop:sidecar && bun run --cwd apps/desktop dist","benchmark:desktop:sidecar": "bun scripts/benchmark-desktop-sidecar.mjs","verify:web-performance": "bun scripts/verify-web-performance.mjs",- "test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs",+ "test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs scripts/release.test.mjs",+ "release": "bun scripts/release.mjs","test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs","test:desktop": "bun test apps/desktop/src/main/account-scope.test.mjs apps/desktop/src/main/diagnostic-log.test.mjs apps/desktop/src/main/file-association.test.mjs apps/desktop/src/main/file-permissions.test.mjs apps/desktop/src/main/installation-location.test.mjs apps/desktop/src/main/resource-url.test.mjs apps/desktop/src/main/staged-resource.test.mjs apps/desktop/src/main/user-data-directory.test.mjs apps/desktop/src/main/window-open-policy.test.mjs apps/desktop/src/main/window-visibility.test.mjs apps/web/src/lib/api.test.mjs apps/web/src/lib/app-page-path.test.mjs apps/web/src/lib/desktop-resources.test.mjs apps/web/src/lib/desktop-sync.test.mjs apps/web/src/lib/local-mirror.test.mjs apps/web/src/lib/repository.test.mjs apps/web/src/lib/runtime.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun run test:desktop:sidecar","verify:desktop-package": "bun scripts/verify-desktop-package.mjs",diff --git a/scripts/release.mjs b/scripts/release.mjsnew file mode 100644index 00000000..87c195cf--- /dev/null+++ b/scripts/release.mjs@@ -0,0 +1,902 @@+import {+ createHash,+} from "node:crypto";+import {+ createReadStream,+ existsSync,+ mkdtempSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { basename, join, resolve, sep } from "node:path";+import { spawn, spawnSync } from "node:child_process";+import { nativeReleaseAssetsReady } from "./check-native-release-assets.mjs";+import { planNativeRelease } from "./plan-native-release.mjs";++const DEFAULT_REPOSITORY = "tianma-if/edgeever";+const POLL_INTERVAL_MS = 10_000;+const RUN_DISCOVERY_TIMEOUT_MS = 60_000;+const RELEASE_WORKFLOWS = {+ desktop: "desktop-build.yml",+ mobile: "mobile-build.yml",+ demo: "deploy-demo.yml",+};++export const RELEASE_VALIDATIONS = [+ { label: "Web typecheck", args: ["run", "typecheck"] },+ { label: "Mobile typecheck", args: ["run", "typecheck:mobile"] },+ { label: "Web build", args: ["run", "build:web"] },+ {+ label: "Native release planning tests",+ args: [+ "test",+ "scripts/plan-native-release.test.mjs",+ "scripts/check-native-release-assets.test.mjs",+ "scripts/release.test.mjs",+ ],+ },+];++const usage = `Usage:+ bun run release -- \\+ --issue-title "Release issue title" \\+ --label bug \\+ --change-en "English user-facing change" \\+ --change-zh "中文用户更新说明"++Repeat --change-en and --change-zh for multiple paired release bullets.++Options:+ --repository <owner/name> GitHub repository (default: ${DEFAULT_REPOSITORY})+ --issue-title <title> Required umbrella Issue title+ --label <label> Required Issue label; may be repeated+ --change-en <text> Required English release bullet; may be repeated+ --change-zh <text> Required Chinese release bullet; may be repeated+ --skip-install Do not install the final DMG after publication+ --dry-run Print the plan and generated notes without mutations+ --help Show this help+`;++export const parseReleaseArgs = (argv) => {+ const options = {+ repository: DEFAULT_REPOSITORY,+ issueTitle: "",+ labels: [],+ changesEn: [],+ changesZh: [],+ skipInstall: false,+ dryRun: false,+ help: false,+ };++ const valueOptions = new Map([+ ["--repository", "repository"],+ ["--issue-title", "issueTitle"],+ ["--label", "labels"],+ ["--change-en", "changesEn"],+ ["--change-zh", "changesZh"],+ ]);++ for (let index = 0; index < argv.length; index += 1) {+ const argument = argv[index];+ if (argument === "--skip-install") {+ options.skipInstall = true;+ continue;+ }+ if (argument === "--dry-run") {+ options.dryRun = true;+ continue;+ }+ if (argument === "--help") {+ options.help = true;+ continue;+ }++ const key = valueOptions.get(argument);+ if (!key) {+ throw new Error(`Unknown option: ${argument}`);+ }+ const value = argv[index + 1]?.trim();+ if (!value || value.startsWith("--")) {+ throw new Error(`${argument} requires a value.`);+ }+ index += 1;+ if (Array.isArray(options[key])) {+ options[key].push(value);+ } else {+ options[key] = value;+ }+ }++ if (options.help) {+ return options;+ }+ if (!/^[^/\s]+\/[^/\s]+$/.test(options.repository)) {+ throw new Error("--repository must use owner/name format.");+ }+ if (!options.issueTitle) {+ throw new Error("--issue-title is required.");+ }+ if (options.labels.length === 0) {+ throw new Error("At least one --label is required.");+ }+ if (options.changesEn.length === 0 || options.changesZh.length === 0) {+ throw new Error("At least one --change-en and --change-zh are required.");+ }+ if (options.changesEn.length !== options.changesZh.length) {+ throw new Error("--change-en and --change-zh must have the same count.");+ }+ return options;+};++export const nextPatchVersion = (version) => {+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);+ if (!match) {+ throw new Error(`Expected a stable X.Y.Z version, received: ${version}`);+ }+ return `${match[1]}.${match[2]}.${Number(match[3]) + 1}`;+};++export const buildIssueBody = ({ changesEn, changesZh }) => [+ "## Summary",+ "",+ ...changesEn.map((change) => `- ${change}`),+ "",+ "## 中文说明",+ "",+ ...changesZh.map((change) => `- ${change}`),+ "",+ "## Acceptance criteria",+ "",+ "- Required type checks, Web build, and native release planning tests pass.",+ "- The Draft Release contains an audited macOS arm64 DMG and Android arm64 APK.",+ "- Post-publication native asset audits pass.",+].join("\n");++export const buildReleaseNotes = ({+ changesEn,+ changesZh,+ issueNumber,+ desktopRebuild,+ mobileRebuild,+ previousTag,+}) => [+ "## Key Changes",+ "",+ ...changesEn.map((change) => `- ${change}`),+ "",+ `Related Issue: #${issueNumber}`,+ "",+ "## Verification",+ "",+ "- `bun run typecheck`",+ "- `bun run typecheck:mobile`",+ "- `bun run build:web`",+ "- Native release planning and asset audit tests.",+ desktopRebuild+ ? "- Desktop release plan: rebuild, sign, notarize, and verify a new macOS arm64 DMG."+ : `- Desktop release plan: reuse the verified assets from ${previousTag} with their original filenames and checksums.`,+ mobileRebuild+ ? "- Android release plan: rebuild and verify a signed arm64 APK."+ : `- Android release plan: reuse the verified APK from ${previousTag} with its original filename and checksum.`,+ "",+ "## 🇨🇳 中文说明 / Chinese Changelog",+ "",+ "## 主要更新",+ "",+ ...changesZh.map((change) => `- ${change}`),+ "",+ `关联 Issue:#${issueNumber}`,+ "",+ "## 验证",+ "",+ "- `bun run typecheck`",+ "- `bun run typecheck:mobile`",+ "- `bun run build:web`",+ "- 原生 Release 规划与资产审计测试。",+ desktopRebuild+ ? "- 桌面端 Release 计划:重新构建、签名、公证并验证新的 macOS arm64 DMG。"+ : `- 桌面端 Release 计划:复用 ${previousTag} 已验证资产,并保留原始文件名与校验和。`,+ mobileRebuild+ ? "- Android Release 计划:重新构建并验证签名 arm64 APK。"+ : `- Android Release 计划:复用 ${previousTag} 已验证 APK,并保留原始文件名与校验和。`,+ "",+].join("\n");++export const reusedAssetMatches = (previousAssets, currentAssets, name) => {+ const previous = previousAssets.find((asset) => asset.name === name);+ const current = currentAssets.find((asset) => asset.name === name);+ return Boolean(+ previous &&+ current &&+ previous.digest &&+ previous.digest === current.digest &&+ previous.size === current.size,+ );+};++const run = (executable, args, { capture = false, allowFailure = false } = {}) => {+ const result = spawnSync(executable, args, {+ cwd: resolve("."),+ encoding: "utf8",+ env: process.env,+ stdio: capture ? ["ignore", "pipe", "pipe"] : "inherit",+ });+ if (result.status !== 0 && !allowFailure) {+ const detail = [result.stdout, result.stderr].filter(Boolean).join("\n").trim();+ throw new Error(+ `${executable} ${args.join(" ")} exited with status ${result.status ?? 1}${detail ? `:\n${detail}` : ""}`,+ );+ }+ return capture ? String(result.stdout ?? "").trim() : result;+};++const ghJson = (args) => JSON.parse(run("gh", args, { capture: true }));+const wait = (milliseconds) => new Promise((resolveWait) => setTimeout(resolveWait, milliseconds));++export const runParallelValidations = async ({+ executable = process.execPath,+ validations = RELEASE_VALIDATIONS,+} = {}) => {+ console.log(`[release] running ${validations.length} validations in parallel`);+ const results = await Promise.all(+ validations.map(({ label, args }) => new Promise((resolveValidation) => {+ console.log(`[release] start: ${label}`);+ const child = spawn(executable, args, {+ cwd: resolve("."),+ env: process.env,+ stdio: "inherit",+ });+ child.on("error", (error) => resolveValidation({ label, error }));+ child.on("exit", (code, signal) => resolveValidation({ label, code, signal }));+ })),+ );+ const failures = results.filter((result) => result.error || result.code !== 0);+ if (failures.length > 0) {+ throw new Error(+ `Release validation failed: ${failures.map(({ label }) => label).join(", ")}`,+ );+ }+ console.log("[release] all parallel validations passed");+};++const readJson = (path) => JSON.parse(readFileSync(path, "utf8"));+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);++const changedFilesBetween = (baseRef, headRef) => run(+ "git",+ ["diff", "--name-only", `${baseRef}...${headRef}`],+ { capture: true },+).split("\n").filter(Boolean);++const assertReleasePreconditions = ({ repository, previousTag }) => {+ if (run("git", ["branch", "--show-current"], { capture: true }) !== "main") {+ throw new Error("Releases must run directly from the main branch.");+ }+ if (run("git", ["status", "--porcelain"], { capture: true })) {+ throw new Error("The working tree must be clean before starting a release.");+ }+ run("git", ["fetch", "origin", "main", "--tags"]);+ const [behind, ahead] = run(+ "git",+ ["rev-list", "--left-right", "--count", "origin/main...main"],+ { capture: true },+ ).split(/\s+/).map(Number);+ if (behind !== 0 || ahead !== 0) {+ throw new Error("main must exactly match origin/main before starting a release.");+ }+ if (run("gh", ["auth", "status"], { allowFailure: true }).status !== 0) {+ throw new Error("GitHub CLI authentication is required.");+ }+ run("git", ["rev-parse", "--verify", `${previousTag}^{commit}`], { capture: true });+ const remote = run("gh", ["repo", "view", repository, "--json", "nameWithOwner", "--jq", ".nameWithOwner"], { capture: true });+ if (remote !== repository) {+ throw new Error(`Unable to resolve repository ${repository}.`);+ }+};++const updateReleaseVersions = ({ nextVersion, desktopRebuild, mobileRebuild }) => {+ const changedPaths = ["package.json"];+ const rootPackage = readJson("package.json");+ rootPackage.version = nextVersion;+ writeJson("package.json", rootPackage);++ if (desktopRebuild) {+ const desktopPackage = readJson("apps/desktop/package.json");+ desktopPackage.version = nextVersion;+ writeJson("apps/desktop/package.json", desktopPackage);+ changedPaths.push("apps/desktop/package.json");+ }++ if (mobileRebuild) {+ const mobileConfig = readJson("apps/mobile/app.json");+ mobileConfig.expo.version = nextVersion;+ mobileConfig.expo.android.versionCode += 1;+ writeJson("apps/mobile/app.json", mobileConfig);+ changedPaths.push("apps/mobile/app.json");+ }+ return changedPaths;+};++const parseRunId = (output) => {+ const match = output.match(/\/actions\/runs\/(\d+)/);+ return match ? Number(match[1]) : null;+};++const waitForRun = async ({ repository, runId, label }) => {+ let lastStatus = "";+ while (true) {+ const runView = ghJson([+ "run",+ "view",+ String(runId),+ "--repo",+ repository,+ "--json",+ "status,conclusion,url,headSha",+ ]);+ const statusLabel = `${runView.status}${runView.conclusion ? `/${runView.conclusion}` : ""}`;+ if (statusLabel !== lastStatus) {+ console.log(`[release] ${label}: ${statusLabel} (${runView.url})`);+ lastStatus = statusLabel;+ }+ if (runView.status === "completed") {+ if (runView.conclusion !== "success") {+ throw new Error(`${label} failed: ${runView.url}`);+ }+ return runView;+ }+ await wait(POLL_INTERVAL_MS);+ }+};++const listWorkflowRuns = ({ repository, workflow, event }) => ghJson([+ "run",+ "list",+ "--repo",+ repository,+ "--workflow",+ workflow,+ "--event",+ event,+ "--limit",+ "20",+ "--json",+ "databaseId,displayTitle,headSha,createdAt,url,status,conclusion",+]);++const dispatchReleaseWorkflow = async ({+ repository,+ workflow,+ tag,+ headSha,+}) => {+ const existingRunIds = new Set(+ listWorkflowRuns({+ repository,+ workflow,+ event: "workflow_dispatch",+ }).map((candidate) => candidate.databaseId),+ );+ const dispatchedAt = Date.now();+ const output = run("gh", [+ "workflow",+ "run",+ workflow,+ "--repo",+ repository,+ "--ref",+ "main",+ "-f",+ `release_tag=${tag}`,+ ], { capture: true });+ const returnedRunId = parseRunId(output);+ if (returnedRunId) {+ return returnedRunId;+ }++ const deadline = Date.now() + RUN_DISCOVERY_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const match = listWorkflowRuns({+ repository,+ workflow,+ event: "workflow_dispatch",+ }).find((candidate) =>+ !existingRunIds.has(candidate.databaseId) &&+ candidate.headSha === headSha &&+ Date.parse(candidate.createdAt) >= dispatchedAt - 5_000+ );+ if (match) {+ return match.databaseId;+ }+ await wait(2_000);+ }+ throw new Error(`Timed out discovering dispatched ${workflow} run for ${tag}.`);+};++const findReleaseRun = async ({+ repository,+ workflow,+ tag,+ headSha,+ publishedAfter,+}) => {+ const deadline = Date.now() + RUN_DISCOVERY_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const runs = listWorkflowRuns({ repository, workflow, event: "release" });+ const match = runs.find((candidate) =>+ candidate.displayTitle === tag &&+ candidate.headSha === headSha &&+ Date.parse(candidate.createdAt) >= publishedAfter - 5_000+ );+ if (match) {+ return match;+ }+ await wait(2_000);+ }+ throw new Error(`Timed out discovering ${workflow} for ${tag}.`);+};++const assertDraftAssets = ({+ assets,+ previousAssets,+ tag,+ version,+ desktopRebuild,+ mobileRebuild,+}) => {+ const assetNames = assets.map((asset) => asset.name);+ if (!nativeReleaseAssetsReady({+ platform: "desktop",+ rebuild: desktopRebuild,+ currentTag: tag,+ desktopVersion: version,+ assetNames,+ })) {+ throw new Error("Draft Release desktop assets are incomplete or incompatible.");+ }+ if (!nativeReleaseAssetsReady({+ platform: "mobile",+ rebuild: mobileRebuild,+ currentTag: tag,+ assetNames,+ })) {+ throw new Error("Draft Release Android assets are incomplete or incompatible.");+ }++ if (!mobileRebuild) {+ const previousApk = previousAssets.find((asset) =>+ /^edgeever-android-v.*-arm64-v8a\.apk$/.test(asset.name)+ );+ if (!previousApk || !reusedAssetMatches(previousAssets, assets, previousApk.name)) {+ throw new Error("Reused Android APK filename, size, or checksum changed.");+ }+ }+ if (!desktopRebuild) {+ const previousDesktopNames = previousAssets+ .map((asset) => asset.name)+ .filter((name) =>+ /^EdgeEver-.*-mac-arm64\.dmg(?:\.blockmap)?$/.test(name) ||+ name === "latest-mac.yml"+ );+ if (+ previousDesktopNames.length !== 3 ||+ !previousDesktopNames.every((name) =>+ reusedAssetMatches(previousAssets, assets, name)+ )+ ) {+ throw new Error("Reused desktop asset filename, size, or checksum changed.");+ }+ }+};++const sha256File = (path) => new Promise((resolveHash, rejectHash) => {+ const hash = createHash("sha256");+ const stream = createReadStream(path);+ stream.on("error", rejectHash);+ stream.on("data", (chunk) => hash.update(chunk));+ stream.on("end", () => resolveHash(hash.digest("hex")));+});++const installPublishedDmg = async ({ repository, tag, version, assets }) => {+ if (process.platform !== "darwin") {+ throw new Error("Final DMG installation requires macOS; use --skip-install elsewhere.");+ }+ const dmg = assets.find((asset) => asset.name === `EdgeEver-${version}-mac-arm64.dmg`);+ if (!dmg?.digest?.startsWith("sha256:")) {+ throw new Error("Published DMG is missing its SHA-256 digest.");+ }++ const temporaryDirectory = mkdtempSync(join(tmpdir(), "edgeever-release-"));+ const mountDirectory = join(temporaryDirectory, "mount");+ const dmgPath = join(temporaryDirectory, dmg.name);+ mkdirSync(mountDirectory);+ let mounted = false;+ let backupPath = "";++ try {+ run("gh", [+ "release",+ "download",+ tag,+ "--repo",+ repository,+ "--pattern",+ dmg.name,+ "--dir",+ temporaryDirectory,+ ]);+ const digest = await sha256File(dmgPath);+ if (`sha256:${digest}` !== dmg.digest) {+ throw new Error(`Downloaded DMG checksum mismatch: ${digest}`);+ }++ run("hdiutil", [+ "attach",+ dmgPath,+ "-nobrowse",+ "-readonly",+ "-mountpoint",+ mountDirectory,+ ]);+ mounted = true;+ const sourceApp = join(mountDirectory, "EdgeEver.app");+ if (!existsSync(sourceApp)) {+ throw new Error("Mounted DMG does not contain EdgeEver.app.");+ }++ run("osascript", ["-e", 'tell application "EdgeEver" to quit'], { allowFailure: true });+ await wait(2_000);+ const installedApp = "/Applications/EdgeEver.app";+ if (existsSync(installedApp)) {+ const trashDirectory = join(process.env.HOME || "", ".Trash");+ if (!trashDirectory.startsWith(`${sep}Users${sep}`)) {+ throw new Error("Could not resolve a safe Trash directory for the previous app.");+ }+ backupPath = join(trashDirectory, `EdgeEver.app.pre-${tag}`);+ if (existsSync(backupPath)) {+ backupPath = `${backupPath}.${Date.now()}`;+ }+ renameSync(installedApp, backupPath);+ }+ try {+ run("ditto", [sourceApp, installedApp]);+ const installedVersion = run(+ "defaults",+ ["read", join(installedApp, "Contents/Info.plist"), "CFBundleShortVersionString"],+ { capture: true },+ );+ if (installedVersion !== version) {+ throw new Error(`Installed app version is ${installedVersion}, expected ${version}.`);+ }+ run("codesign", ["--verify", "--deep", "--strict", installedApp]);+ } catch (error) {+ if (existsSync(installedApp) && backupPath) {+ renameSync(installedApp, `${backupPath}.failed-${Date.now()}`);+ }+ if (backupPath && existsSync(backupPath)) {+ renameSync(backupPath, installedApp);+ }+ throw error;+ }+ run("open", ["-a", installedApp]);+ console.log(`[release] installed and launched EdgeEver ${version}`);+ if (backupPath) {+ console.log(`[release] previous app backup: ${backupPath}`);+ }+ } finally {+ if (mounted) {+ run("hdiutil", ["detach", mountDirectory], { allowFailure: true });+ }+ if (temporaryDirectory.startsWith(`${tmpdir()}${sep}edgeever-release-`)) {+ rmSync(temporaryDirectory, { recursive: true, force: true });+ }+ }+};++const releaseMain = async (options) => {+ const latestRelease = ghJson([+ "api",+ `repos/${options.repository}/releases/latest`,+ "--jq",+ "{tagName:.tag_name,assets:[.assets[]|{name,size,digest}]}",+ ]);+ const previousTag = latestRelease.tagName;+ assertReleasePreconditions({ repository: options.repository, previousTag });++ const rootPackage = readJson("package.json");+ const previousVersion = previousTag.replace(/^v/, "");+ const expectedNextVersion = nextPatchVersion(previousVersion);+ const headShaBeforeRelease = run("git", ["rev-parse", "HEAD"], { capture: true });+ let resumedDraft = null;+ if (rootPackage.version === expectedNextVersion) {+ const draftCandidate = ghJson([+ "release",+ "view",+ `v${rootPackage.version}`,+ "--repo",+ options.repository,+ "--json",+ "tagName,isDraft,isPrerelease,targetCommitish,body,assets,url",+ ]);+ if (+ !draftCandidate.isDraft ||+ draftCandidate.isPrerelease ||+ draftCandidate.targetCommitish !== headShaBeforeRelease+ ) {+ throw new Error(+ `${draftCandidate.tagName} exists but is not a compatible Draft for the current HEAD.`,+ );+ }+ resumedDraft = draftCandidate;+ } else if (rootPackage.version !== previousVersion) {+ throw new Error(+ `package.json version ${rootPackage.version} must match ${previousVersion}, or ${expectedNextVersion} with a resumable Draft.`,+ );+ }+ const nextVersion = resumedDraft ? rootPackage.version : expectedNextVersion;+ const tag = `v${nextVersion}`;+ const changedFiles = changedFilesBetween(previousTag, headShaBeforeRelease);+ if (changedFiles.length === 0) {+ throw new Error(`There are no committed changes after ${previousTag}.`);+ }+ const desktopPlan = planNativeRelease("desktop", changedFiles);+ const mobilePlan = planNativeRelease("mobile", changedFiles);++ console.log(`[release] ${previousTag} -> ${tag}`);+ console.log(`[release] desktop: ${desktopPlan.rebuild ? "rebuild" : "reuse"}`);+ console.log(`[release] Android: ${mobilePlan.rebuild ? "rebuild" : "reuse"}`);++ if (options.dryRun) {+ console.log(buildReleaseNotes({+ changesEn: options.changesEn,+ changesZh: options.changesZh,+ issueNumber: 0,+ desktopRebuild: desktopPlan.rebuild,+ mobileRebuild: mobilePlan.rebuild,+ previousTag,+ }));+ return;+ }++ let issueNumber;+ let releaseSha;+ if (resumedDraft) {+ const issueMatch = resumedDraft.body.match(/Related Issue: #(\d+)/);+ if (!issueMatch) {+ throw new Error(`${tag} Draft notes do not contain a Related Issue number.`);+ }+ issueNumber = Number(issueMatch[1]);+ releaseSha = headShaBeforeRelease;+ console.log(`[release] resuming existing Draft: ${resumedDraft.url}`);+ } else {+ await runParallelValidations();++ const issueUrl = run("gh", [+ "issue",+ "create",+ "--repo",+ options.repository,+ "--title",+ options.issueTitle,+ ...options.labels.flatMap((label) => ["--label", label]),+ "--body",+ buildIssueBody(options),+ ], { capture: true });+ const issueMatch = issueUrl.match(/\/issues\/(\d+)/);+ if (!issueMatch) {+ throw new Error(`Could not parse created Issue URL: ${issueUrl}`);+ }+ issueNumber = Number(issueMatch[1]);+ console.log(`[release] created Issue #${issueNumber}: ${issueUrl}`);++ const versionPaths = updateReleaseVersions({+ nextVersion,+ desktopRebuild: desktopPlan.rebuild,+ mobileRebuild: mobilePlan.rebuild,+ });+ run("git", ["add", ...versionPaths]);+ run("git", ["diff", "--cached", "--check"]);+ run("git", ["commit", "-m", `chore: release ${tag} [skip ci]`]);+ run("git", ["push", "origin", "main"]);+ releaseSha = run("git", ["rev-parse", "HEAD"], { capture: true });++ const notes = buildReleaseNotes({+ changesEn: options.changesEn,+ changesZh: options.changesZh,+ issueNumber,+ desktopRebuild: desktopPlan.rebuild,+ mobileRebuild: mobilePlan.rebuild,+ previousTag,+ });+ const draftUrl = run("gh", [+ "release",+ "create",+ tag,+ "--repo",+ options.repository,+ "--target",+ releaseSha,+ "--title",+ tag,+ "--draft",+ "--notes",+ notes,+ ], { capture: true });+ console.log(`[release] Draft created: ${draftUrl}`);+ }++ const [desktopRunId, mobileRunId] = await Promise.all([+ dispatchReleaseWorkflow({+ repository: options.repository,+ workflow: RELEASE_WORKFLOWS.desktop,+ tag,+ headSha: releaseSha,+ }),+ dispatchReleaseWorkflow({+ repository: options.repository,+ workflow: RELEASE_WORKFLOWS.mobile,+ tag,+ headSha: releaseSha,+ }),+ ]);+ await Promise.all([+ waitForRun({+ repository: options.repository,+ runId: desktopRunId,+ label: "Draft desktop assets",+ }),+ waitForRun({+ repository: options.repository,+ runId: mobileRunId,+ label: "Draft Android assets",+ }),+ ]);++ const draft = ghJson([+ "release",+ "view",+ tag,+ "--repo",+ options.repository,+ "--json",+ "isDraft,isPrerelease,targetCommitish,body,assets",+ ]);+ if (!draft.isDraft || draft.isPrerelease || draft.targetCommitish !== releaseSha) {+ throw new Error("Draft Release metadata does not match the release commit.");+ }+ if (draft.body.includes("\\n")) {+ throw new Error("Release notes contain a literal \\\\n sequence.");+ }+ assertDraftAssets({+ assets: draft.assets,+ previousAssets: latestRelease.assets,+ tag,+ version: nextVersion,+ desktopRebuild: desktopPlan.rebuild,+ mobileRebuild: mobilePlan.rebuild,+ });++ const publishedAt = Date.now();+ const releaseUrl = run("gh", [+ "release",+ "edit",+ tag,+ "--repo",+ options.repository,+ "--draft=false",+ "--latest",+ ], { capture: true });+ console.log(`[release] published: ${releaseUrl}`);++ const [desktopAudit, mobileAudit] = await Promise.all([+ findReleaseRun({+ repository: options.repository,+ workflow: RELEASE_WORKFLOWS.desktop,+ tag,+ headSha: releaseSha,+ publishedAfter: publishedAt,+ }),+ findReleaseRun({+ repository: options.repository,+ workflow: RELEASE_WORKFLOWS.mobile,+ tag,+ headSha: releaseSha,+ publishedAfter: publishedAt,+ }),+ ]);+ const demoRuns = listWorkflowRuns({+ repository: options.repository,+ workflow: RELEASE_WORKFLOWS.demo,+ event: "release",+ });+ const demoRun = demoRuns.find((candidate) =>+ candidate.displayTitle === tag && candidate.headSha === releaseSha+ );+ console.log(+ demoRun+ ? `[release] Demo deployment continues in background: ${demoRun.url}`+ : `[release] Demo deployment continues in background: https://github.com/${options.repository}/actions/workflows/${RELEASE_WORKFLOWS.demo}`,+ );++ try {+ await Promise.all([+ waitForRun({+ repository: options.repository,+ runId: desktopAudit.databaseId,+ label: "Published desktop asset audit",+ }),+ waitForRun({+ repository: options.repository,+ runId: mobileAudit.databaseId,+ label: "Published Android asset audit",+ }),+ ]);+ } catch (error) {+ run("gh", [+ "release",+ "edit",+ tag,+ "--repo",+ options.repository,+ "--draft=true",+ ], { allowFailure: true });+ throw error;+ }++ run("gh", [+ "issue",+ "comment",+ String(issueNumber),+ "--repo",+ options.repository,+ "--body",+ `Released in [${tag}](${releaseUrl}).\n\nRequired local validations, Draft asset preparation, and post-publication native asset audits passed.`,+ ]);+ run("gh", [+ "issue",+ "close",+ String(issueNumber),+ "--repo",+ options.repository,+ "--reason",+ "completed",+ ]);+ console.log(`[release] ${tag} is complete; Demo deployment is not blocking completion`);++ if (!options.skipInstall) {+ const published = ghJson([+ "release",+ "view",+ tag,+ "--repo",+ options.repository,+ "--json",+ "assets",+ ]);+ await installPublishedDmg({+ repository: options.repository,+ tag,+ version: nextVersion,+ assets: published.assets,+ });+ }+};++if (import.meta.main) {+ try {+ const options = parseReleaseArgs(process.argv.slice(2));+ if (options.help) {+ console.log(usage);+ } else {+ await releaseMain(options);+ }+ } catch (error) {+ console.error(`[release] failed: ${error instanceof Error ? error.message : String(error)}`);+ process.exit(1);+ }+}diff --git a/scripts/release.test.mjs b/scripts/release.test.mjsnew file mode 100644index 00000000..fa9d9a9b--- /dev/null+++ b/scripts/release.test.mjs@@ -0,0 +1,83 @@+import { describe, expect, test } from "bun:test";+import {+ buildIssueBody,+ buildReleaseNotes,+ nextPatchVersion,+ parseReleaseArgs,+ reusedAssetMatches,+} from "./release.mjs";++describe("release automation", () => {+ test("parses paired bilingual changes and labels", () => {+ expect(+ parseReleaseArgs([+ "--issue-title",+ "Improve release flow",+ "--label",+ "enhancement",+ "--change-en",+ "Run checks in parallel.",+ "--change-zh",+ "并行运行检查。",+ ]),+ ).toMatchObject({+ issueTitle: "Improve release flow",+ labels: ["enhancement"],+ changesEn: ["Run checks in parallel."],+ changesZh: ["并行运行检查。"],+ });+ });++ test("rejects mismatched bilingual changes", () => {+ expect(() =>+ parseReleaseArgs([+ "--issue-title",+ "Broken input",+ "--label",+ "bug",+ "--change-en",+ "Only English.",+ ])+ ).toThrow("--change-en and --change-zh");+ });++ test("increments stable patch versions", () => {+ expect(nextPatchVersion("1.6.50")).toBe("1.6.51");+ expect(() => nextPatchVersion("1.6")).toThrow("stable X.Y.Z");+ });++ test("builds required bilingual release note structure with real newlines", () => {+ const notes = buildReleaseNotes({+ changesEn: ["Improve the release flow."],+ changesZh: ["优化发布流程。"],+ issueNumber: 126,+ desktopRebuild: false,+ mobileRebuild: false,+ previousTag: "v1.6.50",+ });+ expect(notes).toContain("## Key Changes");+ expect(notes).toContain("Related Issue: #126");+ expect(notes).toContain("## 🇨🇳 中文说明 / Chinese Changelog");+ expect(notes).toContain("关联 Issue:#126");+ expect(notes).not.toContain("\\n");+ });++ test("builds a bilingual umbrella Issue", () => {+ const body = buildIssueBody({+ changesEn: ["Parallel checks."],+ changesZh: ["并行检查。"],+ });+ expect(body).toContain("## Summary");+ expect(body).toContain("- Parallel checks.");+ expect(body).toContain("## 中文说明");+ expect(body).toContain("- 并行检查。");+ });++ test("requires reused assets to keep name, size, and digest", () => {+ const previous = [{ name: "app.apk", size: 10, digest: "sha256:abc" }];+ expect(reusedAssetMatches(previous, [...previous], "app.apk")).toBe(true);+ expect(+ reusedAssetMatches(previous, [{ ...previous[0], digest: "sha256:def" }], "app.apk"),+ ).toBe(false);+ });+});