bun_runtime 0.2.3

Bao runtime integration — JS engine + Bun API + event loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// @trace REQ-ENG-006 REQ-CLI-001 [entity:BaoRuntime]
// @trace REQ-CLI-001: bao CLI entry point and runtime initialization
use bao_engine::context::{JsContext, SmRuntimeGuard};
use bao_engine::error::JsError;
use bao_engine::execution_control::ExecutionControl;
// Re-export for the CLI-side terminal-state → exit-code mapping (#24 S1 CLI
// wiring). Internal experimental surface — NOT a stable API commitment.
#[doc(hidden)]
pub use bao_engine::execution_control::TerminalState;
use bao_engine::module_loader::ModuleLoader;
use bao_engine::value::JsValue;
use mozjs::realm::AutoRealm;
use mozjs::rooted;

use crate::globals;
use crate::require;

// ── B1 runtime resource cleanup (BUN-EVOLUTION B1, 用户裁决 2026-09-17 A) ──
//
// Every runtime-owned process resource (UDP sockets in node_dgram's
// UDP_REGISTRY, Workers in node_worker_threads' WORKER_REGISTRY, and spawned
// children in node_child_process' CP_ASYNC_STATES) is stamped
// with the creating BaoRuntime's monotonic token. When the runtime drops,
// `cleanup_runtime_resources(token)` terminates every resource it owns —
// "drop 时未 close 资源必须 close,防泄漏" (unreaped fd + port → EMFILE;
// unwaited child → zombie).
//
// Token 0 is the sentinel for resources created OUTSIDE any BaoRuntime
// (process-shared): registration points stamp
// `current_runtime_token().unwrap_or(0)` and cleanup never touches them.
static NEXT_RUNTIME_TOKEN: ::std::sync::atomic::AtomicU64 =
    ::std::sync::atomic::AtomicU64::new(1);

::std::thread_local! {
    /// Token of the BaoRuntime most recently created on this thread; `None`
    /// when no runtime is alive here (or the live one already dropped).
    static CURRENT_RUNTIME_TOKEN: ::std::cell::Cell<::std::option::Option<u64>> =
        ::std::cell::Cell::new(None);
}

/// Token of the runtime executing on the current thread, if any.
///
/// `Some(token)` = registrations made here are runtime-owned and are
/// terminated when that runtime drops; `None` → stamp 0 = process-shared,
/// never swept.
pub(crate) fn current_runtime_token() -> ::std::option::Option<u64> {
    CURRENT_RUNTIME_TOKEN.with(|t| t.get())
}

/// Terminate every runtime-owned resource registered under `token`.
///
/// Per-domain cleanup is wired here slice by slice (dgram's UDP registry,
/// worker_threads' worker registry and child_process' child registry).
pub(crate) fn cleanup_runtime_resources(token: u64) {
    crate::node_dgram::cleanup_for_token(token);
    // worker_threads registry: signal + bounded-join every worker this
    // runtime created — a leaked worker thread pins its own JSContext and
    // stack for the life of the process.
    crate::node_worker_threads::cleanup_for_token(token);
    // child_process registry: SIGTERM + bounded-reap every child this runtime
    // spawned and take back its pipe fds + IPC socketpair ends — a child
    // nobody waits zombifies forever and its fds leak.
    crate::node_child_process::cleanup_for_token(token);
    // child_process stdin write ends: the sweep above closed this runtime's
    // swept children's write ends; the thread-local drain below closes
    // whatever is left registered on this thread (exits no JS consumer ever
    // polled). Thread-local = owner boundary under the single-JS-thread model
    // — spawn only happens on the JS thread, so this thread's map belongs to
    // the runtime being dropped; closing a still-live child's stdin write end
    // is the same EOF the child would see from stdin.end().
    crate::node_child_process::close_stdin_fds_for_current_thread();
}

pub struct BaoRuntime {
    ctx: JsContext,
    // Declared after ctx so it drops last: guard drop triggers
    // JS_DestroyContext + JS_ShutDown after all JS execution is done.
    _guard: Option<SmRuntimeGuard>,
    // B1 resource-cleanup token. Copy, no drop logic of its own — declared
    // last; field drop order is unaffected (u64 drops are no-ops).
    token: u64,
    // B1 census row 27: the resolver root this runtime installed on its
    // thread (interned, process-lifetime). Copy, no drop logic of its own.
    resolver_root: &'static [u8],
}

