Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/4525.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Windows development and renderer scripts can use Bun installed through npm (#4525) — thanks @oseunabel62-tech!
1 change: 1 addition & 0 deletions docs/install/windows.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ Prerequisites:

- **Git for Windows** — `winget install --id Git.Git -e`.
- **Bun** — `powershell -c "irm bun.sh/install.ps1 | iex"`.
You can also install Bun with `npm install -g bun`. Open a new terminal and check `bun --version` before running the development or renderer scripts.
- **uv** — `powershell -c "irm https://astral.sh/uv/install.ps1 | iex"` (it
provides the managed Python 3.11 the backend uses).
- **Node.js 22.12.0 or newer** (a current LTS release is recommended). Source
Expand Down
44 changes: 44 additions & 0 deletions electron/scripts/bun-command.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { statSync } from 'node:fs';
import { basename, dirname, isAbsolute, join } from 'node:path';

function isFile(file) {
try {
return statSync(file, { throwIfNoEntry: false })?.isFile() ?? false;
} catch {
// PATH can include inaccessible directories before the working install.
return false;
}
}

/**
* 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`. An
* npm-installed Bun puts only `bun.cmd`/`bun.ps1` shims on PATH, and the spawn
* fails with ENOENT. `bun run` exports its own binary as `npm_execpath`, so the
* running Bun is used whenever a script was started through it.
*/
export function bunCommand({
env = process.env,
versions = process.versions,
execPath = process.execPath,
} = {}) {
if (versions.bun) return execPath;
const runner = String(env.npm_execpath ?? '').trim();
const name = runner.split(/[\\/]/).pop() ?? '';
if (/^bun(\.exe)?$/i.test(name)) return runner;
// Direct Node and npm launches have no Bun runner in npm_execpath.
if (process.platform === 'win32') {
for (const entry of (env.Path ?? env.PATH ?? '').split(';')) {
const dir = entry.trim().replace(/^"(.*)"$/, '$1');
if (!isAbsolute(dir)) continue;
const native = join(dir, 'bun.exe');
if (isFile(native)) return native;
if (!isFile(join(dir, 'bun.cmd'))) continue;
const modules = basename(dir).toLowerCase() === '.bin' ? dirname(dir) : join(dir, 'node_modules');
const npmBun = join(modules, 'bun', 'bin', 'bun.exe');
if (isFile(npmBun)) return npmBun;
}
}
return 'bun';
}
3 changes: 2 additions & 1 deletion scripts/electron-smoke-test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { spawnSync } from 'node:child_process';
import process from 'node:process';
import { bunCommand } from '../electron/scripts/bun-command.mjs';

function run(command, args) {
console.log(`\n> ${command} ${args.join(' ')}`);
Expand All @@ -16,7 +17,7 @@ function run(command, args) {
const args = process.argv.slice(2);

if (!args.includes('--skip-build')) {
run('bun', ['run', '--cwd', 'electron', 'dist:dir']);
run(bunCommand(), ['run', '--cwd', 'electron', 'dist:dir']);
}

const testArgs = args.filter((arg) => arg !== '--skip-build');
Expand Down
5 changes: 3 additions & 2 deletions scripts/perf/renderer-baseline.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:f
import { tmpdir } from 'node:os';
import { join, relative, resolve } from 'node:path';
import { gzipSync } from 'node:zlib';
import { bunCommand } from '../../electron/scripts/bun-command.mjs';

const repo = resolve(import.meta.dirname, '../..');
const electron = join(repo, 'electron');
Expand All @@ -17,8 +18,8 @@ const out = mkdtempSync(join(tmpdir(), 'vs-perf-'));
process.on('exit', () => rmSync(out, { recursive: true, force: true }));

execFileSync(
'bunx',
['vite', 'build', '--config', 'vite.web.config.ts', '--outDir', out, '--emptyOutDir'],
bunCommand(),
['x', 'vite', 'build', '--config', 'vite.web.config.ts', '--outDir', out, '--emptyOutDir'],
{ cwd: electron, stdio: 'ignore' },
);

Expand Down
8 changes: 7 additions & 1 deletion scripts/prepare-dev.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { bunCommand } from "../electron/scripts/bun-command.mjs";
import { assertSupportedNode } from "../electron/scripts/node-version.mjs";

const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
Expand All @@ -23,6 +24,7 @@ export function prepareDev({
arch = process.arch,
run = spawnSync,
log = console.log,
bun = bunCommand({ env }),
} = {}) {
assertSupportedNode(nodeVersion);
const commands = [["install"]];
Expand All @@ -33,7 +35,11 @@ export function prepareDev({
}

for (const args of commands) {
const result = run("bun", args, { cwd: root, env, stdio: "inherit" });
const result = run(bun, args, { cwd: root, env, stdio: "inherit" });
if (result.error?.code === "ENOENT")
throw new Error(
"Bun was not found. Install it from https://bun.sh, reopen your terminal, and run the command again.",
);
if (result.error) throw result.error;
if (result.status !== 0) return result.status ?? 1;
}
Expand Down
97 changes: 97 additions & 0 deletions tests/frontend/bunCommand.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";

import { bunCommand } from "../../electron/scripts/bun-command.mjs";
import { prepareDev } from "../../scripts/prepare-dev.mjs";

const npmBun = "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\bun\\bin\\bun.exe";

test("scripts started by bun run spawn that Bun, not the PATH shim", () => {
assert.equal(bunCommand({ env: { npm_execpath: npmBun }, versions: {} }), npmBun);
assert.equal(
bunCommand({ env: { npm_execpath: "/home/me/.bun/bin/bun" }, versions: {} }),
"/home/me/.bun/bin/bun",
);
});

test("a script running inside Bun spawns its own executable", () => {
assert.equal(bunCommand({ env: {}, versions: { bun: "1.4.2" }, execPath: npmBun }), npmBun);
});

test("direct Node finds the native Bun behind Windows npm shims in PATH order", { skip: process.platform !== "win32" }, (t) => {
const root = mkdtempSync(join(tmpdir(), "bun command "));
t.after(() => rmSync(root, { recursive: true, force: true }));
const globalPrefix = join(root, "global prefix");
const modules = join(root, "local project", "node_modules");
const localBin = join(modules, ".bin");
const nativeBin = join(root, "standalone");
const globalExe = join(globalPrefix, "node_modules", "bun", "bin", "bun.exe");
const localExe = join(modules, "bun", "bin", "bun.exe");
for (const file of [globalExe, localExe, join(localBin, "bun.cmd"), join(globalPrefix, "bun.cmd"), join(nativeBin, "bun.exe")]) {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, "");
}
const resolveBun = (...dirs) => bunCommand({ env: { Path: dirs.join(";") }, versions: {} });
assert.equal(resolveBun(globalPrefix, nativeBin), globalExe);
assert.equal(resolveBun(localBin, globalPrefix), localExe);
assert.equal(resolveBun(nativeBin, globalPrefix), join(nativeBin, "bun.exe"));
});

test("other package runners and direct node launches fall back to PATH", () => {
for (const npm_execpath of [
undefined,
"",
"C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
"/usr/lib/node_modules/pnpm/bin/pnpm.cjs",
"C:\\bun\\bunx.exe",
]) {
assert.equal(bunCommand({ env: { npm_execpath }, versions: {} }), "bun");
}
});

test("dev setup runs the Bun that started it", () => {
const calls = [];
prepareDev({
env: { npm_execpath: npmBun },
platform: "linux",
arch: "x64",
run(command, args) {
calls.push([command, ...args]);
return { status: 0 };
},
});
assert.deepEqual(calls, [
[npmBun, "install"],
[npmBun, "run", "setup:api"],
]);
});

test("a missing Bun explains how to install it", () => {
const error = Object.assign(new Error("spawnSync bun ENOENT"), { code: "ENOENT" });
assert.throws(
() => prepareDev({ env: {}, platform: "linux", arch: "x64", run: () => ({ error }) }),
/Bun was not found\. Install it from https:\/\/bun\.sh/,
);
});

test("no script spawns a bare bun or bunx", () => {
const root = fileURLToPath(new URL("../../", import.meta.url));
const bare = /\b(?:spawn|spawnSync|execFile|execFileSync|run)\(\s*['"]bunx?['"]/;
const offenders = [];
const walk = (dir) => {
for (const entry of readdirSync(join(root, dir), { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name !== "node_modules") walk(path);
} else if (/\.(?:mjs|cjs|js|ts)$/.test(entry.name) && !/\.test\./.test(entry.name)) {
if (bare.test(readFileSync(join(root, path), "utf8"))) offenders.push(path);
}
}
};
for (const dir of ["scripts", "electron/scripts"]) walk(dir);
assert.deepEqual(offenders, [], "spawn bunCommand() from electron/scripts/bun-command.mjs");
});