Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
d0d0e1a
bundler: chain inline input sourcemaps through to output
robobun May 12, 2026
f6b51a4
[autofix.ci] apply automated fixes
autofix-ci[bot] May 12, 2026
016f23a
test: cover plugin onLoad with inline sourcemap (#6173)
robobun May 12, 2026
b099186
address review findings: OOM, leak, test guards
robobun May 12, 2026
547b6bf
sourcemap: anchor findSourceMappingURL to the final line
robobun May 12, 2026
1fccb33
address 3 review findings from claude[bot]
robobun May 12, 2026
7a3846f
ci: retrigger
robobun May 12, 2026
75367ca
test: gate chained-sourcemap tests behind describe.todo
robobun May 16, 2026
51a9e81
bundler: chain inline input sourcemaps through to output (Rust port)
robobun May 16, 2026
e1671a0
[autofix.ci] apply automated fixes
autofix-ci[bot] May 16, 2026
3713d81
sourcemap: trim whitespace on both sides of the URL after sourceMappi…
robobun May 19, 2026
535e210
bundler: init Graph::InputFile.input_source_map in Default impl
robobun May 20, 2026
34c2754
sourcemap: drop unused Mapping import from InputSourceMap.rs
robobun May 20, 2026
e537faf
bundler: hoist source_map option before get_ast to avoid stacked-borr…
robobun May 20, 2026
a64c487
sourcemap: drop redundant mut on estr bindings (-D unused-mut)
robobun Jun 2, 2026
c94b771
sourcemap: hint find_line_with_hint from intermediate line, not remapped
robobun Jun 2, 2026
087e032
[autofix.ci] apply automated fixes
autofix-ci[bot] Jun 2, 2026
598d4b9
sourcemap: align comments with main's port-note cleanup
robobun Jun 6, 2026
dce162d
sourcemap: route write_sources_for paths through source_map_relative_…
robobun Jun 27, 2026
76692b4
sourcemap: use Number::value() accessor (field now private)
robobun Jun 27, 2026
fd7c85e
bundler: cap inline-sourcemap source names; isolate chain tests
robobun Jun 27, 2026
0b19392
test: run inline-sourcemap chain suite concurrently
robobun Jun 27, 2026
1f43f04
test: size oversized-name case past the largest platform MAX_PATH_BYTES
robobun Jun 27, 2026
2fa050b
sourcemap: adapt InputSourceMap to renamed json parse and Result-base…
robobun Aug 15, 2026
ab718e9
sourcemap: read inline maps through the tape-based JSON accessors
robobun Aug 15, 2026
d32e42a
sourcemap: trim explanatory comments to their load-bearing core
robobun Aug 15, 2026
1c77746
sourcemap: use bun_core::strings helpers for byte search (source lint)
robobun Aug 15, 2026
eefe63f
bundler: skip inline-map scan under DevServer; pass URL-schemed sourc…
robobun Aug 15, 2026
1e8554f
bundler: emit inner source names verbatim for virtual-namespace modules
robobun Aug 15, 2026
1daf82f
sourcemap: strip the inline-map comment from slot-0 sourcesContent
robobun Aug 23, 2026
a0c5ca3
sourcemap: track comment_start as Option so offset 0 still truncates
robobun Aug 23, 2026
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
6 changes: 6 additions & 0 deletions src/bundler/Graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ pub struct InputFile {
pub unique_key_for_additional_file: Box<[u8], AstAlloc>,
pub content_hash_for_additional_file: u64,
pub flags: InputFileFlags,
/// Decoded inline `//# sourceMappingURL=data:...` map for this file;
/// the linker expands `sources[]`/`sourcesContent[]` with its entries
/// and `Chunk::Builder` remaps mappings through it. Usually `None`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub input_source_map: Option<Box<bun_sourcemap::InputSourceMap>>,
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

impl Default for InputFile {
Expand All @@ -125,6 +129,7 @@ impl Default for InputFile {
unique_key_for_additional_file: AstAlloc::vec().into_boxed_slice(),
content_hash_for_additional_file: 0,
flags: InputFileFlags::default(),
input_source_map: None,
}
}
}
Expand All @@ -142,6 +147,7 @@ bun_collections::multi_array_columns! {
unique_key_for_additional_file: Box<[u8], AstAlloc>,
content_hash_for_additional_file: u64,
flags: InputFileFlags,
input_source_map: Option<Box<bun_sourcemap::InputSourceMap>>,
}
}

