Skip to content
Closed
7 changes: 3 additions & 4 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3287,10 +3287,7 @@ pub struct Options {
// forward-dep crate; callers pass it as the resolver's trait object so
// both VM and resolver can hold it without the cycle.
pub graph: Option<&'static dyn bun_resolver::StandaloneModuleGraph>,
// Note: debugger
// configuration is plumbed through `RuntimeHooks::ensure_debugger` (the
// CLI option struct lives in `bun_cli`, a forward dep). See
// `runtime/jsc_hooks.rs` for the `configureDebugger` call site.
pub debugger: bun_options_types::context::Debugger,
pub is_main_thread: bool,
}

Expand Down Expand Up @@ -4051,6 +4048,7 @@ impl VirtualMachine {
let graph = opts.graph.expect("init_with_module_graph requires graph");
let init_opts = InitOptions {
transform_options: opts.args,
debugger: opts.debugger,
graph: Some(graph),
log: opts.log,
env_loader: opts.env_loader,
Expand All @@ -4063,6 +4061,7 @@ impl VirtualMachine {
let vm = Self::init(init_opts)?;
// SAFETY: `vm` is the unique live VM on this thread.
let vm_ref = unsafe { &mut *vm };
vm_ref.dns_result_order = opts.dns_result_order;
vm_ref.transpiler.resolver.standalone_module_graph = Some(graph);
vm_ref.install_bytecode_string_table(graph);
// Avoid reading from tsconfig.json & package.json when in standalone mode
Expand Down
1 change: 1 addition & 0 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1157,6 +1157,7 @@ Full documentation is available at <magenta>https://bun.com/docs/cli/run<r>
graph: Some(graph_dyn),
is_main_thread: true,
smol: ctx.runtime_options.smol,
debugger: ::core::mem::take(&mut ctx.runtime_options.debugger),
// `Options::dns_result_order` is `u8` until the
// b2-cycle widens it to `bun_dns::Order`; the enum is
// `#[repr(u8)]` so `as u8` is exact.
Expand Down
182 changes: 181 additions & 1 deletion test/bundler/compile-argv.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { describe, expect } from "bun:test";
import type { Subprocess } from "bun";
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isCI, isWindows, tempDir } from "harness";
import { join } from "node:path";
import { itBundled } from "./expectBundled";

// `BUN_JSC_dumpOptions=2` prints every JSC option as ` name=value` on stderr
Expand Down Expand Up @@ -452,3 +455,180 @@ describe("bundler", () => {
},
});
});

