/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Native runtime installation helpers. * * `bxc install --full` downloads prebuilt runtime libraries into the user's * BXC vendor directory. A source checkout may additionally build the Rust * workspace; it never installs compilers or package-manager dependencies * behind the user's back. */ import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { resolveBxcConfig } from "../config/resolve.ts"; import { NATIVE_DEPENDENCIES } from "./versions.ts"; export type NativeInstallStatus = | "installed" | "present" | "planned" | "skipped" | "failed" | "unsupported"; export interface NativeInstallResult { status: NativeInstallStatus; path?: string; reason?: string; } export interface NativeToolchainReport { cargo: string | null; rustup: string | null; zig: string | null; cmake: string | null; cxx: string | null; } type RustPlatform = { target: | "linux-x64" | "linux-arm64" | "darwin-x64" | "darwin-arm64" | "windows-x64"; archive: string; filenames: string[]; }; type CurlPlatform = { assetTarget: string; directory: string; filenames: string[]; }; const CURL_TAG = Bun.env.BXC_CURL_VERSION ?? NATIVE_DEPENDENCIES.curlImpersonateTag; function rustPlatform( platform: NodeJS.Platform = process.platform, arch: NodeJS.Architecture = process.arch, ): RustPlatform | null { if (platform === "linux" && arch === "x64") { return { target: "linux-x64", archive: "tar.gz", filenames: ["libbxc_rust_bridge.so"], }; } if (platform === "linux" && arch === "arm64") { return { target: "linux-arm64", archive: "tar.gz", filenames: ["libbxc_rust_bridge.so"], }; } if (platform === "darwin" && arch === "x64") { return { target: "darwin-x64", archive: "tar.gz", filenames: ["libbxc_rust_bridge.dylib"], }; } if (platform === "darwin" && arch === "arm64") { return { target: "darwin-arm64", archive: "tar.gz", filenames: ["libbxc_rust_bridge.dylib"], }; } if (platform === "win32" && arch === "x64") { return { target: "windows-x64", archive: "zip", filenames: ["bxc_rust_bridge.dll"], }; } return null; } export function detectCurlPlatform( platform: NodeJS.Platform = process.platform, arch: NodeJS.Architecture = process.arch, ): CurlPlatform | null { if (platform === "linux" && arch === "x64") { return { assetTarget: "x86_64-linux-gnu", directory: "linux-x64", filenames: [ "libcurl-impersonate.so.4.8.0", "libcurl-impersonate.so.4", "libcurl-impersonate.so", "libcurl-impersonate-chrome.so.4.8.0", "libcurl-impersonate-chrome.so.4", "libcurl-impersonate-chrome.so", ], }; } if (platform === "linux" && arch === "arm64") { return { assetTarget: "aarch64-linux-gnu", directory: "linux-arm64", filenames: [ "libcurl-impersonate.so.4.8.0", "libcurl-impersonate.so.4", "libcurl-impersonate.so", "libcurl-impersonate-chrome.so.4.8.0", "libcurl-impersonate-chrome.so.4", "libcurl-impersonate-chrome.so", ], }; } if (platform === "darwin" && arch === "x64") { return { assetTarget: "x86_64-macos", directory: "darwin-x64", filenames: [ "libcurl-impersonate.4.dylib", "libcurl-impersonate.dylib", "libcurl-impersonate-chrome.4.dylib", "libcurl-impersonate-chrome.dylib", ], }; } if (platform === "darwin" && arch === "arm64") { return { assetTarget: "arm64-macos", directory: "darwin-arm64", filenames: [ "libcurl-impersonate.4.dylib", "libcurl-impersonate.dylib", "libcurl-impersonate-chrome.4.dylib", "libcurl-impersonate-chrome.dylib", ], }; } if (platform === "win32" && arch === "x64") { return { assetTarget: "x86_64-win32", directory: "windows-x64", filenames: ["libcurl-impersonate.dll", "libcurl-impersonate-chrome.dll"], }; } if (platform === "win32" && arch === "arm64") { return { assetTarget: "arm64-win32", directory: "windows-arm64", filenames: ["libcurl-impersonate.dll", "libcurl-impersonate-chrome.dll"], }; } return null; } function findFile(root: string, names: readonly string[]): string | null { if (!existsSync(root)) return null; const wanted = new Set(names); const entries = readdirSync(root, { withFileTypes: true }); for (const entry of entries) { const path = join(root, entry.name); if (entry.isFile() && wanted.has(entry.name)) return path; if (entry.isDirectory()) { const nested = findFile(path, names); if (nested) return nested; } } return null; } async function runProcess( command: string, args: readonly string[], options: { cwd?: string } = {}, ): Promise<{ code: number; stdout: string }> { try { const proc = Bun.spawn([command, ...args], { cwd: options.cwd, stdout: "pipe", stderr: "pipe", windowsHide: true, }); const stdout = await new Response(proc.stdout).text(); const code = await proc.exited; return { code, stdout: stdout.trim() }; } catch { return { code: 127, stdout: "" }; } } async function streamToFile(url: string, destination: string): Promise { const response = await fetch(url, { headers: { "User-Agent": "bxc-native-installer" }, redirect: "follow", }); if (!response.ok || !response.body) { throw new Error(`HTTP ${response.status} downloading ${url}`); } mkdirSync(dirname(destination), { recursive: true }); const writer = Bun.file(destination).writer(); const reader = response.body.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) break; writer.write(value); } await writer.flush(); await writer.end(); } catch (error) { try { writer.end(); } catch { // Best effort: the partial file is removed by the caller. } throw error; } } /** Extract one of the archive formats published by the release workflow. */ async function extractArchive( archive: string, archiveName: string, destination: string, ): Promise { const isZip = archiveName.toLowerCase().endsWith(".zip"); const command = isZip ? process.platform === "win32" ? [ "powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "Expand-Archive -LiteralPath $args[0] -DestinationPath $args[1] -Force", archive, destination, ] : ["unzip", "-q", archive, "-d", destination] : ["tar", "-xzf", archive, "-C", destination]; const extracted = await runProcess(command[0]!, command.slice(1)); if (extracted.code !== 0) { throw new Error( `${isZip ? "archive" : "tar"} extraction failed (exit ${extracted.code})`, ); } } /** Return the path where the curl library is expected after installation. */ export function resolveCurlInstallPath( vendorDir: string, platform: NodeJS.Platform = process.platform, arch: NodeJS.Architecture = process.arch, ): string | null { const target = detectCurlPlatform(platform, arch); if (!target) return null; return join( vendorDir, "curl-impersonate", target.directory, target.filenames[0], ); } /** * Download and unpack the upstream prebuilt curl-impersonate library. * The archive is kept in a platform-specific directory so multiple BXC * installations can share one vendor root without overwriting each other. */ export async function installCurlImpersonate( dryRun = false, vendorDir = Bun.env.BXC_VENDOR_DIR ?? resolveBxcConfig().settings.vendorDir, ): Promise { const target = detectCurlPlatform(); if (!target) return { status: "unsupported", reason: "unsupported platform" }; const destinationDir = join(vendorDir, "curl-impersonate", target.directory); const existing = findFile(destinationDir, target.filenames); if (existing) return { status: "present", path: existing }; const archiveName = `libcurl-impersonate-${CURL_TAG}.${target.assetTarget}.tar.gz`; const url = Bun.env.BXC_CURL_DOWNLOAD_URL ?? `https://github.com/lexiforest/curl-impersonate/releases/download/${CURL_TAG}/${archiveName}`; if (dryRun) return { status: "planned", path: join(destinationDir, target.filenames[0]), }; const tempRoot = join(tmpdir(), `bxc-curl-${process.pid}-${Date.now()}`); const archive = join(tempRoot, archiveName); const extractRoot = join(tempRoot, "extract"); try { mkdirSync(extractRoot, { recursive: true }); await streamToFile(url, archive); await extractArchive(archive, archiveName, extractRoot); const library = findFile(extractRoot, target.filenames); if (!library) throw new Error( "archive contains no compatible libcurl-impersonate library", ); mkdirSync(destinationDir, { recursive: true }); // Copy the complete extracted library directory: the dynamic library may // need sibling support libraries shipped by the upstream archive. const sourceDir = dirname(library); for (const entry of readdirSync(sourceDir)) { cpSync(join(sourceDir, entry), join(destinationDir, entry), { recursive: true, force: true, }); } const installed = findFile(destinationDir, target.filenames); if (!installed) throw new Error("installed library could not be verified"); return { status: "installed", path: installed }; } catch (error) { return { status: "failed", reason: error instanceof Error ? error.message : String(error), }; } finally { rmSync(tempRoot, { recursive: true, force: true }); } } /** * Fetch the Rust bridge from the matching BXC release archive when the npm * package is not accompanied by the Rust workspace. Standalone executables * have embedded/adjacent assets and do not need this network fallback. */ export async function installRustBridge( dryRun = false, binDir = Bun.env.BXC_BIN_DIR ?? resolveBxcConfig().settings.binDir, repoRoot = join(import.meta.dir, "../.."), ): Promise { const target = rustPlatform(); if (!target) return { status: "unsupported", reason: "unsupported platform" }; const packagePath = join(repoRoot, "package.json"); if (!existsSync(packagePath)) { return { status: "skipped", reason: "standalone executable assets are already packaged", }; } let version: string | undefined; try { const packageJson = JSON.parse(await Bun.file(packagePath).text()) as { version?: string; }; version = packageJson.version; } catch { return { status: "failed", reason: "could not read package version" }; } if (!version) return { status: "failed", reason: "package version is missing" }; const archiveName = `bxc-${target.target}.${target.archive}`; const releaseTag = Bun.env.BXC_RELEASE_TAG ?? `v${version}`; const url = Bun.env.BXC_NATIVE_RELEASE_URL ?? `https://github.com/${Bun.env.BXC_RELEASE_REPO ?? "aphrody-code/bxc"}/releases/download/${releaseTag}/${archiveName}`; const destinationDir = join(binDir, "native"); const existing = findFile(destinationDir, target.filenames); if (existing) return { status: "present", path: existing }; if (dryRun) return { status: "planned", path: join(destinationDir, target.filenames[0]), }; const tempRoot = join(tmpdir(), `bxc-rust-${process.pid}-${Date.now()}`); const archive = join(tempRoot, archiveName); const extractRoot = join(tempRoot, "extract"); try { mkdirSync(extractRoot, { recursive: true }); await streamToFile(url, archive); await extractArchive(archive, archiveName, extractRoot); const library = findFile(extractRoot, target.filenames); if (!library) throw new Error("BXC release contains no Rust bridge for this platform"); mkdirSync(destinationDir, { recursive: true }); cpSync(library, join(destinationDir, target.filenames[0]), { force: true }); const installed = join(destinationDir, target.filenames[0]); if (!existsSync(installed)) throw new Error("Rust bridge could not be verified"); return { status: "installed", path: installed }; } catch (error) { return { status: "failed", reason: error instanceof Error ? error.message : String(error), }; } finally { rmSync(tempRoot, { recursive: true, force: true }); } } /** Probe the native build commands without changing the host installation. */ export async function inspectNativeToolchain(): Promise { const probes: Array<[keyof NativeToolchainReport, string, string[]]> = [ ["cargo", "cargo", ["--version"]], ["rustup", "rustup", ["--version"]], ["zig", "zig", ["version"]], ["cmake", "cmake", ["--version"]], ]; const report: NativeToolchainReport = { cargo: null, rustup: null, zig: null, cmake: null, cxx: null, }; for (const [key, command, args] of probes) { const result = await runProcess(command, args); if (result.code === 0) report[key] = result.stdout.split(/\r?\n/, 1)[0] ?? null; } for (const command of process.platform === "win32" ? ["cl"] : ["c++", "clang++"]) { const result = await runProcess(command, ["--version"]); if (result.code === 0) { report.cxx = result.stdout.split(/\r?\n/, 1)[0] ?? command; break; } } return report; } /** Build the Rust native workspace when running from the source repository. */ export async function buildRustWorkspace( dryRun = false, repoRoot = join(import.meta.dir, "../.."), ): Promise { const manifest = join(repoRoot, "rust-bridge", "Cargo.toml"); if (!existsSync(manifest)) { return { status: "skipped", reason: "Rust workspace is not included in this package", }; } if (dryRun) { return { status: "planned", path: join(repoRoot, "rust-bridge", "target", "release"), }; } const result = await runProcess( "cargo", ["build", "--release", "--workspace", "--locked"], { cwd: join(repoRoot, "rust-bridge"), }, ); if (result.code !== 0) { return { status: "failed", reason: `cargo build failed (exit ${result.code})`, }; } return { status: "installed", path: join(repoRoot, "rust-bridge", "target", "release"), }; }