Expand Down
235 changes: 172 additions & 63 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1049,89 +1049,108 @@ impl<'a> LinkerContext<'a> {

let sources = self.parse_graph().input_files.items_source();
let quoted_source_map_contents = self.graph.files.items_quoted_source_contents();
// DevServer's stitcher (`SourceMapStore::join_vlq`) assumes one
// `sources[]` slot per input, so chaining is gated to `Bun.build`.
Comment thread
robobun marked this conversation as resolved.
Resolved
let input_source_maps: Option<&[Option<Box<bun_sourcemap::InputSourceMap>>]> =
if self.dev_server.is_none() {
Some(self.parse_graph().input_files.items_input_source_map())
} else {
None
};

// Entries in `results` do not 1:1 map to source files, the mapping
// is actually many to one, where a source file can have multiple chunks
// in the sourcemap.
//
// This hashmap is going to map:
// `source_index` (per compilation) in a chunk
// -->
// Which source index in the generated sourcemap, referred to
// as the "mapping source index" within this function to be distinct.
// Many-to-one: a source file can own several chunks. Maps each
// compilation `source_index` to its base index in the generated
// `sources[]`; a file with an inline map spans
// `base ..= base + external_source_names.len`.
Comment thread
robobun marked this conversation as resolved.
Resolved
let mut source_id_map: ArrayHashMap<u32, i32> = ArrayHashMap::new();

let source_indices = results.items_source_index();

j.push_static(b"{\n \"version\": 3,\n \"sources\": [");
let mut next_mapping_source_index: i32 = 0;
if !source_indices.is_empty() {
{
let index = source_indices[0];
let path = &sources[index as usize].path;
source_id_map.put_no_clobber(index, 0)?;

// Note: the relative path lives in a local owned buffer
// (drops at scope exit).
let rel_path_storage;
let pretty: &[u8] = if path.is_file() {
rel_path_storage = Self::source_map_relative_path(chunk_abs_dir, path.text)?;
&rel_path_storage
} else {
path.pretty
};

let mut quote_buf = MutableString::init(pretty.len() + 2)?;
js_printer::quote_for_json(pretty, &mut quote_buf, false)?;
// `to_default_owned` moves the buffer into the joiner
// (joiner owns it until `done`).
j.push_owned(quote_buf.to_default_owned());
}

let mut next_mapping_source_index: i32 = 1;
for &index in &source_indices[1..] {
for (chunk_i, &index) in source_indices.iter().enumerate() {
let gop = source_id_map.get_or_put(index)?;
if gop.found_existing {
continue;
}

*gop.value_ptr = next_mapping_source_index;
next_mapping_source_index += 1;

let path = &sources[index as usize].path;

let rel_path_storage;
let pretty: &[u8] = if path.is_file() {
rel_path_storage = Self::source_map_relative_path(chunk_abs_dir, path.text)?;
&rel_path_storage
} else {
path.pretty
// `1` for the intermediate input, plus one slot per inner
// source listed in its `sourceMappingURL`.
Comment thread
robobun marked this conversation as resolved.
Resolved
let inner: Option<&bun_sourcemap::InputSourceMap> =
input_source_maps.and_then(|m| m[index as usize].as_deref());
let expansion: i32 = 1 + match inner {
Some(ism) => {
i32::try_from(ism.map.external_source_names.len()).expect("int cast")
}
None => 0,
};

let mut quote_buf = MutableString::init(pretty.len() + ", ".len() + 2)?;
quote_buf.append_assume_capacity(b", ");
js_printer::quote_for_json(pretty, &mut quote_buf, false)?;
j.push_owned(quote_buf.to_default_owned());
next_mapping_source_index += expansion;

write_sources_for(
&mut j,
chunk_abs_dir,
&sources[index as usize].path,
inner,
chunk_i > 0,
)?;
}
}

j.push_static(b"],\n \"sourcesContent\": [");

let source_indices_for_contents = source_id_map.keys();
if !source_indices_for_contents.is_empty() {
j.push_static(b"\n ");
j.push_static(
quoted_source_map_contents[source_indices_for_contents[0] as usize]
.as_deref()
.unwrap_or(b""),
);

for &index in &source_indices_for_contents[1..] {
j.push_static(b",\n ");
j.push_static(
quoted_source_map_contents[index as usize]
.as_deref()
.unwrap_or(b""),
);
let mut emitted_contents: usize = 0;
for &index in source_indices_for_contents.iter() {
// Slot 0: the intermediate input file's contents (already
// JSON-quoted by `compute_quoted_source_contents`).
Comment thread
robobun marked this conversation as resolved.
Resolved
{
let sep: &[u8] = if emitted_contents == 0 {
b"\n "
} else {
b",\n "
};
j.push_static(sep);
// For a chained file, strip the trailing comment from
// slot 0: the inner map would otherwise ship twice
// (base64 here + decoded in slots 1..N).
Comment on lines +1116 to +1118

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

let file_contents: &[u8] = &sources[index as usize].contents;
let comment_start = input_source_maps
.and_then(|m| m[index as usize].as_deref())
.and_then(|ism| ism.comment_start)
.filter(|&start| start <= file_contents.len());
match comment_start {
Some(start) => {
let truncated = &file_contents[..start];
let mut quote_buf = MutableString::init(truncated.len() + 2)?;
js_printer::quote_for_json(truncated, &mut quote_buf, false)?;
Comment on lines +1119 to +1128

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 The guard ism.comment_start > 0 conflates byte offset 0 with "unset": when the file has no newline before its final line (e.g. a plugin onLoad returns only //# sourceMappingURL=data:...), find_source_mapping_url returns comment_start = 0, so this falls through to the _ arm and ships the full base64 comment as slot-0 sourcesContent — the double-shipping this block exists to prevent. Since the bundler only populates input_source_map via parse_from_source (never raw parse), comment_start is always a real offset here; drop the > 0 check (keep <= file_contents.len()) or make the sentinel Option<usize>/usize::MAX.

Extended reasoning...

What the bug is

The match guard at LinkerContext.rs:1122 tests ism.comment_start > 0 && ism.comment_start <= file_contents.len() to decide whether to emit slot-0 sourcesContent truncated at the inline-map comment (the intent of commit 1daf82f, "strip the inline-map comment from slot-0 sourcesContent"). The > 0 half is meant to distinguish "set by parse_from_source" from "unset by raw parse()" (InputSourceMap.rs:150 initializes comment_start: 0 in parse_internal, and the field's doc comment says "0 when parsed from raw JSON"). But 0 is also a valid byte offset returned by find_source_mapping_url — so the guard gates on truthiness where it should gate on presence.

The specific code path that triggers it

In find_source_mapping_url (InputSourceMap.rs:174-184):

let last_line_start = match bun_core::strings::last_index_of_char(body, b'\n') {
    Some(i) => i + 1,
    None => 0,
};
...
let comment_start = last_line_start;

When the whitespace-trimmed body contains no \n, last_line_start = 0, so comment_start = 0. This is a legitimate byte offset meaning "the //# sourceMappingURL= comment starts at byte 0 of the file". A plugin onLoad returning { contents: "//# sourceMappingURL=data:application/json;base64,<...>", loader: "js" } (no leading code, no leading newline) — pathological but valid JS and reachable via the #6173 plugin path this PR targets — produces exactly this.

Why existing code doesn't prevent it

The only producer of input_source_map in the bundler graph is InputSourceMap::parse_from_source (ParseTask.rs:2700); ServerComponentParseTask.rs:205 sets None. Raw InputSourceMap::parse (which sets comment_start = 0 as a genuine "unset" sentinel) is never reached from the bundler, so every ism reaching this match arm has comment_start set to a real byte offset. The > 0 check therefore has no legitimate "unset" case to reject here — it only creates a false negative for the comment_start == 0 case.

None of the 11 tests in bun-build-inline-sourcemap-chain.test.ts exercise a single-line-comment-only intermediate; they all prefix the comment with at least one line of code plus a \n.

Step-by-step proof

Take a plugin onLoad returning contents = "//# sourceMappingURL=data:application/json;base64,eyJ2ZXJz..." (no leading newline, no trailing newline):

  1. ParseTask.rs:2700 — InputSourceMap::parse_from_source(&source.contents) is called (gates pass: !has_dev_server, source_map != None, loader.can_have_source_map(), !contents.is_empty()).
  2. InputSourceMap.rs:160-168 — trailing-whitespace trim: no trailing whitespace, so body = source.
  3. InputSourceMap.rs:174 — last_index_of_char(body, b'\n') → None (no newline in body) → last_line_start = 0.
  4. InputSourceMap.rs:178-184 — last_line = &body[0..] starts with //# sourceMappingURL= ✓ → comment_start = 0. The data URL parses successfully → map.comment_start = 0.
  5. bundle_v2.rs:7142 — moved into graph.input_files.items_input_source_map_mut()[idx].
  6. LinkerContext.rs:1120-1123 — input_source_maps.and_then(...) → Some(ism) with ism.comment_start == 0. Guard evaluates 0 > 0 → false.
  7. LinkerContext.rs:1130-1135 — falls through to the _ arm: emits quoted_source_map_contents[index], which is the JSON-quoted full file contents — i.e. the entire //# sourceMappingURL=data:...;base64,<payload> string.
  8. LinkerContext.rs:1140-1152 — slots 1..N then emit the decoded inner sourcesContent[i].

Result: the inner map ships twice in the output sourcesContent[] — once base64-encoded in slot 0, once decoded in slots 1..N — exactly the bloat the comment_start truncation exists to prevent. Mappings and source resolution are unaffected (they don't read sourcesContent), so correctness is fine; only output size regresses on this input shape.

How to fix it

This is REVIEW.md's "Treat empty, zero, and unset as three distinct states — gate on presence, not truthiness" rule verbatim. Two options:

  • Minimal: drop the > 0 half of the guard, keeping only ism.comment_start <= file_contents.len(). Since every ism reaching this code came from parse_from_source, comment_start is always a valid slice index (including 0), and &file_contents[..0] correctly yields b"" → slot 0 emits "".
  • Structural: change InputSourceMap.comment_start to Option<usize> (or use usize::MAX as the sentinel in parse_internal) so "unset" and "offset 0" are representationally distinct — then the guard becomes if let Some(start) = ism.comment_start and the ambiguity disappears at the type level.

Nit-level because the trigger requires a file whose entire non-whitespace content is the sourceMappingURL comment (only a plugin onLoad returning nothing but the comment would produce it), and the impact is output-size bloat only.

j.push_owned(quote_buf.to_default_owned());
}
None => {
let content = quoted_source_map_contents[index as usize]
.as_deref()
.unwrap_or(b"null");
j.push_static(if content.is_empty() { b"null" } else { content });
}
}
emitted_contents += 1;
}
// Slots 1..N: inner sources' contents, if any.
if let Some(ism) = input_source_maps.and_then(|m| m[index as usize].as_deref()) {
for content in ism.sources_content.iter() {
j.push_static(b",\n ");
if !content.is_empty() {
let mut quote_buf = MutableString::init(content.len() + 2)?;
js_printer::quote_for_json(content, &mut quote_buf, false)?;
j.push_owned(quote_buf.to_default_owned());
} else {
j.push_static(b"null");
}
emitted_contents += 1;
}
}
}
}
j.push_static(b"\n ],\n \"mappings\": \"");
Expand Down Expand Up @@ -1171,7 +1190,9 @@ impl<'a> LinkerContext<'a> {
)?;

prev_end_state = chunk.end_state;
prev_end_state.source_index = mapping_source_index;
// `chunk.end_state.source_index` is chunk-relative (0 without an
// inline map); rebase it onto this file's slot base.
Comment thread
robobun marked this conversation as resolved.
Resolved
prev_end_state.source_index = mapping_source_index + chunk.end_state.source_index;
prev_column_offset = chunk.final_generated_column;

if prev_end_state.generated_line == 0 {
Expand Down Expand Up @@ -1215,6 +1236,85 @@ impl<'a> LinkerContext<'a> {
}
}

/// Emit one outer source's quoted path plus its chained inner paths, in
/// the slot layout `Chunk::Builder` emits against: slot 0 = the outer
/// file, slots 1..N = inner `sources[i]`.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn write_sources_for(
joiner: &mut StringJoiner,
chunk_abs_dir: &[u8],
outer_path: &bun_paths::fs::Path,
input_map: Option<&bun_sourcemap::InputSourceMap>,
leading_comma: bool,
) -> Result<(), BunError> {
// 1) the intermediate input.
let rel_path_storage;
let pretty: &[u8] = if outer_path.is_file() {
rel_path_storage = LinkerContext::source_map_relative_path(chunk_abs_dir, outer_path.text)?;
&rel_path_storage
} else {
outer_path.pretty
};
{
let mut quote_buf = MutableString::init(pretty.len() + ", ".len() + 2)?;
if leading_comma {
quote_buf.append_assume_capacity(b", ");
}
js_printer::quote_for_json(pretty, &mut quote_buf, false)?;
joiner.push_owned(quote_buf.to_default_owned());
}

// 2) inner sources: resolve each against the intermediate's dir, then
// re-relativize to `chunk_abs_dir` for the emitted JSON.
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(ism) = input_map {
let emit = |joiner: &mut StringJoiner, p: &[u8]| -> Result<(), BunError> {
let mut quote_buf = MutableString::init(p.len() + ", ".len() + 2)?;
quote_buf.append_assume_capacity(b", ");
js_printer::quote_for_json(p, &mut quote_buf, false)?;
joiner.push_owned(quote_buf.to_default_owned());
Ok(())
};
// A non-file intermediate (plugin virtual module) has no directory
// to resolve against; emit inner names verbatim.
Comment on lines +1276 to +1277

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

if !outer_path.is_file() {
for name in ism.map.external_source_names.iter() {
emit(joiner, name.as_ref())?;
}
return Ok(());
}
let base_dir = bun_paths::resolve_path::dirname::<bun_paths::resolve_path::platform::Auto>(
outer_path.text,
);
let mut join_buf = bun_paths::path_buffer_pool::get();
for name in ism.map.external_source_names.iter() {
let name: &[u8] = name.as_ref();
// The spec allows URLs in `sources[]` (e.g. `webpack:///src/a.ts`);
// path-joining would destroy the scheme, so pass them through.
Comment thread
robobun marked this conversation as resolved.
Resolved
if bun_core::strings::index_of(name, b"://").is_some() {
emit(joiner, name)?;
continue;
}
if bun_paths::resolve_path::Platform::AUTO.is_absolute(name) {
let rel = LinkerContext::source_map_relative_path(chunk_abs_dir, name)?;
emit(joiner, &rel)?;
continue;
}
// The checked join returns `None` on overflow (adversarial
// map); emit the raw, spec-valid name instead of panicking.
Comment thread
robobun marked this conversation as resolved.
Resolved
match bun_paths::resolve_path::join_abs_string_buf_checked::<
bun_paths::resolve_path::platform::Auto,
>(base_dir, join_buf.as_mut_slice(), &[name])
{
Some(abs_path) => {
let rel = LinkerContext::source_map_relative_path(chunk_abs_dir, abs_path)?;
emit(joiner, &rel)?;
}
None => emit(joiner, name)?,
}
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}
Ok(())
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ScanCssImportsResult {
Ok,
Expand Down Expand Up @@ -2198,6 +2298,14 @@ impl<'a> LinkerContext<'a> {
// SAFETY: `self.mangled_props` is not mutated during printing; detached borrow
// outlives only this call (see above).
unsafe { bun_ptr::detach_lifetime_ref(&self.mangled_props) };
// DevServer's stitcher assumes one `sources[]` slot per file;
// chaining is gated to the `Bun.build` path.
Comment thread
robobun marked this conversation as resolved.
Resolved
let input_source_map: Option<&bun_sourcemap::InputSourceMap> = if self.dev_server.is_none()
{
parse_graph.input_files.items_input_source_map()[source_index.get() as usize].as_deref()
} else {
None
};

let print_options = js_printer::Options {
bundling: true,
Expand Down Expand Up @@ -2246,6 +2354,7 @@ impl<'a> LinkerContext<'a> {
} else {
None
},
input_source_map,
mangled_props: Some(mangled_props),
module_info,
..Default::default()
Expand Down
26 changes: 26 additions & 0 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ pub(crate) struct Success {

/// The package name from package.json, used for barrel optimization.
pub(crate) package_name: ast::StoreStr,

/// Decoded trailing inline `//# sourceMappingURL=data:...` map; `None`
/// when absent, disabled, or malformed. Moved into
/// `graph.input_files.input_source_map` by `on_parse_task_complete`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) input_source_map: Option<Box<bun_sourcemap::InputSourceMap>>,
}

pub(crate) struct ResultError {
Expand Down Expand Up @@ -2621,6 +2626,11 @@ pub mod parse_worker {
// SAFETY: task.ctx backref valid for the bundle pass (outlives `'r`).
let task_ctx = unsafe { task.ctx() };
let module_type = opts.module_type;
// Copy these out before the tombstone: get_ast reborrows
// `(*transpiler).options` mutably, invalidating `topts` under
// Stacked Borrows.
Comment thread
robobun marked this conversation as resolved.
Resolved
let source_map_option = topts.source_map;
let has_dev_server = topts.has_dev_server();
// `topts` (a `&BundleOptions`) is dead past this point; the callees take
// raw `*mut Transpiler` and reborrow `(*transpiler).options` mutably.
let _ = topts;
Expand Down Expand Up @@ -2681,6 +2691,20 @@ pub mod parse_worker {

*step = Step::Resolve;

// Scan for an inline `//# sourceMappingURL=data:...` map to chain
// into the output sourcemap. Runs on `source.contents` regardless
// of origin (file read or plugin `onLoad`, covering #6173). Skipped
// under DevServer: its stitcher never consumes the result.
Comment thread
robobun marked this conversation as resolved.
Resolved
let input_source_map: Option<Box<bun_sourcemap::InputSourceMap>> = if !has_dev_server
&& source_map_option != options::SourceMapOption::None
&& loader.can_have_source_map()
&& !source.contents.is_empty()
{
bun_sourcemap::InputSourceMap::parse_from_source(&source.contents)
} else {
None
};

Ok(Success {
ast,
source: source.clone(),
Expand All @@ -2693,6 +2717,8 @@ pub mod parse_worker {

// Hash the files in here so that we do it in parallel.
content_hash_for_additional_file: unique_key_for_additional_file.content_hash,

input_source_map,
})
}

Expand Down
2 changes: 2 additions & 0 deletions src/bundler/ServerComponentParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ fn task_callback(
unique_key_for_additional_file: bun_ast::StoreStr::EMPTY,
content_hash_for_additional_file: 0,
package_name: bun_ast::StoreStr::EMPTY,
// Generated wrapper: nothing to chain.
input_source_map: None,
})
}

Expand Down
Loading
Loading