#!/usr/bin/env bun /** * 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. */ /** * Bxc postinstall — auto-download Lightpanda, with an explicit full-native mode. * * Behavior : * - Detects platform from process.platform + process.arch * - If binary already exists in vendor/lightpanda-bin//lightpanda → skip * - Otherwise fetches latest GitHub release asset matching the platform, streams to disk via Bun.file().writer() * - Idempotent : safe to re-run (skips when file already on disk and non-zero size) * - Never blocks install : on any failure (network, unsupported platform, write error) logs a warning and exits 0 * * Opt-out env vars : * - BXC_NO_AUTOINSTALL=1 → skip entirely (user opt-out) * - CI=1 → skip unless LIGHTPANDA_AUTOINSTALL=1 (CI environments often have caches) * - BXC_INSTALL_FULL=1 → also install the Rust bridge + curl-impersonate * * Override env vars : * - LIGHTPANDA_RELEASE_TAG → fetch a specific release tag instead of "latest" (defaults to "nightly" upstream) * - LIGHTPANDA_DOWNLOAD_URL → override asset URL entirely * - BXC_VENDOR_DIR → override target dir (default vendor/lightpanda-bin) * * Bun-native APIs only : Bun.file, Bun.write, Bun.$, fetch. */ import { chmodSync, existsSync, mkdirSync, renameSync } from "node:fs"; import { dirname, join } from "node:path"; import { buildRustWorkspace, installCurlImpersonate, installRustBridge, } from "../src/native/install.ts"; import { resolveBxcConfig } from "../src/config/resolve.ts"; type LightpandaPlatform = | "x86_64-linux" | "aarch64-linux" | "x86_64-macos" | "aarch64-macos" | "x86_64-windows"; type DetectedPlatform = { id: LightpandaPlatform; dirName: | "linux-x64" | "linux-arm64" | "darwin-x64" | "darwin-arm64" | "windows-x64"; assetName: string; }; const TAG = Bun.env.LIGHTPANDA_RELEASE_TAG ?? "nightly"; const VENDOR_DIR_ENV = Bun.env.BXC_VENDOR_DIR; /** * Detect the current platform mapping. * Returns null if the platform is unsupported. */ export function detectPlatform( platform: NodeJS.Platform = process.platform, arch: NodeJS.Architecture = process.arch, ): DetectedPlatform | null { if (platform === "linux") { if (arch === "x64") { return { id: "x86_64-linux", dirName: "linux-x64", assetName: "lightpanda-x86_64-linux", }; } if (arch === "arm64") { return { id: "aarch64-linux", dirName: "linux-arm64", assetName: "lightpanda-aarch64-linux", }; } return null; } if (platform === "darwin") { if (arch === "x64") { return { id: "x86_64-macos", dirName: "darwin-x64", assetName: "lightpanda-x86_64-macos", }; } if (arch === "arm64") { return { id: "aarch64-macos", dirName: "darwin-arm64", assetName: "lightpanda-aarch64-macos", }; } return null; } if (platform === "win32") { if (arch === "x64") { return { id: "x86_64-windows", dirName: "windows-x64", assetName: "lightpanda-x86_64-windows.exe", }; } return null; } return null; } /** * Decide whether the postinstall should run. * Returns a reason string if it should skip, or null if it should proceed. * * The hook is wired in `package.json` so that **consumers** of the npm package * get a browser without a second command. It must stay out of the way of the * source checkout: a normal `bun install` in this repository would otherwise * start downloading a browser binary as a side effect. A `.git` directory * next to the script is the signal — `LIGHTPANDA_AUTOINSTALL=1` or the * explicit `BXC_INSTALL_FULL=1` overrides it. */ export function shouldSkip( env: Record = Bun.env as Record< string, string | undefined >, exists: (path: string) => boolean = existsSync, rootDir: string = join(import.meta.dir, ".."), ): string | null { if (env.BXC_NO_AUTOINSTALL === "1") { return "BXC_NO_AUTOINSTALL=1 (user opt-out)"; } if ( env.CI === "1" && env.LIGHTPANDA_AUTOINSTALL !== "1" && env.BXC_INSTALL_FULL !== "1" ) { return "CI=1 detected and explicit native install was not requested (CI cache assumed)"; } if ( env.LIGHTPANDA_AUTOINSTALL !== "1" && env.BXC_INSTALL_FULL !== "1" && exists(join(rootDir, ".git")) ) { return "source checkout detected (.git present) — run `bxc install` explicitly"; } return null; } /** * Resolve the absolute target path for the Lightpanda binary. */ export function resolveTargetPath( platform: DetectedPlatform, rootDir: string = import.meta.dir, vendorOverride: string | undefined = VENDOR_DIR_ENV, ): string { const baseDir = vendorOverride ? join(vendorOverride, "lightpanda-bin") : join(rootDir, "..", "vendor", "lightpanda-bin"); const ext = platform.id.includes("windows") ? ".exe" : ""; return join(baseDir, platform.dirName, `lightpanda${ext}`); } function fmtMB(bytes: number): string { return `${(bytes / 1024 / 1024).toFixed(1)} MB`; } function log(msg: string): void { console.log(`[bxc postinstall] ${msg}`); } function warn(msg: string): void { console.warn(`[bxc postinstall] WARNING : ${msg}`); } /** * Fetch the GitHub release manifest for a given tag. * Returns the asset that matches the platform's assetName, or null on any error. */ async function fetchReleaseAsset( platform: DetectedPlatform, tag: string, ): Promise<{ url: string; size: number } | null> { const overrideUrl = Bun.env.LIGHTPANDA_DOWNLOAD_URL; if (overrideUrl) { return { url: overrideUrl, size: 0 }; } const apiUrl = `https://api.github.com/repos/lightpanda-io/browser/releases/tags/${encodeURIComponent(tag)}`; const res = await fetch(apiUrl, { headers: { "User-Agent": "bxc-postinstall", Accept: "application/vnd.github+json", }, }); if (!res.ok) { warn(`GitHub API ${apiUrl} → HTTP ${res.status}`); return null; } const body = (await res.json()) as { assets?: Array<{ name: string; size: number; browser_download_url: string; }>; }; const asset = body.assets?.find((a) => a.name === platform.assetName); if (!asset) { warn( `No asset named '${platform.assetName}' in release '${tag}' (assets present : ${body.assets?.map((a) => a.name).join(", ") ?? "none"})`, ); return null; } return { url: asset.browser_download_url, size: asset.size }; } /** * Stream-download a URL into a target file via Bun.file().writer(). * Writes to .partial first, then atomic-renames to target. */ async function streamDownload( url: string, targetPath: string, expectedSize: number, ): Promise<{ written: number }> { const partial = `${targetPath}.partial`; // `dirname` supporte `C:\\…` ; `lastIndexOf("/")` renvoyait -1 sous Windows. mkdirSync(dirname(targetPath), { recursive: true }); const res = await fetch(url, { headers: { "User-Agent": "bxc-postinstall" }, redirect: "follow", }); if (!res.ok || !res.body) { throw new Error(`download failed : HTTP ${res.status} for ${url}`); } const writer = Bun.file(partial).writer(); let written = 0; const reader = res.body.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) break; writer.write(value); written += value.byteLength; } await writer.flush(); await writer.end(); } catch (err) { try { writer.end(); } catch { // ignore — best-effort cleanup } throw err; } if (expectedSize > 0 && written !== expectedSize) { throw new Error( `size mismatch : expected ${expectedSize} bytes, got ${written}`, ); } renameSync(partial, targetPath); return { written }; } /** * Run the postinstall flow. Always resolves (never throws) — exit code is always 0 * to avoid breaking `bun install` on transient errors. */ export async function runPostinstall( rootDir: string = import.meta.dir, ): Promise<{ status: "skipped" | "downloaded" | "present" | "failed"; reason?: string; path?: string; }> { const skipReason = shouldSkip(); if (skipReason !== null) { log(`skipping : ${skipReason}`); return { status: "skipped", reason: skipReason }; } const platform = detectPlatform(); if (!platform) { warn( `unsupported platform ${process.platform}/${process.arch} — Lightpanda is currently published for linux x64/arm64 and darwin x64/arm64 only. Falling back to manual install.`, ); return { status: "skipped", reason: `unsupported platform ${process.platform}/${process.arch}`, }; } const targetPath = resolveTargetPath(platform, rootDir); const existing = Bun.file(targetPath); if (await existing.exists()) { const size = existing.size; if (size > 0) { log( `already present : ${targetPath} (${fmtMB(size)}) — skipping download`, ); return { status: "present", path: targetPath }; } warn(`existing file is empty, re-downloading : ${targetPath}`); } log( `detected ${platform.dirName} (${platform.id}), looking up release '${TAG}'`, ); const asset = await fetchReleaseAsset(platform, TAG); if (!asset) { warn( `could not resolve release asset — manual install required : https://github.com/lightpanda-io/browser/releases`, ); return { status: "failed", reason: "release asset lookup failed" }; } log( `downloading ${asset.url} → ${targetPath}${asset.size ? ` (${fmtMB(asset.size)})` : ""}`, ); try { const { written } = await streamDownload(asset.url, targetPath, asset.size); // `chmod` n'est pas un builtin du shell Bun et n'existe pas sous Windows. if (process.platform !== "win32") chmodSync(targetPath, 0o755); log(`installed lightpanda binary : ${targetPath} (${fmtMB(written)})`); return { status: "downloaded", path: targetPath }; } catch (err) { warn( `download failed : ${err instanceof Error ? err.message : String(err)}. Manual install : https://github.com/lightpanda-io/browser/releases`, ); return { status: "failed", reason: err instanceof Error ? err.message : String(err), }; } } // --------------------------------------------------------------------------- // Extended profile install via BXC_INSTALL_PROFILES env var // --------------------------------------------------------------------------- /** * Parse the BXC_INSTALL_PROFILES env var and run additional installs. * * Supported values (comma-separated) : * stealth — install Chrome for Testing (required by profile=stealth) * max — install Camoufox v135 (required by profile=max) * all — both of the above * * This runs after the standard Lightpanda install. * Always resolves — never throws — does not affect the exit code. * * Requires BXC_NO_PROMPT=1 or non-interactive stdin because postinstall * cannot prompt the user interactively. If prompt suppression is not set and * "max" is requested, the install is skipped with a warning. */ if (import.meta.main) { // Hard guard : a postinstall must NEVER break `bun install` / `bun update`, // even on a module-load throw or an unexpected rejection. Any error here is // logged and swallowed — exit code is unconditionally 0. try { await runPostinstall(); if ( Bun.env.BXC_INSTALL_FULL === "1" && Bun.env.BXC_NO_AUTOINSTALL !== "1" ) { const packageRoot = join(import.meta.dir, ".."); const rustBuild = await buildRustWorkspace(false, packageRoot); const rust = rustBuild.status === "skipped" ? await installRustBridge( false, Bun.env.BXC_BIN_DIR ?? resolveBxcConfig().settings.binDir, packageRoot, ) : rustBuild; log(`full install: Rust bridge ${rust.status}${rust.path ? ` at ${rust.path}` : ""}`); if (rust.status === "failed") warn(rust.reason ?? "Rust bridge installation failed"); // Full installs belong to the user's BXC data directory. Writing into // the package's own vendor/ tree breaks read-only npm installs and is // lost on every package upgrade. const vendorDir = Bun.env.BXC_VENDOR_DIR ?? resolveBxcConfig().settings.vendorDir; const curl = await installCurlImpersonate(false, vendorDir); log(`full install: curl-impersonate ${curl.status}${curl.path ? ` at ${curl.path}` : ""}`); if (curl.status === "failed") warn(curl.reason ?? "curl-impersonate installation failed"); } } catch (err) { warn( `postinstall aborted (non-fatal) : ${err instanceof Error ? err.message : String(err)}`, ); } process.exit(0); }