Add dual-mode self-update and multi-target binary build

This commit is contained in:
gitea committed 2026-08-25 13:51:53 +08:00
1 parent 85ca31f4ad
commit c86ee6a235
4 files changed
+207 -19

No files matched your search

+51 -10
View File
@@ -5,22 +5,63 @@ import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
const output = resolve(root, "dist/bin/seal-home");
mkdirSync(dirname(output), { recursive: true });
run(bun, ["build", "--compile", "--outfile", output, "src/cli.ts"]);
const TARGET_MAP = {
"darwin-arm64": { bunTarget: "bun-darwin-arm64", outfile: "dist/bin/seal-home-darwin-arm64" },
"darwin-x64": { bunTarget: "bun-darwin-x64", outfile: "dist/bin/seal-home-darwin-x64" },
"linux-x64": { bunTarget: "bun-linux-x64", outfile: "dist/bin/seal-home-linux-x64" },
"linux-arm64": { bunTarget: "bun-linux-arm64", outfile: "dist/bin/seal-home-linux-arm64" },
"windows-x64": { bunTarget: "bun-windows-x64", outfile: "dist/bin/seal-home-windows-x64.exe" }
};
// Bun's macOS standalone output can carry a stale code-signature blob on
// development machines. Re-signing ad hoc keeps the local binary executable.
if (process.platform === "darwin") {
run("/usr/bin/codesign", ["--remove-signature", output]);
run("/usr/bin/codesign", ["--force", "--sign", "-", output]);
const args = process.argv.slice(2);
const isAll = args.includes("--all") || args.includes("--matrix");
const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", "");
if (isAll) {
for (const [name, config] of Object.entries(TARGET_MAP)) {
buildTarget(name, config.bunTarget, resolve(root, config.outfile));
}
} else if (targetArg) {
const config = TARGET_MAP[targetArg];
if (!config) {
throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`);
}
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
} else {
const output = resolve(root, "dist/bin/seal-home");
buildTarget("host", null, output);
}
function run(command, args) {
function buildTarget(name, bunTarget, output) {
mkdirSync(dirname(output), { recursive: true });
const buildArgs = ["build", "--compile"];
if (bunTarget) {
buildArgs.push(`--target=${bunTarget}`);
}
buildArgs.push("--outfile", output, "src/cli.ts");
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
run(bun, buildArgs);
if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) {
try {
run("/usr/bin/codesign", ["--remove-signature", output], { quiet: true });
} catch {
// ignore
}
try {
run("/usr/bin/codesign", ["--force", "--sign", "-", output], { quiet: true });
} catch {
// ignore
}
}
}
function run(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: root,
stdio: "inherit"
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit"
});
if (result.error) throw result.error;
if (result.status !== 0) {
+9
View File
@@ -111,6 +111,15 @@ describe("CLI version & help handling", () => {
expect(current.status).toBe(1);
expect(current.stderr).toContain("Stateless mode is enabled");
});
test("update command runs in source mode when executed from bun", () => {
const result = runCli(["update"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.updated).toBe(true);
expect(parsed.mode).toBe("source");
expect(parsed.version).toBe(VERSION);
});
});
function makeConfigEnv(): Record<string, string> {
+143 -7
View File
@@ -1,3 +1,4 @@
import { chmodSync, renameSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { isCompiledBinary } from "../../core/runtime.js";
import { VERSION } from "../../version.js";
@@ -6,7 +7,10 @@ import { printJson } from "../printer.js";
import { STATE_DIR } from "./service.js";
import type { CliRuntime } from "../types.js";
export async function handleUpdateCommand(runtime: CliRuntime) {
const DEFAULT_GITHUB_REPO = "yunyingk/seal-home";
const UPDATE_URL_ENV = "SEAL_HOME_UPDATE_URL";
export async function handleUpdateCommand(runtime: CliRuntime, options: { checkOnly?: boolean } = {}) {
const serviceConfig = {
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
@@ -14,23 +18,155 @@ export async function handleUpdateCommand(runtime: CliRuntime) {
version: VERSION,
launcher: runtime.launcher
};
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
if (!isCompiledBinary()) {
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
runCommand("bun", ["install"], { cwd: runtime.appRoot });
if (wasRunning) await runServiceCommand("start", serviceConfig);
printJson({
updated: true,
serviceRestarted: wasRunning,
version: VERSION,
mode: "source"
});
return;
}
if (wasRunning) await runServiceCommand("start", serviceConfig);
// Standalone binary update
const currentPlatform = detectPlatformArch();
const updateInfo = await fetchLatestReleaseInfo();
if (!updateInfo) {
printJson({
updated: false,
version: VERSION,
mode: "binary",
message: "No update source configured or release server unreachable"
});
return;
}
if (isNewerVersion(updateInfo.version, VERSION)) {
if (options.checkOnly) {
printJson({
updated: false,
updateAvailable: true,
currentVersion: VERSION,
latestVersion: updateInfo.version,
downloadUrl: updateInfo.downloads[currentPlatform]?.url
});
return;
}
const downloadUrl = updateInfo.downloads[currentPlatform]?.url;
if (!downloadUrl) {
throw new Error(`No prebuilt binary available for platform: ${currentPlatform} in release ${updateInfo.version}`);
}
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
const tmpBinary = `${process.execPath}.tmp.${Date.now()}`;
const response = await fetch(downloadUrl);
if (!response.ok) {
throw new Error(`Failed to download binary update: ${response.status} ${response.statusText}`);
}
const buffer = Buffer.from(await response.arrayBuffer());
writeFileSync(tmpBinary, buffer);
chmodSync(tmpBinary, 0o755);
renameSync(tmpBinary, process.execPath);
if (wasRunning) await runServiceCommand("start", serviceConfig);
printJson({
updated: true,
fromVersion: VERSION,
toVersion: updateInfo.version,
serviceRestarted: wasRunning,
mode: "binary"
});
return;
}
printJson({
updated: true,
serviceRestarted: wasRunning,
version: VERSION
updated: false,
version: VERSION,
mode: "binary",
message: "seal-home is already up to date"
});
}
function detectPlatformArch(): string {
const platform = process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : "linux";
const arch = process.arch === "arm64" ? "arm64" : "x64";
return `${platform}-${arch}`;
}
type ReleaseInfo = {
version: string;
downloads: Record<string, { url: string; sha256?: string }>;
};
async function fetchLatestReleaseInfo(): Promise<ReleaseInfo | undefined> {
const customUrl = process.env[UPDATE_URL_ENV]?.trim();
if (customUrl) {
try {
const res = await fetch(customUrl);
if (res.ok) {
return (await res.json()) as ReleaseInfo;
}
} catch {
// ignore
}
}
// Fallback to GitHub API
try {
const res = await fetch(`https://api.github.com/repos/${DEFAULT_GITHUB_REPO}/releases/latest`, {
headers: {
"User-Agent": `seal-home/${VERSION}`
}
});
if (!res.ok) return undefined;
const json = (await res.json()) as {
tag_name?: string;
assets?: Array<{ name: string; browser_download_url: string }>;
};
const version = (json.tag_name ?? "").replace(/^v/, "");
if (!version) return undefined;
const downloads: Record<string, { url: string }> = {};
for (const asset of json.assets ?? []) {
for (const target of ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64", "windows-x64"]) {
if (asset.name.includes(target)) {
downloads[target] = { url: asset.browser_download_url };
}
}
}
return { version, downloads };
} catch {
return undefined;
}
}
function isNewerVersion(latest: string, current: string): boolean {
const lParts = latest.split(".").map(Number);
const cParts = current.split(".").map(Number);
for (let i = 0; i < Math.max(lParts.length, cParts.length); i++) {
const l = lParts[i] ?? 0;
const c = cParts[i] ?? 0;
if (l > c) return true;
if (l < c) return false;
}
return false;
}
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd,
+4 -2
View File
@@ -25,7 +25,7 @@ import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand } from "./commands/webhook.js";
import { selectCorp } from "./helpers.js";
import { parseArgs, stringOption } from "./parser.js";
import { booleanOption, parseArgs, stringOption } from "./parser.js";
import {
formatConsoleOutput,
joinOutput,
@@ -162,7 +162,9 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (area === "update") {
await handleUpdateCommand(runtime);
await handleUpdateCommand(runtime, {
checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"])
});
return;
}