// The standalone boot path parses exec argv into the CLI context and then
// builds the VM through `init_with_module_graph`. Flags that only the VM acts
// on (the inspector, the DNS result order) must survive that hand-off, not
// just show up in `process.execArgv`.
describe("compile-exec-argv runtime flags reach the VM", () => {
// Each test rewrites a whole executable (the debug binary is ~800 MB), so
// give them the budget `itBundled` gives its compile tests.
const compileTest = (name: string, fn: () => Promise<void>) => test.concurrent(name, fn, isCI ? undefined : 30_000);

// Where the flags come from: baked into the executable, or the environment.
const sources = [
["--compile-exec-argv", (flags: readonly string[]) => ({ execArgv: flags, env: {} })],
["BUN_OPTIONS", (flags: readonly string[]) => ({ execArgv: [], env: { BUN_OPTIONS: flags.join(" ") } })],
] as const;

async function waitForInspectorUrl(stderr: ReadableStream<Uint8Array>): Promise<URL> {
const reader = stderr.getReader();
const decoder = new TextDecoder();
let text = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
text += decoder.decode(value, { stream: true });
const match = text.match(/^\s*(ws:\/\/\S+)\n/m);
if (match) {
// Keep draining so the child never blocks on a full stderr pipe.
void (async () => {
while (!(await reader.read()).done) {}
})();
return new URL(match[1]);
}
}
throw new Error(`inspector did not start. stderr:\n${text}`);
}

async function readLine(stdout: ReadableStream<Uint8Array>): Promise<string> {
const reader = stdout.getReader();
const decoder = new TextDecoder();
let text = "";
while (!text.includes("\n")) {
const { value, done } = await reader.read();
if (done) break;
text += decoder.decode(value, { stream: true });
}
reader.releaseLock();
return text;
}

async function compile(dir: string, execArgv: readonly string[]): Promise<string> {
const exe = join(dir, isWindows ? "app.exe" : "app");
await using build = Bun.spawn({
cmd: [
bunExe(),
"build",
"--compile",
...(execArgv.length ? [`--compile-exec-argv=${execArgv.join(" ")}`] : []),
"--outfile",
exe,
"entry.js",
],
cwd: dir,
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [, buildStderr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]);
expect(buildStderr).not.toContain("error");
expect(buildExit).toBe(0);
return exe;
}

// Opens a session on the inspectee. A dropped socket or a dead inspectee
// rejects whatever is awaited instead of leaving it to the test timeout.
async function connectInspector(proc: Subprocess, url: URL) {
const ws = new WebSocket(url.href);
const failed = Promise.withResolvers<never>();
failed.promise.catch(() => {});
ws.onerror = event => failed.reject(new Error("WebSocket error", { cause: event }));
ws.onclose = event => failed.reject(new Error(`WebSocket closed (${event.code})`));
proc.exited.then(code => failed.reject(new Error(`inspectee exited (${code}) before the inspector answered`)));

const opened = Promise.withResolvers<void>();
ws.onopen = () => opened.resolve();
await Promise.race([opened.promise, failed.promise]);

const pending = new Map<number, (reply: unknown) => void>();
ws.onmessage = event => {
const message = JSON.parse(String(event.data));
pending.get(message.id)?.(message);
};
let nextId = 1;
return {
request(method: string, params: Record<string, unknown> = {}): Promise<unknown> {
const id = nextId++;
const reply = Promise.withResolvers<unknown>();
pending.set(id, reply.resolve);
ws.send(JSON.stringify({ id, method, params }));
return Promise.race([reply.promise, failed.promise]);
},
close: () => ws.close(),
};
}

for (const [source, via] of sources) {
// `--inspect-wait` blocks the program until a client sends
// `Inspector.initialized`, so the shape is deterministic either way: the
// fixed binary prints the listening URL and waits, a binary that drops the
// flag runs to completion and its stderr ends without a URL.
compileTest(`--inspect-wait and --dns-result-order from ${source}`, async () => {
const flags = ["--inspect-wait=127.0.0.1:0", "--dns-result-order=ipv4first"];
const { execArgv, env } = via(flags);
using dir = tempDir("compile-exec-argv-vm-flags", {
"entry.js": /* js */ `
const dns = require("node:dns");
console.log(JSON.stringify({ execArgv: process.execArgv, dnsOrder: dns.getDefaultResultOrder() }));
`,
});
const exe = await compile(String(dir), execArgv);

await using proc = Bun.spawn({
cmd: [exe],
env: { ...bunEnv, ...env },
stdout: "pipe",
stderr: "pipe",
});
const url = await waitForInspectorUrl(proc.stderr);
expect(url.hostname).toBe("127.0.0.1");

const inspector = await connectInspector(proc, url);
// Releases the wait. The program runs to its end, and the connected
// client keeps the process alive for the evaluation.
expect(await inspector.request("Inspector.initialized")).toEqual({ id: 1, result: {} });
expect(await inspector.request("Runtime.evaluate", { expression: "1 + 1" })).toMatchObject({
id: 2,
result: { result: { type: "number", value: 2 } },
});
inspector.close();

const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]);
expect(JSON.parse(stdout)).toEqual({ execArgv: flags, dnsOrder: "ipv4first" });
expect(exitCode).toBe(0);
});

// Plain `--inspect` must not block the program. The inspectee holds itself
// open long enough for the client to connect; a connected client then keeps
// the process alive. When the flag is dropped that timer is all that is
// pending, so the process exits on its own and stderr ends without a URL.
compileTest(`--inspect from ${source} starts the inspector without blocking the program`, async () => {
const { execArgv, env } = via(["--inspect=127.0.0.1:0"]);
using dir = tempDir("compile-exec-argv-inspect", {
"entry.js": /* js */ `
console.log("started");
setTimeout(() => {}, 10_000);
`,
});
const exe = await compile(String(dir), execArgv);

await using proc = Bun.spawn({
cmd: [exe],
env: { ...bunEnv, ...env },
stdout: "pipe",
stderr: "pipe",
});
// The program runs before any client connects.
expect(await readLine(proc.stdout)).toBe("started\n");

const url = await waitForInspectorUrl(proc.stderr);
const inspector = await connectInspector(proc, url);
expect(await inspector.request("Runtime.evaluate", { expression: "1 + 1" })).toMatchObject({
id: 1,
result: { result: { type: "number", value: 2 } },
});
inspector.close();
});
}
});
Loading