bun_runtime 0.5.4

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// @trace REQ-ENG-006 [api:Bun.Glob] — glob pattern object.
//
// Upstream face (js/builtins/Glob.ts + runtime/api/glob.zig):
// `new Bun.Glob(pattern)` →
//   * `glob.match(path)`            — bun_glob::r#match (Bun-faithful matcher)
//   * `glob.scanSync({ cwd, dot, onlyFiles, absolute, followSymlinks })`
//                                   — GlobWalker collection → Array
//                                     (arrays are iterable; upstream returns a
//                                     generator over the same values)
//   * `glob.scan({...})`            — same collection wrapped as an async
//                                     iterable (upstream: async generator)
//
// Upstream option defaults (runtime/api/glob.zig ScanOpts.fromJS): dot=false,
// onlyFiles=true, followSymlinks=false, errorOnBrokenSymlinks=false,
// absolute=false. Yielded paths are joined with `cwd` (cwd-rooted).
//
// BCE-20260817-GLOB-STRCWD — scan/scanSync(arg) only read options when arg
// was an object, so the upstream string form (`g.scanSync('/abs/dir')` —
// ScanOpts.fromJS treats a string arg as the `cwd` shorthand, parseCWD
// resolving relative values against the process cwd) was silently ignored
// and the scan ran against the process cwd instead → empty result. Non-
// object/non-string args and a non-string `cwd` now fail closed with the
// upstream messages instead of being dropped.
use mozjs::jsapi::*;
use mozjs::jsval::{JSVal, ObjectValue, StringValue, UndefinedValue};
use mozjs::rooted;
use mozjs::rust::ToBoolean;
use mozjs::rust::wrappers2::{JS_DefineFunction, JS_DefineProperty3, JS_NewPlainObject};

use bun_core::ZBox;

#[derive(Default, Clone, Copy)]
struct ScanOpts {
    dot: bool,
    only_files: bool,
    absolute: bool,
    follow_symlinks: bool,
}

impl ScanOpts {
    /// Upstream defaults: only_files=true, everything else false.
    fn upstream_defaults() -> Self {
        ScanOpts { dot: false, only_files: true, absolute: false, follow_symlinks: false }
    }
}

/// Read the pattern stored on the Glob instance (`_pattern` private prop).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn glob_pattern_of(
    cx: *mut JSContext,
    obj: mozjs::rust::Handle<*mut JSObject>,
) -> Option<String> {
    let mut v = UndefinedValue();
    if !JS_GetProperty(
        cx,
        obj.into(),
        c"_pattern".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut v,
        },
    ) || !v.is_string()
    {
        JS_ClearPendingException(cx);
        return None;
    }
    Some(crate::js_to_rust_string(cx, v))
}

fn process_cwd() -> String {
    ::std::env::current_dir()
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|_| ".".to_string())
}

/// Upstream `parseCWD` (runtime/api/glob.zig): "" → process cwd (i.e. cwd
/// left unset), absolute → as-is, relative → resolved against process cwd.
fn resolve_scan_cwd(cwd_val: &str) -> String {
    if cwd_val.is_empty() {
        return process_cwd();
    }
    // Platform-aware absolute test. The old leading-'/' check treated a
    // Windows drive-rooted cwd ("C:\dir") as RELATIVE and joined it onto
    // the process cwd ("<cwd>/C:\dir") — every scanSync("C:\...") then
    // walked a nonexistent path and returned [] (fs.globSync worked because
    // its options parser takes the cwd verbatim).
    let absolute = if cfg!(windows) {
        let b = cwd_val.as_bytes();
        let rooted = b.first().is_some_and(|&c| c == b'/' || c == b'\\');
        let drive_rooted = b.len() > 2
            && b[0].is_ascii_alphabetic()
            && b[1] == b':'
            && (b[2] == b'/' || b[2] == b'\\');
        rooted || drive_rooted
    } else {
        cwd_val.starts_with('/')
    };
    if absolute {
        return cwd_val.to_string();
    }
    let base = process_cwd();
    let trimmed = base.trim_end_matches('/');
    if trimmed.is_empty() {
        format!("/{}", cwd_val)
    } else {
        format!("{}/{}", trimmed, cwd_val)
    }
}

