bun_bundler 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
543
544
545
546
547
548
549
550
551
use core::ffi::c_void;

use crate::options::Loader;
// `bake::Side` / `jsc.api.BuildArtifact.OutputKind` are TYPE_ONLY move-ins;
// the `options` module already defines them locally.
use crate::options::{OutputKind, Side};
use bun_core::Error;
use bun_core::{PathString, String as BunString};
use bun_paths::PathBuffer;
use bun_paths::fs;
use bun_paths::resolve_path::{self, platform};
use bun_sys::Fd;

use crate::bun_fs::RealFS;

// Instead of keeping files in-memory, we:
// 1. Write directly to disk
// 2. (Optional) move the file to the destination
// This saves us from allocating a buffer

pub struct OutputFile {
    pub loader: Loader,
    pub input_loader: Loader,
    pub src_path: fs::Path<'static>,
    pub owned_src_path_text: Box<[u8]>,
    pub value: Value,
    pub size: usize,
    pub size_without_sourcemap: usize,
    pub hash: u64,
    pub is_executable: bool,
    pub source_map_index: u32,
    pub bytecode_index: u32,
    pub module_info_index: u32,
    pub output_kind: OutputKind,
    /// Relative
    pub dest_path: Box<[u8]>,
    pub side: Option<Side>,
    /// This is only set for the JS bundle, and not files associated with an
    /// entrypoint like sourcemaps and bytecode
    pub entry_point_index: Option<u32>,
    pub referenced_css_chunks: Box<[Index]>,
    pub source_index: IndexOptional,
    pub bake_extra: BakeExtra,
}

impl OutputFile {
    // TODO(port): Zig `zero_value` is a const struct literal; Rust can't make this a
    // true `const` because `Box`/`fs::Path` aren't const-constructible. Exposed as a
    // plain fn so call sites read `OutputFile::zero_value()`.
    pub fn zero_value() -> OutputFile {
        OutputFile {
            loader: Loader::File,
            input_loader: Loader::Js,
            src_path: fs::Path::init(b""),
            owned_src_path_text: Box::default(),
            value: Value::Noop,
            size: 0,
            size_without_sourcemap: 0,
            hash: 0,
            is_executable: false,
            source_map_index: u32::MAX,
            bytecode_index: u32::MAX,
            module_info_index: u32::MAX,
            output_kind: OutputKind::Chunk,
            dest_path: Box::default(),
            side: None,
            entry_point_index: None,
            referenced_css_chunks: Box::default(),
            source_index: IndexOptional::NONE,
            bake_extra: BakeExtra::default(),
        }
    }
}

impl Clone for OutputFile {
    fn clone(&self) -> Self {
        let owned_src_path_text = self.owned_src_path_text.clone();
        // SAFETY: `owned_src_path_text` is a sibling field that outlives `src_path`; the boxed buffer never moves.
        let text: &'static [u8] =
            unsafe { core::mem::transmute::<&[u8], &'static [u8]>(&owned_src_path_text) };
        let src_path = if !self.owned_src_path_text.is_empty() {
            fs::Path {
                is_disabled: self.src_path.is_disabled,
                is_symlink: self.src_path.is_symlink,
                ..fs::Path::init(text)
            }
        } else {
            self.src_path
        };
        OutputFile {
            loader: self.loader,
            input_loader: self.input_loader,
            src_path,
            owned_src_path_text,
            value: self.value.clone(),
            size: self.size,
            size_without_sourcemap: self.size_without_sourcemap,
            hash: self.hash,
            is_executable: self.is_executable,
            source_map_index: self.source_map_index,
            bytecode_index: self.bytecode_index,
            module_info_index: self.module_info_index,
            output_kind: self.output_kind,
            dest_path: self.dest_path.clone(),
            side: self.side,
            entry_point_index: self.entry_point_index,
            referenced_css_chunks: self.referenced_css_chunks.clone(),
            source_index: self.source_index,
            bake_extra: self.bake_extra,
        }
    }
}

#[derive(Default, Clone, Copy)]
pub struct BakeExtra {
    pub is_route: bool,
    pub fully_static: bool,
    pub bake_is_runtime: bool,
}

// Zig: `pub const Index = bun.GenericIndex(u32, OutputFile);`
pub type Index = bun_core::GenericIndex<u32, OutputFile>;
pub type IndexOptional = bun_core::GenericIndexOptional<u32, OutputFile>;

// Depending on:
// - The target
// - The number of open file handles
// - Whether or not a file of the same name exists
// We may use a different system call
#[derive(Clone)]
pub struct FileOperation {
    // TODO(port): lifetime — Zig never frees `pathname`; may be borrowed from
    // `Options.output_path`. Using owned `Box<[u8]>` for now.
    pub pathname: Box<[u8]>,
    pub fd: Fd,
    pub dir: Fd,
    pub is_tmpdir: bool,
    pub is_outdir: bool,
    pub close_handle_on_complete: bool,
    pub autowatch: bool,
}

impl Default for FileOperation {
    fn default() -> Self {
        Self {
            pathname: Box::default(),
            fd: Fd::INVALID,
            dir: Fd::INVALID,
            is_tmpdir: false,
            is_outdir: false,
            close_handle_on_complete: false,
            autowatch: true,
        }
    }
}

impl FileOperation {
    pub fn from_file(fd: Fd, pathname: &[u8]) -> FileOperation {
        FileOperation {
            fd,
            pathname: Box::from(pathname),
            ..Default::default()
        }
    }

