Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
14 changes: 13 additions & 1 deletion src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2939,6 +2939,14 @@ pub mod bv2_impl {
};

if resolve_result.flags.is_external() {
let record: &mut ImportRecord = &mut self.graph.ast.items_import_records_mut()
[import_record.importer_source_index as usize]
.as_mut_slice()[import_record.import_record_index as usize];
record.flags.set(
bun_ast::ImportRecordFlags::IS_EXTERNAL_WITHOUT_SIDE_EFFECTS,
resolve_result.primary_side_effects_data
!= bun_ast::SideEffects::HasSideEffects,
);
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved

Expand Down Expand Up @@ -4128,7 +4136,11 @@ pub mod bv2_impl {
self.graph.input_files.append(crate::Graph::InputFile {
source: core::mem::take(source),
loader,
side_effects: loader.side_effects(),
// The loader fallback is what drops an unused JSON or text import on this path.
side_effects: match resolve_result.primary_side_effects_data {
bun_ast::SideEffects::HasSideEffects => loader.side_effects(),
declared => declared,
},
Comment thread
robobun marked this conversation as resolved.
Resolved
..Default::default()
})?;
// `ParseTask::init` takes `bun_ast::Index`; both Index newtypes
Expand Down
17 changes: 13 additions & 4 deletions src/resolver/node_fallbacks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::fs;
use crate::package_json::{PackageJSON, SideEffects};
use crate::package_json::PackageJSON;
use bun_ast::SideEffects;
use bun_options_types::bundle_enums::ModuleType;

pub const IMPORT_PATH: &[u8] = b"/bun-vfs$$/node_modules/";
Expand All @@ -15,6 +16,7 @@ pub(crate) struct FallbackModule {
// PackageJSONs and we hand out `&'static` borrows into it.
pub package_json: &'static PackageJSON,
pub code: fn() -> &'static str,
pub side_effects: SideEffects,
}

// This workaround exists to allow bun_core::runtime_embed_file to work.
Expand Down Expand Up @@ -78,10 +80,14 @@ struct FallbackSpec {
pretty: &'static [u8],
pkgjson_path: &'static [u8],
code: fn() -> &'static str,
side_effects: SideEffects,
}

macro_rules! fallback_spec {
($name:literal, $code_path:literal) => {
fallback_spec!($name, $code_path, SideEffects::NoSideEffectsPureData)

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.

🔴 Browser builds with --splitting that use a Node polyfill can now run the polyfill after a later-imported file with side effects, so source evaluation order is no longer honored. Every polyfill except sys is declared NoSideEffectsPureData at src/resolver/node_fallbacks.rs:88, and the linker's chunk_of_file in findAllImportedPartsInJSOrder.rs:30 treats such a chunk as running nothing and moves its import behind chunks that do. Polyfills like url, util, buffer and timers read globals at load, so a setup file imported after them can now replace or freeze what they capture. Fix: keep the tree-shaking value for dropping unused imports but have chunk ordering treat polyfill files as running code at load, so a used polyfill keeps its source position.

Why this was flagged

A browser build with splitting: true and several entry points where entry.js has import { EventEmitter } from "node:events"; import "./setup.js"; and setup.js freezes a prototype or replaces a global such as globalThis.URL. src/resolver/node_fallbacks.rs:88 marks the events, url, util, buffer, timers and 18 other polyfills NoSideEffectsPureData. In src/bundler/linker_context/computeCrossChunkDependencies.rs:360-367 a chunk whose files all satisfy loading_file_has_no_side_effects is marked inert, and its import is placed after chunks that run code. The polyfill chunk is therefore evaluated after setup.js even though the source imported it first. On the base branch the polyfill package.json carried no usable side-effect data, so the chunk kept source order for these eight polyfills and the polyfill captured the original global or ran before the freeze. The new test test/bundler/bundler_browser.test.ts polyfill-first.js case asserts "ReplacedURL", locking in the reordered order.

Verification: src/resolver/node_fallbacks.rs:88 defaults every polyfill to SideEffects::NoSideEffectsPureData. The cross-chunk import ORDER is decided in src/bundler/linker_context/findAllImportedPartsInJSOrder.rs:29-33, which populates chunk_of_file only for files where !loading_file_has_no_side_effects(source_index). So the polyfill chunk's import is printed after every chunk that was reached through a side-effectful file.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is still open, and it is the question in the PR description. The branch is back to the resolver-only change, so a used polyfill orders like a "sideEffects": false package under --splitting. browser/UsedNodePolyfillLoadsAfterSideEffectsWithSplitting pins that.

I built the variant that you describe: a separate value that chunk ordering reads as code that runs at load. A self-review rejected it. It needs 128 added source lines of linker state, and it keeps the polyfill in a build that uses a polyfill which the unused one requires. The notes in the description have its numbers. A maintainer decides which of the two to take.

};
($name:literal, $code_path:literal, $side_effects:expr) => {
FallbackSpec {
name: $name.as_bytes(),
index_path: ::const_format::concatcp!("/bun-vfs$$/node_modules/", $name, "/index.js")
Expand All @@ -94,6 +100,7 @@ macro_rules! fallback_spec {
)
.as_bytes(),
code: create_source_code_getter!($code_path),
side_effects: $side_effects,
}
};
}
Expand All @@ -116,7 +123,9 @@ static SPECS: [FallbackSpec; 23] = [
fallback_spec!("querystring", "node-fallbacks/querystring.js"),
fallback_spec!("stream", "node-fallbacks/stream.js"),
fallback_spec!("string_decoder", "node-fallbacks/string_decoder.js"),
fallback_spec!("sys", "node-fallbacks/sys.js"),
// Keeps its side effects: it is `export * from "util"`, and the linker does not
// initialize a `require()`d `util` for a binding imported through a file without them.
Comment on lines +126 to +127

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed. The exception for sys is a workaround for a linker gap on main: a name read through export * does not initialize a lazily loaded target. #46786 fixes that gap. This PR is a draft until it merges. The exception and its comment go then.

fallback_spec!("sys", "node-fallbacks/sys.js", SideEffects::HasSideEffects),
fallback_spec!("timers", "node-fallbacks/timers.js"),
fallback_spec!("tty", "node-fallbacks/tty.js"),
fallback_spec!("url", "node-fallbacks/url.js"),
Expand Down Expand Up @@ -155,7 +164,6 @@ fn init_modules() {
// main_fields/browser_map are never read on this code path;
// Default::default() fills them safely.
source: bun_ast::Source::init_path_string(spec.pkgjson_path, b""),
side_effects: SideEffects::False,
..Default::default()
},
fs::Path::init_with_namespace_virtual(spec.index_path, b"node", spec.pretty),
Expand All @@ -170,13 +178,14 @@ fn init_modules() {
unsafe {
*MODULES.get() = Some(modules);
let modules_ref: &'static [FallbackEntry] = (*MODULES.get()).as_deref().unwrap();
for (name, pkg, path, code) in modules_ref.iter() {
for ((name, pkg, path, code), spec) in modules_ref.iter().zip(&SPECS) {
m.put_assume_capacity(
name,
FallbackModule {
path: *path,
package_json: pkg,
code: *code,
side_effects: spec.side_effects,
},
);
}
Expand Down
1 change: 1 addition & 0 deletions src/resolver/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1956,6 +1956,7 @@ impl<'a> Resolver<'a> {
fallback_module.package_json,
));
result.flags.set_is_from_node_modules(true);
result.primary_side_effects_data = fallback_module.side_effects;
return ResultUnion::Success(result);
}

Expand Down
218 changes: 217 additions & 1 deletion test/bundler/bundler_browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from "assert";
import { describe, expect } from "bun:test";
import { itBundled } from "./expectBundled";
import { itBundled, type BundlerTestBundleAPI, type BundlerTestInput } from "./expectBundled";

describe("bundler", () => {
const nodePolyfillList = {
Expand Down Expand Up @@ -289,6 +289,222 @@ describe("bundler", () => {
},
});

// A polyfill has no side effects, so an import statement that nothing uses
// must not put it in the bundle. These are all the forms of that statement.
// The named export must exist: a name the polyfill lacks is a build error.
const unusedImportsOf = (name: string, namedExport: string) => /* js */ `
import { ${namedExport} as ${name}Named } from "node:${name}";
import { ${namedExport} as ${name}WithoutPrefix } from "${name}";
import ${name}Default from "node:${name}";
import * as ${name}Namespace from "node:${name}";
import "node:${name}";
import { ${namedExport} as ${name}ReExported } from "./re-export.js";
`;
const unusedPolyfillImportBuilds = {
cli: { backend: "cli" },
api: { backend: "api" },
// An onResolve callback that returns nothing leaves the import to the resolver.
decliningOnResolve: {
backend: "api",
plugins(builder) {
builder.onResolve({ filter: /.*/ }, () => undefined);
},
},
} satisfies Record<string, Partial<BundlerTestInput>>;
// The comment that starts each module of the bundle. A test checks this list
// before the whole text, so a failure names the polyfills and does not print them.
const bundledModules = (api: BundlerTestBundleAPI) => api.readFile("/out.js").match(/^\/\/ .+$/gm);
for (const [build, options] of Object.entries(unusedPolyfillImportBuilds)) {
itBundled(`browser/UnusedNodePolyfillImport-${build}`, {
...options,
files: {
// stream is the one polyfill that is CommonJS. crypto requires four other polyfills.
"/entry.js":
unusedImportsOf("events", "EventEmitter") +
unusedImportsOf("stream", "Readable") +
unusedImportsOf("crypto", "createHash") +
/* js */ `console.log("no polyfill");`,
"/re-export.js": /* js */ `
export { EventEmitter } from "node:events";
export { Readable } from "node:stream";
export { createHash } from "node:crypto";
`,
},
target: "browser",
run: { stdout: "no polyfill" },
onAfterBundle(api) {
expect(bundledModules(api)).toEqual(["// entry.js"]);
api.expectFile("out.js").toBe('// entry.js\nconsole.log("no polyfill");\n');
},
});
// The usual case: a package for both sides of an app. Only an export that
// the browser entry point does not import uses the builtins.
itBundled(`browser/NodePolyfillForUnusedExport-${build}`, {
...options,
files: {
"/entry.js": /* js */ `
import { forBrowser } from "both-sides";
console.log(forBrowser());
`,
"/node_modules/both-sides/package.json": /* json */ `
{ "name": "both-sides", "type": "module", "main": "./index.js" }
`,
"/node_modules/both-sides/index.js": /* js */ `
import * as events from "node:events";
import { Readable } from "stream";
export function forBrowser() {
return "for the browser";
}
export function forServer() {
return [new events.EventEmitter(), new Readable()];
}
`,
},
target: "browser",
run: { stdout: "for the browser" },
onAfterBundle(api) {
expect(bundledModules(api)).toEqual(["// node_modules/both-sides/index.js", "// entry.js"]);
},
});
}
itBundled("browser/UnusedNodePolyfillImportNextToUsedOne", {
files: {
"/entry.js": /* js */ `
import { Buffer } from "node:buffer";
import { EventEmitter } from "node:events";
const emitter = new EventEmitter();
emitter.on("hello", value => console.log(value));
emitter.emit("hello", "used events");
`,
},
target: "browser",
run: { stdout: "used events" },
onAfterBundle(api) {
expect(bundledModules(api)).toEqual(["// node:events", "// entry.js"]);
},
});
itBundled("browser/UnusedNodePolyfillImportWithSplitting", {
files: {
"/uses.js": /* js */ `
import { EventEmitter } from "node:events";
const emitter = new EventEmitter();
emitter.on("hello", value => console.log("uses", value));
emitter.emit("hello", 1);
`,
"/also-uses.js": /* js */ `
import { EventEmitter } from "node:events";
const emitter = new EventEmitter();
emitter.on("hello", value => console.log("also uses", value));
emitter.emit("hello", 2);
`,
"/unused.js": /* js */ `
import { EventEmitter } from "node:events";
console.log("unused");
`,
},
entryPoints: ["/uses.js", "/also-uses.js", "/unused.js"],
splitting: true,
outdir: "/out",
target: "browser",
run: [
{ file: "/out/uses.js", stdout: "uses 1" },
{ file: "/out/also-uses.js", stdout: "also uses 2" },
{ file: "/out/unused.js", stdout: "unused" },
],
onAfterBundle(api) {
// The polyfill is in a chunk of its own. Only its users import that chunk.
api.expectFile("/out/unused.js").toBe('// unused.js\nconsole.log("unused");\n');
},
});
// The url polyfill reads globalThis.URL when it loads. Here it has a chunk of
// its own, and a chunk with no side effects loads after the chunks that have
// some. So the polyfill sees the class that replace-url.js sets, also when
// the entry point imports the polyfill first.
itBundled("browser/UsedNodePolyfillLoadsAfterSideEffectsWithSplitting", {
files: {
"/side-effect-first.js": /* js */ `
import "./replace-url.js";
import { URL } from "node:url";
console.log(URL.name);
`,
"/polyfill-first.js": /* js */ `
import { URL } from "node:url";
import "./replace-url.js";
console.log(URL.name);
`,
"/only-polyfill.js": /* js */ `
import { URL } from "node:url";
console.log(URL.name);
`,
"/only-side-effect.js": /* js */ `
import "./replace-url.js";
console.log(globalThis.URL.name);
`,
"/replace-url.js": /* js */ `
globalThis.URL = class ReplacedURL {};
`,
},
entryPoints: ["/side-effect-first.js", "/polyfill-first.js", "/only-polyfill.js", "/only-side-effect.js"],
splitting: true,
outdir: "/out",
target: "browser",
run: [
{ file: "/out/side-effect-first.js", stdout: "ReplacedURL" },
{ file: "/out/polyfill-first.js", stdout: "ReplacedURL" },
{ file: "/out/only-polyfill.js", stdout: "URL" },
],
});
// --ignore-dce-annotations turns the side-effect data off, for a polyfill too.
itBundled("browser/UnusedNodePolyfillImportIgnoreDCEAnnotations", {
files: {
"/entry.js": /* js */ `
import { EventEmitter } from "node:events";
console.log("polyfill kept");
`,
},
target: "browser",
ignoreDCEAnnotations: true,
run: { stdout: "polyfill kept" },
onAfterBundle(api) {
expect(bundledModules(api)).toEqual(["// node:events", "// entry.js"]);
},
});
// require() and import() are expressions. They load the polyfill when they
// run, so the polyfill stays in the bundle.
itBundled("browser/UnusedRequireAndDynamicImportKeepNodePolyfill", {
files: {
"/entry.js": /* js */ `
require("node:events");
await import("node:buffer");
console.log("loaded");
`,
},
target: "browser",
run: { stdout: "loaded" },
onAfterBundle(api) {
expect(bundledModules(api)).toEqual(["// node:events", "// node:buffer", "// entry.js"]);
},
});
// sys is `export * from "util"`, and the assert polyfill loads util with
// require(). sys keeps its side effects: they are what initializes that util
// before uses-sys.js reads a binding of it.
itBundled("browser/NodeSysNextToPolyfillThatRequiresUtil", {
files: {
"/entry.js": /* js */ `
import "./uses-sys.js";
import assert from "node:assert";
assert.ok(true);
`,
"/uses-sys.js": /* js */ `
import { inspect } from "node:sys";
import * as sys from "node:sys";
console.log(inspect({ a: 1 }), sys.format("%s:%d", "b", 2));
`,
},
target: "browser",
run: { stdout: "{ a: 1 } b:2" },
});

// #4928: a package.json "browser": {"<builtin>": false} must win over the
// builtin polyfill for --target browser. Packages set this to keep their
// node-only code paths from dragging crypto/stream/buffer into browser bundles.
Expand Down
Loading
Loading