/// Read scan options off arg 0 — upstream `ScanOpts.fromJS` semantics:
///   * absent / undefined / null → defaults (process cwd)
///   * string → the string IS the `cwd` (shorthand form; parseCWD-resolved)
///   * object → truthy reads of cwd/dot/onlyFiles/absolute/followSymlinks
///     (a truthy non-boolean reads as false, mirroring upstream getTruthy +
///     `if (v.isBoolean()) v.asBoolean() else false`)
///   * anything else → Err (caller reports; upstream throws)
/// A truthy non-string `cwd` → Err (upstream: "invalid `cwd`, not a string").
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn glob_scan_opts(
    cx: *mut JSContext,
    argc: u32,
    args: &CallArgs,
    fn_name: &str,
) -> ::std::result::Result<(String, ScanOpts), String> {
    let mut cwd = process_cwd();
    let mut opts = ScanOpts::upstream_defaults();
    if argc == 0 {
        return Ok((cwd, opts));
    }
    let arg0 = *args.get(0).ptr;
    if arg0.is_undefined() || arg0.is_null() {
        return Ok((cwd, opts));
    }
    if !arg0.is_object() {
        if arg0.is_string() {
            let s = crate::js_to_rust_string(cx, arg0);
            cwd = resolve_scan_cwd(&s);
            return Ok((cwd, opts));
        }
        return Err(format!("{}: expected first argument to be an object", fn_name));
    }

    let mut wrapped =
        mozjs::context::JSContext::from_ptr(::std::ptr::NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped;
    rooted!(&in(cx_ref) let oobj = arg0.to_object());
    let o_h = oobj.handle().into();

    // `cwd` — only a truthy string is accepted (getTruthy + isString check).
    let mut v = UndefinedValue();
    if JS_GetProperty(
        cx,
        o_h,
        c"cwd".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut v,
        },
    ) {
        rooted!(&in(cx_ref) let v_root = v);
        if ToBoolean(v_root.handle()) {
            if !v.is_string() {
                return Err(format!("{}: invalid `cwd`, not a string", fn_name));
            }
            let s = crate::js_to_rust_string(cx, v);
            cwd = resolve_scan_cwd(&s);
        }
    } else {
        JS_ClearPendingException(cx);
    }

    let bools: &[(&::std::ffi::CStr, fn(&mut ScanOpts, bool))] = &[
        (c"dot", |o, b| o.dot = b),
        (c"onlyFiles", |o, b| o.only_files = b),
        (c"absolute", |o, b| o.absolute = b),
        (c"followSymlinks", |o, b| o.follow_symlinks = b),
    ];
    for (name, setter) in bools {
        let mut bv = UndefinedValue();
        if JS_GetProperty(
            cx,
            o_h,
            name.as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut bv,
            },
        ) {
            rooted!(&in(cx_ref) let bv_root = bv);
            if ToBoolean(bv_root.handle()) {
                setter(&mut opts, bv.is_boolean() && bv.to_boolean());
            }
        } else {
            JS_ClearPendingException(cx);
        }
    }
    Ok((cwd, opts))
}

/// Collect matches via the workspace GlobWalker (the same engine fs.glob
/// uses — node_fs.rs glob_collect pattern). Returns cwd-rooted paths.
/// Windows-absolute test shared by the glob collectors (drive-rooted or
/// rooted); POSIX = leading '/'.
pub(crate) fn glob_pattern_is_absolute(p: &str) -> bool {
    if cfg!(windows) {
        let b = p.as_bytes();
        let rooted = b.first().is_some_and(|&c| c == b'/' || c == b'\\');
        let drive_rooted = b.len() > 2
            && b[0].is_ascii_alphabetic()
            && b[1] == b':'
            && (b[2] == b'/' || b[2] == b'\\');
        rooted || drive_rooted
    } else {
        p.starts_with('/')
    }
}

