import { createHash } from "node:crypto"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; import { parseArgs } from "node:util"; import { RELEASE_TARGETS as targets } from "./release-config.js"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); const { values } = parseArgs({ options: { all: { type: "boolean" }, target: { type: "string" }, outdir: { type: "string", default: "dist" }, help: { type: "boolean", short: "h" }, } }); if (values.help) { console.log(`usage: bun run build [--all | --target ] [--outdir ]\nplatforms: ${targets.join(", ")}\nDefault: build and smoke-test the current platform. Requires tar.`); process.exit(0); } if (values.all && values.target) throw new Error("choose --all or --target, not both"); const nativeTarget = `${process.platform}-${process.arch}`; const selected = values.all ? targets : [values.target ?? nativeTarget]; for (const target of selected) { if (!targets.includes(target)) throw new Error(`unsupported platform: ${target}`); } const bunVersion = pkg.packageManager.slice(4); if (process.versions.bun !== bunVersion) throw new Error(`builds require Bun ${bunVersion}; found ${process.versions.bun ?? "Node.js"}`); const outdir = resolve(root, values.outdir); await mkdir(outdir, { recursive: true }); function run(command, args, options = {}) { const result = spawnSync(command, args, { cwd: root, stdio: "inherit", ...options }); if (result.error) throw result.error; if (result.status !== 0) throw new Error(`${command} failed (${result.signal ?? result.status})`); return result.stdout; } const sums = []; for (const target of selected) { const directory = join(outdir, target); await mkdir(directory, { recursive: true }); const name = target.startsWith("windows-") ? "mbr.exe" : "mbr"; const binary = join(directory, name); run(process.execPath, ["build", "index.js", "--compile", "--minify", "--sourcemap", "--no-compile-autoload-dotenv", "--no-compile-autoload-bunfig", `--target=bun-${target}`, "--outfile", binary]); if (target === nativeTarget) { const version = run(binary, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }); if (version.trim() !== `mbr ${pkg.version}`) throw new Error("compiled version does not match package.json"); run(binary, ["--help"]); } const archive = `mbr-v${pkg.version}-${target}.tar.gz`; run("tar", ["-czf", join(outdir, archive), "-C", directory, name]); sums.push(`${createHash("sha256").update(await readFile(join(outdir, archive))).digest("hex")} ${archive}`); console.log(`built ${archive}`); } await writeFile(join(outdir, "SHA256SUMS"), `${sums.join("\n")}\n`);