impl ::std::ops::Drop for BaoRuntime {
    fn drop(&mut self) {
        // `Drop::drop` runs BEFORE the struct's fields are dropped (fields go
        // in declaration order: ctx, then _guard last). The contract noted on
        // `_guard` above still holds — JS_DestroyContext + JS_ShutDown still
        // happen after this body — so every runtime-owned resource (UDP
        // socket fds) is closed while the process is fully alive, and the
        // engine teardown sequence is byte-for-byte unchanged.
        cleanup_runtime_resources(self.token);
        // B1 census row 27: retire this runtime's resolver-root claim.
        // clear-if-same inside bun_core: a parasitic (older) runtime dropping
        // after a newer one re-seeded the overlay must not erase the newer
        // root — same shape as the CURRENT_RUNTIME_TOKEN clear below.
        bun_core::clear_current_top_level_dir(self.resolver_root);
        CURRENT_RUNTIME_TOKEN.with(|t| {
            // Clear only if THIS runtime is still the latest one on the
            // thread: a parasitic BaoRuntime::new() (shared JSContext)
            // overwrote the slot with its own token, and this older runtime's
            // drop must not erase it.
            if t.get() == Some(self.token) {
                t.set(None);
            }
        });
    }
}

impl BaoRuntime {
    pub fn new() -> ::std::result::Result<Self, JsError> {
        // B1: claim this runtime's monotonic resource-cleanup token up front
        // (0 is the "no runtime" sentinel, so tokens start at 1); publish it
        // to the thread-local only AFTER engine init succeeds so a failed
        // new() leaves no stale CURRENT_RUNTIME_TOKEN behind.
        let token = NEXT_RUNTIME_TOKEN.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed);
        // BAO_* → BUN_* env aliasing is resolved at the env read layer
        // (`bun_core::getenv_z` / `getenv_z_any_case`): a `BUN_<SUFFIX>` lookup
        // that misses falls back to `BAO_<SUFFIX>` (explicit BUN_ wins). The
        // constructor no longer copies BAO_* into the host process env via
        // `std::env::set_var` — a library constructor must not irreversibly
        // mutate the host environment (issue #32 / B0 census row 16;
        // the retired `init_env_aliases` lived here).
        // @trace REQ-CLI-001 — alias contract preserved, moved to read time
        // @trace REQ-H3-001: 默认启用 h3/HTTP3 fetch 能力(BAO 是正常 BUN)。
        // 在 HTTP 线程启动前设置,确保 bun_http::h3_alt_svc_enabled() 返回 true,
        // fetch() 默认支持 Alt-Svc 协商 + force_http3 显式协议选项。
        crate::h3_fetch::enable_h3_by_default();
        // Initialize bun_core output subsystem before any background thread
        // (e.g. fetch() worker) calls configure_thread() and hits the
        // STDOUT_STREAM_SET debug_assert.
        bun_core::output::init_test();
        crate::resolver_bridge::install();
        crate::bun_api::init_process_start();
        let (mut ctx, guard) = JsContext::init_runtime()?;
        // Publish the token before any lazy registration path (global_setup /
        // require installs fire on the first eval) can stamp a resource with
        // it. A parasitic runtime (shared JSContext) legitimately overwrites
        // the slot — newest runtime owns the current-registration window.
        CURRENT_RUNTIME_TOKEN.with(|t| t.set(Some(token)));
        // B1 census row 27: publish this runtime's resolver root only after
        // engine init succeeded (a failed new() must leave no stale overlay
        // behind, mirroring the token publish above). Every read of the
        // top-level dir on this thread — resolve_path's relative* joins,
        // Path::init_top_level_dir, dotenv's node/ccache lookup — follows
        // this overlay until the runtime drops.
        let resolver_root = crate::resolver_bridge::install_runtime_root();
        ctx.set_global_setup(globals::install_all);
        // Drain the event loop first; once it is done (natural end or
        // process.exit()), dispatch process 'exit' listeners inside the live
        // realm. Node semantics: registration order, exit code argument,
        // exitCode set by a listener is respected by the CLI main loop.
        ctx.set_post_eval_hook(crate::bun_api::post_eval_drain_then_exit);
        ::std::result::Result::Ok(BaoRuntime { ctx, _guard: guard, token, resolver_root })
    }

    pub fn eval(
        &mut self,
        source: &str,
        filename: &str,
    ) -> ::std::result::Result<JsValue, JsError> {
        self.ctx.eval(source, filename)
    }

    /// Ensure this context's persistent realm exists (realm-per-context,
    /// ECMA-262/Node semantics: one realm per agent for its whole lifetime).
    ///
    /// Delegates to `JsContext::ensure_realm_global` (idempotent — first call
    /// lazily creates the global, applies `global_setup` exactly once,
    /// publishes `thread_realm_global` for async dispatch; later calls return
    /// the stored global). No eval runs here, so no post-eval hook / exit
    /// dispatch — safe to call before any user code.
    fn ensure_realm(
        &mut self,
    ) -> ::std::result::Result<*mut mozjs::jsapi::JSObject, JsError> {
        let setup = self.ctx.global_setup();
        let mut cx = self.ctx.cx();
        self.ctx.ensure_realm_global(&mut cx, setup)
    }

    pub fn eval_module(
        &mut self,
        source: &str,
        filename: &str,
    ) -> ::std::result::Result<JsValue, JsError> {
        let hook = self.ctx.post_eval_hook();
        let mut cx = self.ctx.cx();
        // Realm-per-context: evaluate the module in this context's single
        // persistent realm — the same realm every script `eval` uses (Node
        // semantics: `globalThis` and `require` singletons are shared across
        // script and module evals). No new global, no global_setup re-run.
        let global_ptr = self.ensure_realm()?;
        rooted!(&in(cx) let global = global_ptr);
        ModuleLoader::eval_module_in_realm(&mut cx, source, filename, hook, global.handle())
    }

    // ── SM-EVOLUTION #24 S1 wiring (internal experimental surface) ──────────
    //
    // `#[doc(hidden)]`: NOT a stable public API commitment. These variants
    // exist so the engine-native interrupt/cancellation control
    // (`bao_engine::execution_control`) reaches the REAL production entries —
    // the same bodies `bao run` / `bao -e` / `bao --module` use — without
    // changing any user-visible behavior. Product-level exposure (CLI flag,
    // signal wiring) requires SPEC legislation first (ledger S1 boundary).

    /// `ExecutionControl` bound to THIS runtime's owner-thread context.
    /// Must be called on the runtime's own thread (same contract as the
    /// entries below); the returned handle may be cloned to any thread,
    /// which may then only submit `cancel()` / poll the terminal state.
    #[doc(hidden)]
    pub fn execution_control(&self) -> ExecutionControl {
        ExecutionControl::new()
    }

    /// `eval` + engine-native control (#24 S1 wiring of the script entry —
    /// the `bao -e` / CJS `bao run` body). Behavior identical to
    /// [`BaoRuntime::eval`] unless the deadline passes or the control is
    /// cancelled, in which case the runaway script is terminated with an
    /// uncatchable interrupt and a stable termination error is returned.
    #[doc(hidden)]
    pub fn eval_with_control(
        &mut self,
        control: &ExecutionControl,
        source: &str,
        filename: &str,
        timeout: Option<::std::time::Duration>,
    ) -> ::std::result::Result<JsValue, JsError> {
        self.ctx
            .run_with_control(control, timeout, |ctx| ctx.eval(source, filename))
    }

    /// `eval_module` + engine-native control (#24 S1 wiring of the module
    /// entry — the `bao run *.mjs` body). The control is armed around the
    /// WHOLE entry: module link/evaluate AND the post-eval event-loop pump,
    /// so a runaway in module top level or inside a timer/job/pump callback
    /// is terminated deterministically. On termination the stable
    /// termination error propagates out of the entry exactly like a script
    /// error (the CLI's existing `Err` → exit-code-1 mapping applies).
    #[doc(hidden)]
    pub fn eval_module_with_control(
        &mut self,
        control: &ExecutionControl,
        source: &str,
        filename: &str,
        timeout: Option<::std::time::Duration>,
    ) -> ::std::result::Result<JsValue, JsError> {
        let hook = self.ctx.post_eval_hook();
        let global_ptr = self.ensure_realm()?;
        // The persistent realm's global is AddRawValueRoot-ed for the
        // context's lifetime (`ensure_realm_global`), so re-rooting it inside
        // the runner is the same contract as `eval_module` above.
        self.ctx.run_with_control(control, timeout, |ctx| {
            let mut cx = ctx.cx();
            rooted!(&in(cx) let global = global_ptr);
            ModuleLoader::eval_module_in_realm(&mut cx, source, filename, hook, global.handle())
        })
    }

    pub fn run_file(&mut self, path: &str) -> ::std::result::Result<JsValue, JsError> {
        let (source, is_module) = self.prepare_file_execution(path)?;
        self.eval_file_body(path, &source, is_module, None, None)
    }

    /// `run_file` + engine-native control (#24 S1 wiring of the file entry —
    /// the `bao run <file>` body). Same source-read / require-dir /
    /// file-globals / script-vs-module dispatch as [`BaoRuntime::run_file`];
    /// the chosen entry runs under `control` (+ optional deadline). The
    /// control covers the WHOLE entry incl. the post-eval event-loop pump —
    /// a runaway in module top level or a timer/job/pump callback is
    /// terminated deterministically with the stable termination error.
    ///
    /// Internal experimental surface — NOT a stable API commitment.
    #[doc(hidden)]
    pub fn run_file_with_control(
        &mut self,
        control: &ExecutionControl,
        path: &str,
        timeout: ::std::option::Option<::std::time::Duration>,
    ) -> ::std::result::Result<JsValue, JsError> {
        let (source, is_module) = self.prepare_file_execution(path)?;
        self.eval_file_body(path, &source, is_module, Some(control), timeout)
    }

    /// Shared pre-dispatch half of the file entries: read the file, anchor
    /// the require dir, install per-file globals, and decide script vs
    /// module. Order-identical to the historical inline `run_file` sequence
    /// so the plain path is byte-for-byte the same execution.
    fn prepare_file_execution(
        &mut self,
        path: &str,
    ) -> ::std::result::Result<(String, bool), JsError> {
        let source = bun_sys::fs::read_to_string(path).map_err(|e| JsError {
            message: format!("Error reading {}: {}", path, e),
            filename: path.into(),
            line: 0,
            column: 0,
            stack: None,
        })?;

        let abs_path = if ::std::path::Path::new(path).is_absolute() {
            ::std::path::PathBuf::from(path)
        } else {
            ::std::env::current_dir().unwrap_or_default().join(path)
        };
        if let Some(dir) = abs_path.parent() {
            require::set_require_dir(dir.to_path_buf());
        }

        let filename_str = abs_path.to_string_lossy().into_owned();
        let dirname_str = abs_path
            .parent()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default();
        globals::install_file_globals(&mut self.ctx, &filename_str, &dirname_str);

        let is_module = if path.ends_with(".mjs") || path.ends_with(".mts") {
            true
        } else if path.ends_with(".ts") || path.ends_with(".tsx") || path.ends_with(".jsx") {
            // TypeScript/JSX files: treat as ESM if they contain import/export
            source.contains("import ") || source.contains("export ")
        } else if source.contains("import ")
            && (source.contains(" from ")
                || source.contains(" from\"")
                || source.contains("from '"))
            && !source.contains("require(")
        {
            // JS files with ESM imports (and no require): treat as ESM
            true
        } else if source.trim_start().starts_with("import ") {
            true
        } else {
            false
        };
        ::std::result::Result::Ok((source, is_module))
    }

    /// Dispatch half of the file entries: script or module, plain or under
    /// `control`. The four combinations are exact delegations — no behavior
    /// of the plain path changes.
    fn eval_file_body(
        &mut self,
        path: &str,
        source: &str,
        is_module: bool,
        control: ::std::option::Option<&ExecutionControl>,
        timeout: ::std::option::Option<::std::time::Duration>,
    ) -> ::std::result::Result<JsValue, JsError> {
        match (is_module, control) {
            (true, Some(control)) => self.eval_module_with_control(control, source, path, timeout),
            (true, None) => self.eval_module(source, path),
            (false, Some(control)) => self.eval_with_control(control, source, path, timeout),
            (false, None) => self.eval(source, path),
        }
    }

    /// Load and execute a test file, then run the registered `bun:test`
    /// suites while the realm that registered them is still alive. Returns
    /// a full report (counters + named passes/failures).
    ///
    /// Files that don't look like modules fall back to plain `eval` in the
    /// same persistent realm; a plain script cannot register bun:test suites
    /// via the module loader, so the report is empty — test files should use
    /// ESM/TS syntax.
    //
    // @trace REQ-ENG-006 [entity:BaoRuntime] — bao test runner execution
    pub fn run_test_file(
        &mut self,
        path: &str,
    ) -> ::std::result::Result<crate::bun_test::TestReport, JsError> {
        let source = bun_sys::fs::read_to_string(path).map_err(|e| JsError {
            message: format!("Error reading {}: {}", path, e),
            filename: path.into(),
            line: 0,
            column: 0,
            stack: None,
        })?;

        let abs_path = if ::std::path::Path::new(path).is_absolute() {
            ::std::path::PathBuf::from(path)
        } else {
            ::std::env::current_dir().unwrap_or_default().join(path)
        };
        if let Some(dir) = abs_path.parent() {
            require::set_require_dir(dir.to_path_buf());
        }

        let filename_str = abs_path.to_string_lossy().into_owned();
        let dirname_str = abs_path
            .parent()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default();
        globals::install_file_globals(&mut self.ctx, &filename_str, &dirname_str);

        let is_module = path.ends_with(".mjs")
            || path.ends_with(".mts")
            || path.ends_with(".ts")
            || path.ends_with(".tsx")
            || path.ends_with(".jsx")
            || (source.contains("import ")
                && (source.contains(" from ")
                    || source.contains(" from\"")
                    || source.contains("from '"))
                && !source.contains("require("))
            || source.trim_start().starts_with("import ");

        if is_module {
            let hook = self.ctx.post_eval_hook();
            let mut cx = self.ctx.cx();
            // Realm-per-context: run the test module in the same persistent
            // realm as every script eval on this context.
            let global_ptr = self.ensure_realm()?;
            rooted!(&in(cx) let global = global_ptr);
            ModuleLoader::eval_module_in_realm_then(
                &mut cx,
                &source,
                path,
                hook,
                global.handle(),
                |realm_cx| unsafe { crate::bun_test::run_bun_tests_report(realm_cx.raw_cx()) },
            )
        } else {
            // Non-module (CJS/plain-script) file: run as a script in the
            // persistent realm, then drive the registered suites exactly like
            // the module branch above — require('node:test') in a CJS file
            // registers into the same bun:test collector, and registered but
            // never-executed suites are the silent fake pass this runner
            // exists to prevent.
            self.eval(&source, path)?;
            ::std::result::Result::Ok(self.run_registered_tests())
        }
    }

    /// Drive the bun:test suites registered in this context's persistent
    /// realm and return the report. `bao test` calls this after evaluating
    /// each test file — module files via `eval_module_in_realm_then`'s
    /// callback (which runs inside `AutoRealm`), plain-script files and
    /// `bao test -e` evals directly here — so every entry path executes what
    /// it registered instead of reporting a vacuous 0/0.
    //
    // @trace REQ-ENG-006 [entity:BaoRuntime] — bao test runner execution
    pub fn run_registered_tests(&mut self) -> crate::bun_test::TestReport {
        let global_ptr = match self.ensure_realm() {
            Ok(g) => g,
            Err(_) => return crate::bun_test::TestReport::default(),
        };
        let mut cx = self.ctx.cx();
        rooted!(&in(cx) let global = global_ptr);
        // Enter the persistent realm: the runner's shims evaluate against the
        // current realm's global (same contract as the module branch's
        // after_eval callback).
        let mut realm = AutoRealm::new_from_handle(&mut cx, global.handle());
        let realm_cx: &mut mozjs::context::JSContext = &mut realm;
        unsafe { crate::bun_test::run_bun_tests_report(realm_cx.raw_cx()) }
    }
}