    pub fn get_pathname(&self) -> &[u8] {
        if self.is_tmpdir {
            // PORT NOTE: `resolve_path.joinAbs` writes into a threadlocal buffer in
            // Zig; the Rust port returns a borrow into that TLS buffer (`'static`),
            // which coerces to the `&self` lifetime here.
            return resolve_path::join_abs::<platform::Auto>(RealFS::tmpdir_path(), &self.pathname);
        }
        &self.pathname
    }
}

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
pub enum Kind {
    Move,
    Copy,
    Noop,
    Buffer,
    Pending,
    Saved,
}

// TODO: document how and why all variants of this union(enum) are used,
// specifically .move and .copy; the new bundler has to load files in memory
// in order to hash them, so i think it uses .buffer for those
pub enum Value {
    Move(FileOperation),
    Copy(FileOperation),
    Noop,
    Buffer {
        // Zig carried `arena: std.mem.Allocator` alongside `bytes`; in Rust the
        // global mimalloc arena backs `Box<[u8]>`, so the field is dropped.
        bytes: Box<[u8]>,
    },
    // PORT NOTE: boxed to avoid blowing up `Value`'s inline size (`resolver::Result`
    // is several hundred bytes).
    Pending(Box<bun_resolver::Result>),
    Saved(SavedFile),
}

// Zig `bun.copy(OutputFile, dst, src)` is a bitwise memcpy used to splice
// finished output files into the final list. The `Pending` arm is never present
// at that stage (only `buffer`/`copy`/`saved` are produced by `init`), so its
// clone is intentionally unreachable rather than forcing `resolver::Result` to
// be `Clone`.
impl Clone for Value {
    fn clone(&self) -> Self {
        match self {
            Value::Move(op) => Value::Move(op.clone()),
            Value::Copy(op) => Value::Copy(op.clone()),
            Value::Noop => Value::Noop,
            Value::Buffer { bytes } => Value::Buffer {
                bytes: bytes.clone(),
            },
            Value::Pending(_) => unreachable!("OutputFile.Value::Pending is never cloned"),
            Value::Saved(s) => Value::Saved(*s),
        }
    }
}

impl Value {
    pub fn as_slice(&self) -> &[u8] {
        match self {
            Value::Buffer { bytes } => bytes,
            _ => b"",
        }
    }