fn glob_collect_impl(pattern: &str, cwd: &str, opts: ScanOpts) -> Vec<String> {
    type Walker = bun_glob::GlobWalker<bun_glob::walk::SyscallAccessor, false>;
    // Windows absolute patterns carry MAIN_SEPARATOR, but the glob language
    // treats '\' as an escape — normalize the pattern to '/' (filenames
    // cannot contain backslashes on Windows, so the rewrite is lossless).
    #[cfg(windows)]
    let pattern_owned;
    #[cfg(windows)]
    let pattern = if glob_pattern_is_absolute(pattern) {
        pattern_owned = pattern.replace('\\', "/");
        &pattern_owned
    } else {
        pattern
    };
    let absolute = opts.absolute || glob_pattern_is_absolute(pattern);
    let mut walker = match Walker::init_with_cwd(
        pattern.as_bytes(),
        cwd.as_bytes(),
        opts.dot,
        absolute,
        opts.follow_symlinks,
        false, // error_on_broken_symlinks (upstream default)
        opts.only_files,
        None,
    ) {
        Ok(Ok(w)) => w,
        // Malformed pattern (unbalanced brace/class) → no matches.
        _ => return Vec::new(),
    };
    let mut iter = bun_glob::walk::Iterator::new(&mut walker);
    if iter.init().is_err() {
        return Vec::new();
    }
    let mut out = Vec::new();
    loop {
        match iter.next() {
            Ok(Ok(Some(path))) => out.push(String::from_utf8_lossy(&path).into_owned()),
            _ => break,
        }
    }
    // Glob results are '/'-shaped on every platform (the pattern language
    // is posix-shaped; node fs.glob / Bun GlobWalker yield forward slashes
    // on win32). The engine's platform join emits MAIN_SEPARATOR on
    // Windows — normalize here (scan + scanSync share this collector). Safe
    // blanket replace: a Windows filename cannot contain a backslash.
    #[cfg(windows)]
    for r in out.iter_mut() {
        *r = r.replace('\\', "/");
    }
    out
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn glob_ctor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if args.argc_ == 0 || !(*args.get(0).ptr).is_string() {
        JS_ReportErrorUTF8(cx, c"Bun.Glob expects a pattern string".as_ptr());
        return false;
    }
    let pattern = crate::js_to_rust_string(cx, *args.get(0).ptr);

    let mut wrapped = mozjs::context::JSContext::from_ptr(::std::ptr::NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped;
    rooted!(&in(cx_ref) let g = JS_NewPlainObject(cx_ref));
    if g.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let c_pattern = ZBox::from_bytes(pattern.as_bytes());
    let js_pattern = JS_NewStringCopyZ(cx, c_pattern.as_ptr());
    if !js_pattern.is_null() {
        rooted!(&in(cx_ref) let pv = StringValue(&*js_pattern));
        JS_DefineProperty(
            cx,
            g.handle().into(),
            c"_pattern".as_ptr(),
            pv.handle().into(),
            0,
        );
    }
    // Bun.Glob instances expose the pattern as `source` too (Glob.ts).
    if !js_pattern.is_null() {
        rooted!(&in(cx_ref) let pv = StringValue(&*js_pattern));
        JS_DefineProperty(
            cx,
            g.handle().into(),
            c"source".as_ptr(),
            pv.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
    JS_DefineFunction(
        cx_ref,
        g.handle(),
        c"match".as_ptr(),
        Some(glob_match),
        1,
        JSPROP_ENUMERATE as u32,
    );
    JS_DefineFunction(
        cx_ref,
        g.handle(),
        c"scanSync".as_ptr(),
        Some(glob_scan_sync),
        1,
        JSPROP_ENUMERATE as u32,
    );
    JS_DefineFunction(
        cx_ref,
        g.handle(),
        c"scan".as_ptr(),
        Some(glob_scan),
        1,
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(g.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn glob_match(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped = mozjs::context::JSContext::from_ptr(::std::ptr::NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped;
    let this = args.thisv();
    if !this.is_object() {
        JS_ReportErrorUTF8(cx, c"Bun.Glob.prototype.match requires a Glob instance".as_ptr());
        return false;
    }
    rooted!(&in(cx_ref) let this_root = this.to_object());
    let Some(pattern) = glob_pattern_of(cx, this_root.handle()) else {
        JS_ReportErrorUTF8(cx, c"Bun.Glob instance has no pattern".as_ptr());
        return false;
    };
    if argc == 0 || !(*args.get(0).ptr).is_string() {
        JS_ReportErrorUTF8(cx, c"Bun.Glob.match expects a path string".as_ptr());
        return false;
    }
    let path = crate::js_to_rust_string(cx, *args.get(0).ptr);
    let matched = matches!(
        bun_glob::r#match(pattern.as_bytes(), path.as_bytes()),
        bun_glob::MatchResult::Match
    );
    args.rval().set(mozjs::jsval::BooleanValue(matched));
    true
}

/// The canonical scan body both scan entry points call after resolving `this`:
/// collect matches and build the JS array. `Ok(null)` = unusable `this`
/// (caller yields undefined); `Err` = invalid scan argument (caller reports).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn glob_scan_body(
    cx: *mut JSContext,
    this: *mut JSObject,
    argc: u32,
    args: &CallArgs,
    fn_name: &str,
) -> ::std::result::Result<*mut JSObject, String> {
    let mut wrapped = mozjs::context::JSContext::from_ptr(::std::ptr::NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped;
    rooted!(&in(cx_ref) let this_root = this);
    let Some(pattern) = glob_pattern_of(cx, this_root.handle()) else {
        return Ok(::std::ptr::null_mut());
    };
    let (cwd, opts) = glob_scan_opts(cx, argc, args, fn_name)?;
    let matches = glob_collect_impl(&pattern, &cwd, opts);

    rooted!(&in(cx_ref) let arr = mozjs::rust::wrappers2::NewArrayObject1(cx_ref, matches.len()));
    if arr.get().is_null() {
        return Ok(::std::ptr::null_mut());
    }
    for (i, m) in matches.iter().enumerate() {
        let c_m = ZBox::from_bytes(m.as_bytes());
        let js_m = JS_NewStringCopyZ(cx, c_m.as_ptr());
        if !js_m.is_null() {
            rooted!(&in(cx_ref) let mv = StringValue(&*js_m));
            let _ = JS_DefineElement(
                cx,
                arr.handle().into(),
                i as u32,
                mv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }
    Ok(arr.get())
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn glob_scan_sync(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if !this.is_object() {
        JS_ReportErrorUTF8(cx, c"Bun.Glob.scanSync requires a Glob instance".as_ptr());
        return false;
    }
    match glob_scan_body(cx, this.to_object(), argc, &args, "scanSync") {
        Ok(arr) if !arr.is_null() => args.rval().set(ObjectValue(arr)),
        Ok(_) => args.rval().set(UndefinedValue()),
        Err(msg) => {
            let m = ZBox::from_vec(msg.into_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), m.as_ptr());
            return false;
        }
    }
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn glob_scan(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    // scan: synchronous collection wrapped as an async iterable (upstream
    // returns an async generator over the same match set).
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if !this.is_object() {
        JS_ReportErrorUTF8(cx, c"Bun.Glob.scan requires a Glob instance".as_ptr());
        return false;
    }
    let arr = match glob_scan_body(cx, this.to_object(), argc, &args, "scan") {
        Ok(arr) if !arr.is_null() => arr,
        Ok(_) => {
            args.rval().set(UndefinedValue());
            return true;
        }
        Err(msg) => {
            let m = ZBox::from_vec(msg.into_bytes());
            JS_ReportErrorUTF8(cx, c"%s".as_ptr(), m.as_ptr());
            return false;
        }
    };
    let mut wrapped = mozjs::context::JSContext::from_ptr(::std::ptr::NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped;
    // Root `arr` for the async-iterator wrap window below: NewCompileOptions /
    // Evaluate2 / JS_CallFunctionValue are all GC points — a nursery GC
    // relocates the array and the bare local would go stale (e206 class).
    rooted!(&in(cx_ref) let arr_r = arr);
    let wrap_src = r#"(function(arr) {
  return {
    [Symbol.asyncIterator]: async function* () { yield* arr; },
    [Symbol.iterator]: function* () { yield* arr; },
  };
})"#;
    let mut text = mozjs::rust::transform_str_to_source_text(wrap_src);
    let opts = mozjs::glue::NewCompileOptions(cx, c"<bun:glob-scan>".as_ptr(), 1);
    if opts.is_null() {
        args.rval().set(ObjectValue(arr_r.get()));
        return true;
    }
    let mut ctor = UndefinedValue();
    let ctor_h = MutableHandle::<Value> {
        _phantom_0: ::std::marker::PhantomData,
        ptr: &mut ctor,
    };
    let ok = mozjs_sys::jsapi::JS::Evaluate2(cx, opts, &mut text, ctor_h);
    mozjs::glue::DeleteCompileOptions(opts);
    if !ok || !ctor.is_object() {
        JS_ClearPendingException(cx);
        args.rval().set(ObjectValue(arr_r.get()));
        return true;
    }
    rooted!(&in(cx_ref) let ctor_obj = ctor.to_object());
    rooted!(&in(cx_ref) let ctor_val = ObjectValue(ctor_obj.get()));
    rooted!(&in(cx_ref) let arr_val = ObjectValue(arr_r.get()));
    let call_vals = [arr_val.handle().get()];
    let call_arr = HandleValueArray {
        length_: 1,
        elements_: call_vals.as_ptr(),
    };
    let mut out = UndefinedValue();
    let called = JS_CallFunctionValue(
        cx,
        ctor_obj.handle().into(),
        ctor_val.handle().into(),
        &call_arr,
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut out,
        },
    );
    if !called || !out.is_object() {
        if !called {
            JS_ClearPendingException(cx);
        }
        args.rval().set(ObjectValue(arr_r.get()));
        return true;
    }
    args.rval().set(out);
    true
}

/// Install `Bun.Glob` (constructor) on the Bun object.
///
/// # Safety
/// Caller must ensure `cx` is a valid JSContext and `bun_obj` a live object.
pub unsafe fn install(
    cx: &mut mozjs::context::JSContext,
    bun_obj: mozjs::rust::Handle<*mut JSObject>,
) {
    // JSFUN_CONSTRUCTOR (0x400): constructible so `new Bun.Glob(pattern)`
    // dispatches here (node_buffer.rs JSFUN_CONSTRUCTOR pattern — SM's
    // [[Construct]] for natives honours the rval we set).
    const JSFUN_CONSTRUCTOR: u32 = 0x400;
    let ctor = JS_NewFunction(
        cx.raw_cx(),
        Some(glob_ctor),
        1,
        JSFUN_CONSTRUCTOR,
        c"Glob".as_ptr(),
    );
    if ctor.is_null() {
        return;
    }
    let ctor_obj = JS_GetFunctionObject(ctor);
    if ctor_obj.is_null() {
        return;
    }
    rooted!(&in(cx) let ctor_root = ctor_obj);
    JS_DefineProperty3(
        cx,
        bun_obj,
        c"Glob".as_ptr(),
        ctor_root.handle(),
        JSPROP_ENUMERATE as u32,
    );
}