import { statSync } from 'node:fs'; import { win32 } from 'node:path'; export const BUN_MISSING_MESSAGE = 'Bun was not found. Install it from https://bun.sh (or `npm install -g bun`), reopen your terminal, and run the command again.'; function isFile(file) { try { return statSync(file, { throwIfNoEntry: false })?.isFile() ?? false; } catch { // PATH can list directories this user cannot read ahead of the working install. return false; } } function pathEntries(env) { // A plain env copy keeps Windows' `Path` spelling but is case-sensitive. const key = Object.keys(env).find((name) => name.toLowerCase() === 'path'); return String(key ? env[key] : '') .split(';') .map((entry) => entry.trim().replace(/^"(.*)"$/, '$1')) .filter((dir) => win32.isAbsolute(dir)); } /** The real bun.exe behind PATH, skipping the .cmd/.ps1 shims `spawn` cannot run. */ function findWindowsBun(env, exists) { for (const dir of pathEntries(env)) { const native = win32.join(dir, 'bun.exe'); if (exists(native)) return native; if (!exists(win32.join(dir, 'bun.cmd'))) continue; // npm puts the shims in the prefix (global) or in node_modules/.bin (local); // the executable lives in the `bun` package next to them. const modules = win32.basename(dir).toLowerCase() === '.bin' ? win32.dirname(dir) : win32.join(dir, 'node_modules'); const npmBun = win32.join(modules, 'bun', 'bin', 'bun.exe'); if (exists(npmBun)) return npmBun; } return undefined; } /** * The Bun executable a script should spawn for a child `bun` command. * * `spawn` runs no shell, so on Windows a bare "bun" only finds `bun.exe`, while * an npm-installed Bun puts only `bun.cmd`/`bun.ps1` shims on PATH and the spawn * fails with ENOENT. Preference order: the Bun running this script, the Bun that * `bun run` exports as `npm_execpath`, the real executable behind a Windows PATH * shim, then a bare `bun` for the platform's own lookup. */ export function bunCommand({ env = process.env, versions = process.versions, execPath = process.execPath, platform = process.platform, exists = isFile, } = {}) { if (versions.bun) return execPath; const runner = String(env.npm_execpath ?? '').trim(); if (/^bun(\.exe)?$/i.test(runner.split(/[\\/]/).pop() ?? '')) return runner; if (platform === 'win32') return findWindowsBun(env, exists) ?? 'bun'; return 'bun'; } /** Replace a raw `spawn bun ENOENT` with an install hint; pass other errors through. */ export function explainBunError(error) { return error?.code === 'ENOENT' ? new Error(BUN_MISSING_MESSAGE, { cause: error }) : error; }