    pub fn to_bun_string(self) -> BunString {
        match self {
            Value::Noop => BunString::EMPTY,
            Value::Buffer { bytes } => {
                if bytes.is_empty() {
                    return BunString::EMPTY;
                }
                // Use ExternalStringImpl to avoid cloning the string, at
                // the cost of allocating space to remember the arena.
                //
                // Zig boxed a `FreeContext { arena }` and passed an `extern "C"`
                // callback that frees the slice via that arena then destroys the
                // context. With the global arena, the context collapses to the
                // (ptr, len) pair already passed to the callback.
                extern "C" fn on_free(_ctx: *mut c_void, buffer: *mut c_void, len: usize) {
                    // SAFETY: `buffer`/`len` were produced by `heap::alloc` on a
                    // `Box<[u8]>` below; reconstructing and dropping is sound.
                    unsafe {
                        drop(bun_core::heap::take(core::ptr::slice_from_raw_parts_mut(
                            buffer.cast::<u8>(),
                            len,
                        )));
                    }
                }
                // Hand the `Box<[u8]>` to the ExternalStringImpl: `heap::release`
                // (= `Box::leak`) yields a `&'static mut [u8]` borrow of the
                // now-JSC-owned allocation; `on_free` reclaims it on GC.
                let bytes: &'static mut [u8] = bun_core::heap::release(bytes);
                // latin1 flag = true (matches Zig).
                BunString::create_external::<*mut c_void>(
                    bytes,
                    true,
                    core::ptr::null_mut::<c_void>(),
                    on_free,
                )
            }
            Value::Pending(_) => unreachable!(),
            // Zig: `else => |tag| bun.todoPanic(@src(), "handle .{s}", .{@tagName(tag)})`
            // — an intentional shipped runtime panic for `.move`/`.copy`/`.saved`,
            // not a port placeholder.
            other => bun_core::todo_panic!("handle .{}", <&'static str>::from(other.kind())),
        }
    }

    /// Borrowing variant of [`Self::to_bun_string`]: wraps the buffer in a
    /// `WTF::ExternalStringImpl` that aliases `bytes` with a **no-op** free
    /// callback (zero-copy). Caller guarantees `self` outlives every use of the
    /// returned string.
    ///
    /// This is the faithful port of Zig's `Value.toBunString` as called from
    /// `bake/production.zig` (`pt.bundled_outputs[i].value.toBunString()`): Zig
    /// passes the union by value so the slice is aliased in place, and
    /// `PerThread.bundled_outputs` owns the bytes for the entire prerender
    /// phase. The consuming [`Self::to_bun_string`] cannot be used there
    /// because the Rust `Vec<OutputFile>` is only borrowed.
    pub fn to_bun_string_ref(&self) -> BunString {
        match self {
            Value::Noop => BunString::EMPTY,
            Value::Buffer { bytes } => {
                if bytes.is_empty() {
                    return BunString::EMPTY;
                }
                extern "C" fn noop(_: *mut c_void, _: *mut c_void, _: usize) {}
                // latin1 = true (matches Zig).
                BunString::create_external::<*mut c_void>(
                    bytes,
                    true,
                    core::ptr::null_mut::<c_void>(),
                    noop,
                )
            }
            Value::Pending(_) => unreachable!(),
            other => bun_core::todo_panic!("handle .{}", <&'static str>::from(other.kind())),
        }
    }

    pub fn kind(&self) -> Kind {
        match self {
            Value::Move(_) => Kind::Move,
            Value::Copy(_) => Kind::Copy,
            Value::Noop => Kind::Noop,
            Value::Buffer { .. } => Kind::Buffer,
            Value::Pending(_) => Kind::Pending,
            Value::Saved(_) => Kind::Saved,
        }
    }
}

/// `OutputFile.zig:SavedFile` (TYPE_ONLY move-in from bundler_jsc).
#[derive(Default, Clone, Copy)]
pub struct SavedFile {
    pub byte_size: u64,
}

impl OutputFile {
    pub fn init_pending(loader: Loader, pending: bun_resolver::Result) -> OutputFile {
        // PORT NOTE: Zig copied the whole `Fs.Path` struct (`pending.pathConst().?.*`).
        // The Rust `bun_paths::fs::Path<'static>` and `bun_resolver::fs::Path<'static>` are
        // distinct nominal types with identical layout; re-init from `text` (the
        // resolver path borrows arena/static memory, so the `'static` bound holds).
        let src_path = fs::Path::init(pending.path_const().expect("path").text);
        OutputFile {
            loader,
            src_path,
            size: 0,
            value: Value::Pending(Box::new(pending)),
            ..OutputFile::zero_value()
        }
    }

    // TODO(port): Zig took `std.fs.File`; std::fs is banned. Accepting a raw `Fd`.
    pub fn init_file(file: Fd, pathname: &'static [u8], size: usize) -> OutputFile {
        OutputFile {
            loader: Loader::File,
            src_path: fs::Path::init(pathname),
            size,
            value: Value::Copy(FileOperation::from_file(file, pathname)),
            ..OutputFile::zero_value()
        }
    }

    // TODO(port): Zig took `std.fs.Dir`; using `Fd` for the dir handle.
    pub fn init_file_with_dir(
        file: Fd,
        pathname: &'static [u8],
        size: usize,
        dir: Fd,
    ) -> OutputFile {
        let mut res = Self::init_file(file, pathname, size);
        if let Value::Copy(op) = &mut res.value {
            // PORT NOTE: Zig wrote `res.value.copy.dir_handle = .fromStdDir(dir)` but
            // `FileOperation` has no `dir_handle` field — looks like a latent bug; the
            // intended field is `dir`.
            op.dir = dir;
        }
        res
    }
}

pub enum OptionsData {
    Buffer {
        // arena dropped — global mimalloc.
        data: Box<[u8]>,
    },
    File {
        // TODO(port): Zig used `std.fs.File` / `std.fs.Dir`; mapped to `Fd`.
        file: Fd,
        size: usize,
        dir: Fd,
    },
    Saved(usize),
}

pub struct Options {
    pub loader: Loader,
    pub input_loader: Loader,
    pub hash: Option<u64>,
    pub source_map_index: Option<u32>,
    pub bytecode_index: Option<u32>,
    pub module_info_index: Option<u32>,
    pub output_path: Box<[u8]>,
    pub source_index: IndexOptional,
    pub size: Option<usize>,
    pub input_path: Box<[u8]>,
    pub display_size: u32,
    pub output_kind: OutputKind,
    pub is_executable: bool,
    pub data: OptionsData,
    pub side: Option<Side>,
    pub entry_point_index: Option<u32>,
    pub referenced_css_chunks: Box<[Index]>,
    pub bake_extra: BakeExtra,
}

impl OutputFile {
    pub fn init(options: Options) -> OutputFile {
        let size = options.size.unwrap_or(match &options.data {
            OptionsData::Buffer { data } => data.len(),
            OptionsData::File { size, .. } => *size,
            OptionsData::Saved(_) => 0,
        });
        let owned_src_path_text: Box<[u8]> = options.input_path;
        // SAFETY: `owned_src_path_text` is a sibling field that outlives `src_path`; the boxed buffer never moves.
        let input_path: &'static [u8] =
            unsafe { core::mem::transmute::<&[u8], &'static [u8]>(&owned_src_path_text) };
        OutputFile {
            loader: options.loader,
            input_loader: options.input_loader,
            src_path: fs::Path::init(input_path),
            owned_src_path_text,
            dest_path: options.output_path.clone(),
            source_index: options.source_index,
            size,
            size_without_sourcemap: options.display_size as usize,
            hash: options.hash.unwrap_or(0),
            output_kind: options.output_kind,
            bytecode_index: options.bytecode_index.unwrap_or(u32::MAX),
            module_info_index: options.module_info_index.unwrap_or(u32::MAX),
            source_map_index: options.source_map_index.unwrap_or(u32::MAX),
            is_executable: options.is_executable,
            value: match options.data {
                OptionsData::Buffer { data } => Value::Buffer { bytes: data },
                OptionsData::File { file, dir, .. } => Value::Copy('brk: {
                    let mut op = FileOperation::from_file(file, &options.output_path);
                    op.dir = dir;
                    break 'brk op;
                }),
                OptionsData::Saved(_) => Value::Saved(SavedFile::default()),
            },
            side: options.side,
            entry_point_index: options.entry_point_index,
            referenced_css_chunks: options.referenced_css_chunks,
            bake_extra: options.bake_extra,
        }
    }

    // TODO(port): narrow error set
    pub fn write_to_disk(&self, root_dir: Fd, root_dir_path: &[u8]) -> Result<(), Error> {
        match &self.value {
            Value::Noop => {}
            Value::Saved(_) => {
                // already written to disk
            }
            Value::Buffer { bytes } => {
                let mut rel_path: &[u8] = &self.dest_path;
                if self.dest_path.len() > root_dir_path.len() {
                    rel_path = resolve_path::relative(root_dir_path, &self.dest_path);
                    // Zig: `std.fs.path.dirname` returns `null` when there's no
                    // separator; the Rust port returns `b""` instead.
                    let parent = resolve_path::dirname::<platform::Auto>(rel_path);
                    if !parent.is_empty() {
                        bun_sys::Dir::borrow(&root_dir).make_path(parent)?;
                    }
                }

                let mut path_buf = PathBuffer::uninit();
                let _ = bun_sys::write_file_with_path_buffer(
                    &mut path_buf,
                    &bun_sys::WriteFileArgs {
                        data: bun_sys::WriteFileData::Buffer {
                            // Zig built a JSC ArrayBuffer view over `bytes` via
                            // `@constCast`; the Rust side just borrows the slice.
                            buffer: bytes,
                        },
                        encoding: bun_sys::WriteFileEncoding::Buffer,
                        mode: if self.is_executable { 0o755 } else { 0o644 },
                        dirfd: root_dir,
                        file: bun_sys::PathOrFileDescriptor::Path(PathString::init(rel_path)),
                    },
                )?;
            }
            Value::Move(value) => {
                self.move_to(root_dir_path, &value.pathname, root_dir)?;
            }
            Value::Copy(value) => {
                self.copy_to(root_dir_path, &value.pathname, root_dir)?;
            }
            Value::Pending(_) => unreachable!(),
        }
        Ok(())
    }

    // TODO(port): narrow error set
    pub fn move_to(&self, _: &[u8], rel_path: &[u8], dir: Fd) -> Result<(), Error> {
        let Value::Move(mv) = &self.value else {
            unreachable!()
        };
        // Zig: `std.posix.toPosixPath` + `bun.sliceTo(.., 0)` to NUL-terminate both
        // paths into stack buffers. Mirrored with `resolve_path::z` over two
        // `PathBuffer`s.
        let mut src_buf = PathBuffer::uninit();
        let mut dst_buf = PathBuffer::uninit();
        let src = resolve_path::z(mv.get_pathname(), &mut src_buf);
        let dst = resolve_path::z(rel_path, &mut dst_buf);
        bun_sys::move_file_z(mv.dir, src, dir, dst)?;
        Ok(())
    }

    // TODO(port): narrow error set
    pub fn copy_to(&self, _: &[u8], rel_path: &[u8], dir: Fd) -> Result<(), Error> {
        // PORT NOTE: Zig used `dir.stdDir().createFile(rel_path, .{})` and
        // `std.fs.cwd().openFile(...)`. Mapped to `bun_sys::openat` (which takes
        // a NUL-terminated `&ZStr`).
        let mut out_buf = PathBuffer::uninit();
        let fd_out = bun_sys::openat(
            dir,
            resolve_path::z(rel_path, &mut out_buf),
            bun_sys::O::WRONLY | bun_sys::O::CREAT | bun_sys::O::TRUNC,
            0o644,
        )?;
        let mut in_buf = PathBuffer::uninit();
        let fd_in = bun_sys::openat(
            Fd::cwd(),
            resolve_path::z(self.src_path.text, &mut in_buf),
            bun_sys::O::RDONLY,
            0,
        )?;

        #[cfg(windows)]
        {
            let _ = (fd_out, fd_in);
            // use paths instead of bun.getFdPathW()
            panic!("TODO windows");
        }
        #[cfg(not(windows))]
        {
            bun_sys::copy_file(fd_in, fd_out)?;
            Ok(())
        }
    }
}

// Zig: `pub const toJS = @import("../bundler_jsc/output_file_jsc.zig").toJS;`
// Zig: `pub const toBlob = @import("../bundler_jsc/output_file_jsc.zig").toBlob;`
// Deleted per PORTING.md — `to_js` / `to_blob` become extension-trait methods that
// live in `bun_bundler_jsc`; the base type carries no jsc reference.

// ported from: src/bundler/OutputFile.zig