Skip to content
Merged
Show file tree
Hide file tree
Changes from 62 commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
6c27927
implement onEnd()
alii Aug 23, 2025
47d4336
tidy a bit
alii Aug 23, 2025
2d323f3
changes + onResolve regression test
alii Aug 23, 2025
0db31cb
make it so
alii Aug 23, 2025
c8e08a5
rm
alii Aug 23, 2025
3a96364
fix regression test
alii Aug 23, 2025
78c16e0
yay
alii Aug 23, 2025
5f6954f
fix p resolution
alii Aug 23, 2025
2a91661
waffle
alii Aug 23, 2025
286324d
suggestions
alii Aug 23, 2025
27493d5
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 23, 2025
4a17d83
fix
alii Aug 23, 2025
e633727
onEndCallbacks needn't exist in cpp
alii Aug 23, 2025
a6ea4db
rip out this old test
alii Aug 23, 2025
0dd25a1
these are crashing
alii Aug 23, 2025
52c11dc
bundler plugin onResolve basic fuzzer
alii Aug 23, 2025
5e29a08
fix test name
alii Aug 23, 2025
3778c63
feels plausible
alii Aug 23, 2025
ce44cb3
only validate namespace itf it's strictly specified
alii Aug 23, 2025
566654b
try this
alii Aug 24, 2025
40f643d
claener
alii Aug 24, 2025
f8e2fa6
checkpoint
alii Aug 24, 2025
7886428
okay great it works
alii Aug 24, 2025
00d47ea
remove thenWithJSValueCtx
alii Aug 24, 2025
0abb980
fix
alii Aug 24, 2025
c442739
rip onresolve change for now
alii Aug 24, 2025
a72d2e9
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 24, 2025
0c2e32d
refactor to js part one
alii Aug 24, 2025
2f4249b
move
alii Aug 24, 2025
fc27de6
part two
alii Aug 24, 2025
4da40ce
part three
alii Aug 24, 2025
4b06fd1
fix: pass the promise
alii Aug 24, 2025
40a76cb
fix compilation
alii Aug 24, 2025
b53476e
for now, remove onResolve in entrypoint failing tests
alii Aug 24, 2025
fccf9c8
2/3 suggestions
alii Aug 25, 2025
0e4c0c5
change
alii Aug 25, 2025
fd3424f
better naming
alii Aug 25, 2025
0c63be8
update jsdoc for .throw
alii Aug 25, 2025
0c6813f
fix
alii Aug 25, 2025
02b513d
add passing tests
alii Aug 25, 2025
ef986f1
Merge branch 'main' into ali/unplugin-bundler-changes
alii Aug 25, 2025
2fa54f7
docs
alii Aug 25, 2025
b28afb7
check exception
alii Aug 25, 2025
b4aaf54
reject the promise, not eat the exception
alii Aug 25, 2025
c7df84b
checkpoint
alii Aug 25, 2025
3ac2026
checkpoint
alii Aug 25, 2025
71cab05
remove tests that dont do anything actually
alii Aug 25, 2025
8058c03
implement .throw in itBundled()
alii Aug 25, 2025
9bb8ecd
fix expected build error
alii Aug 25, 2025
a02011f
update tests
alii Aug 25, 2025
e518ebf
more test coverage
alii Aug 25, 2025
4b8c936
fix: test wasnt running
alii Aug 25, 2025
e885fe1
onResolve entrypoint tests
alii Aug 25, 2025
339977d
implement the better onResolve handling
alii Aug 26, 2025
120ee00
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 26, 2025
210d933
fix leak in entry_point_original_names
alii Aug 26, 2025
384d389
make IndexStringList
alii Aug 26, 2025
4a0fcf9
fix
alii Aug 26, 2025
7da0457
fix compilation error
alii Aug 26, 2025
16fc0af
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 26, 2025
d85ba49
cleaner
alii Aug 26, 2025
e4a8800
it's actually a map
alii Aug 26, 2025
37442ab
PR Review comments
alii Aug 26, 2025
eac1e7d
`bun scripts/glob-sources.mjs`
alii Aug 26, 2025
1509a6e
Merge branch 'main' into ali/onresolve-entrypoint-bundler-fix
alii Aug 26, 2025
cdc8de3
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 26, 2025
53049d5
Merge branch 'main' into ali/onresolve-entrypoint-bundler-fix
alii Aug 26, 2025
2b531e1
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 26, 2025
3bc07b9
fix: use bun.handleOom()
alii Aug 26, 2025
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
1 change: 1 addition & 0 deletions cmake/sources/ZigSources.txt
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,7 @@ src/bundler/DeferredBatchTask.zig
src/bundler/entry_points.zig
src/bundler/Graph.zig
src/bundler/HTMLImportManifest.zig
src/bundler/IndexStringMap.zig
src/bundler/linker_context/computeChunks.zig
src/bundler/linker_context/computeCrossChunkDependencies.zig
src/bundler/linker_context/convertStmtsForChunk.zig
Expand Down
30 changes: 28 additions & 2 deletions docs/bundler/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1259,6 +1259,33 @@ $ bun build ./index.tsx --outdir ./out --drop=console --drop=debugger --drop=any

{% /codetabs %}

### `throw`

Controls error handling behavior when the build fails. When set to `true` (default), the returned promise rejects with an `AggregateError`. When set to `false`, the promise resolves with a `BuildOutput` object where `success` is `false`.

```ts#JavaScript
// Default behavior: throws on error
try {
await Bun.build({
entrypoints: ['./index.tsx'],
throw: true, // default
});
} catch (error) {
// Handle AggregateError
console.error("Build failed:", error);
}

// Alternative: handle errors via success property
const result = await Bun.build({
entrypoints: ['./index.tsx'],
throw: false,
});

if (!result.success) {
console.error("Build failed with errors:", result.logs);
}
```

## Outputs

The `Bun.build` function returns a `Promise<BuildOutput>`, defined as:
Expand Down Expand Up @@ -1569,8 +1596,7 @@ interface BuildConfig {
* When set to `true`, the returned promise rejects with an AggregateError when a build failure happens.
* When set to `false`, the `success` property of the returned object will be `false` when a build failure happens.
*
* This defaults to `false` in Bun 1.1 and will change to `true` in Bun 1.2
* as most usage of `Bun.build` forgets to check for errors.
* This defaults to `true`.
*/
throw?: boolean;
}
Expand Down
49 changes: 49 additions & 0 deletions docs/bundler/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Plugins can register callbacks to be run at various points in the lifecycle of a
- [`onStart()`](#onstart): Run once the bundler has started a bundle
- [`onResolve()`](#onresolve): Run before a module is resolved
- [`onLoad()`](#onload): Run before a module is loaded.
- [`onEnd()`](#onend): Run after the bundle has completed
- [`onBeforeParse()`](#onbeforeparse): Run zero-copy native addons in the parser thread before a file is parsed.

### Reference
Expand All @@ -18,6 +19,7 @@ A rough overview of the types (please refer to Bun's `bun.d.ts` for the full typ
```ts
type PluginBuilder = {
onStart(callback: () => void): void;
onEnd(callback: (result: BuildOutput) => void | Promise<void>): void;
onResolve: (
args: { filter: RegExp; namespace?: string },
callback: (args: { path: string; importer: string }) => {
Expand Down Expand Up @@ -285,6 +287,53 @@ plugin({

Note that the `.defer()` function currently has the limitation that it can only be called once per `onLoad` callback.

### `onEnd`

```ts
onEnd(callback: (result: BuildOutput) => void | Promise<void>): void;
```

Registers a callback to be run when the bundler completes a bundle (whether successful or not).

The callback receives the `BuildOutput` object containing:

- `success`: boolean indicating if the build succeeded
- `outputs`: array of generated build artifacts
- `logs`: array of build messages (warnings, errors, etc.)

This is useful for post-processing, cleanup, notifications, or custom error handling.

```ts
await Bun.build({
entrypoints: ["./index.ts"],
outdir: "./out",
plugins: [
{
name: "onEnd example",
setup(build) {
build.onEnd(result => {
if (result.success) {
console.log(
`✅ Build succeeded with ${result.outputs.length} outputs`,
);
} else {
console.error(`❌ Build failed with ${result.logs.length} errors`);
}
});
},
},
],
});
```

The `onEnd` callbacks are called:

- **Before** the build promise resolves or rejects
- **After** all bundling is complete
- **In the order** they were registered

Multiple plugins can register `onEnd` callbacks, and they will all be called sequentially. If an `onEnd` callback returns a promise, the build will wait for it to resolve before continuing.

## Native plugins

One of the reasons why Bun's bundler is so fast is that it is written in native code and leverages multi-threading to load and parse modules in parallel.
Expand Down
27 changes: 24 additions & 3 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1814,9 +1814,10 @@ declare module "bun" {
drop?: string[];

/**
* When set to `true`, the returned promise rejects with an AggregateError when a build failure happens.
* When set to `false`, the `success` property of the returned object will be `false` when a build failure happens.
* This defaults to `true`.
* - When set to `true`, the returned promise rejects with an AggregateError when a build failure happens.
* - When set to `false`, returns a {@link BuildOutput} with `{success: false}`
*
* @default true
*/
throw?: boolean;

Expand Down Expand Up @@ -5485,6 +5486,7 @@ declare module "bun" {
type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject | undefined | void;
type OnLoadCallback = (args: OnLoadArgs) => OnLoadResult | Promise<OnLoadResult>;
type OnStartCallback = () => void | Promise<void>;
type OnEndCallback = (result: BuildOutput) => void | Promise<void>;

interface OnResolveArgs {
/**
Expand Down Expand Up @@ -5562,6 +5564,25 @@ declare module "bun" {
* @returns `this` for method chaining
*/
onStart(callback: OnStartCallback): this;
/**
* Register a callback which will be invoked when bundling ends. This is
* called after all modules have been bundled and the build is complete.
*
* @example
* ```ts
* const plugin: Bun.BunPlugin = {
* name: "my-plugin",
* setup(builder) {
* builder.onEnd((result) => {
* console.log("bundle just finished!!", result);
* });
* },
* };
* ```
*
* @returns `this` for method chaining
*/
onEnd(callback: OnEndCallback): this;
onBeforeParse(
constraints: PluginConstraints,
callback: {
Expand Down
21 changes: 21 additions & 0 deletions src/bun.js/api/JSBundler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,27 @@ pub const JSBundler = struct {
}

extern fn JSBundlerPlugin__tombstone(*Plugin) void;
extern fn JSBundlerPlugin__runOnEndCallbacks(*Plugin, jsc.JSValue, jsc.JSValue, jsc.JSValue) jsc.JSValue;

pub fn runOnEndCallbacks(this: *Plugin, globalThis: *jsc.JSGlobalObject, build_promise: *jsc.JSPromise, build_result: jsc.JSValue, rejection: jsc.JSValue) JSError!jsc.JSValue {
jsc.markBinding(@src());

var scope: jsc.CatchScope = undefined;
scope.init(globalThis, @src());
defer scope.deinit();

const value = JSBundlerPlugin__runOnEndCallbacks(
this,
build_promise.asValue(globalThis),
build_result,
rejection,
);

try scope.returnIfException();

return value;
}

pub fn deinit(this: *Plugin) void {
jsc.markBinding(@src());
JSBundlerPlugin__tombstone(this);
Expand Down
30 changes: 30 additions & 0 deletions src/bun.js/bindings/JSBundlerPlugin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ class JSBundlerPlugin final : public JSC::JSNonFinalObject {
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> onLoadFunction;
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> onResolveFunction;
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> setupFunction;

JSC::JSGlobalObject* m_globalObject;

private:
Expand Down Expand Up @@ -626,6 +627,7 @@ extern "C" JSC::EncodedJSValue JSBundlerPlugin__runSetupFunction(

auto result = JSC::profiledCall(lexicalGlobalObject, ProfilingReason::API, setupFunction, callData, plugin, arguments);
RETURN_IF_EXCEPTION(scope, {}); // should be able to use RELEASE_AND_RETURN, no? observed it returning undefined with exception active

return JSValue::encode(result);
}

Expand All @@ -652,6 +654,34 @@ extern "C" void JSBundlerPlugin__tombstone(Bun::JSBundlerPlugin* plugin)
plugin->plugin.tombstone();
}

extern "C" JSC::EncodedJSValue JSBundlerPlugin__runOnEndCallbacks(Bun::JSBundlerPlugin* plugin, JSC::EncodedJSValue encodedBuildPromise, JSC::EncodedJSValue encodedBuildResult, JSC::EncodedJSValue encodedRejection)
{
auto& vm = plugin->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto* globalObject = plugin->globalObject();

// TODO: have a prototype for JSBundlerPlugin that this is put on instead of re-creating the function on each usage
auto* runOnEndCallbacksFn = JSC::JSFunction::create(vm, globalObject,
WebCore::bundlerPluginRunOnEndCallbacksCodeGenerator(vm), globalObject);

JSC::CallData callData = JSC::getCallData(runOnEndCallbacksFn);
if (callData.type == JSC::CallData::Type::None) [[unlikely]] {
return JSValue::encode(jsUndefined());
}

MarkedArgumentBuffer arguments;
arguments.append(JSValue::decode(encodedBuildPromise));
arguments.append(JSValue::decode(encodedBuildResult));
arguments.append(JSValue::decode(encodedRejection));

// TODO: use AsyncContextFrame?
auto result
= JSC::profiledCall(globalObject, ProfilingReason::API, runOnEndCallbacksFn, callData, plugin, arguments);
RETURN_IF_EXCEPTION(scope, {});

return JSValue::encode(result);
}

extern "C" int JSBundlerPlugin__callOnBeforeParsePlugins(
Bun::JSBundlerPlugin* plugin,
void* bunContextPtr,
Expand Down
3 changes: 3 additions & 0 deletions src/bundler/Graph.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ heap: ThreadLocalArena,

/// Mapping user-specified entry points to their Source Index
entry_points: std.ArrayListUnmanaged(Index) = .{},
/// Maps entry point source indices to their original specifiers (for virtual entries resolved by plugins)
entry_point_original_names: IndexStringMap = .{},
/// Every source index has an associated InputFile
input_files: MultiArrayList(InputFile) = .{},
/// Every source index has an associated Ast
Expand Down Expand Up @@ -101,6 +103,7 @@ pub const Index = bun.ast.Index;

const string = []const u8;

const IndexStringMap = @import("./IndexStringMap.zig");
const Logger = @import("../logger.zig");
const _resolver = @import("../resolver/resolver.zig");
const std = @import("std");
Expand Down
23 changes: 23 additions & 0 deletions src/bundler/IndexStringMap.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const IndexStringMap = @This();

pub const Index = bun.ast.Index;

map: std.AutoArrayHashMapUnmanaged(Index.Int, []const u8) = .{},

pub fn deinit(self: *IndexStringMap, allocator: std.mem.Allocator) void {
for (self.map.values()) |value| {
allocator.free(value);
}
self.map.deinit(allocator);
}

pub fn get(self: *const IndexStringMap, index: Index.Int) ?[]const u8 {
return self.map.get(index);
}

pub fn put(self: *IndexStringMap, allocator: std.mem.Allocator, index: Index.Int, value: []const u8) !void {
try self.map.put(allocator, index, value);
}

const bun = @import("bun");
const std = @import("std");
2 changes: 1 addition & 1 deletion src/bundler/LinkerContext.zig
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ pub const LinkerContext = struct {

const sources: []const Logger.Source = this.parse_graph.input_files.items(.source);

try this.graph.load(entry_points, sources, server_component_boundaries, bundle.dynamic_import_entry_points.keys());
try this.graph.load(entry_points, sources, server_component_boundaries, bundle.dynamic_import_entry_points.keys(), &this.parse_graph.entry_point_original_names);
bundle.dynamic_import_entry_points.deinit();

var runtime_named_exports = &this.graph.ast.items(.named_exports)[Index.runtime.get()];
Expand Down
11 changes: 10 additions & 1 deletion src/bundler/LinkerGraph.zig
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ pub fn load(
sources: []const Logger.Source,
server_component_boundaries: ServerComponentBoundary.List,
dynamic_import_entry_points: []const Index.Int,
entry_point_original_names: *const IndexStringMap,
) !void {
const scb = server_component_boundaries.slice();
try this.files.setCapacity(this.allocator, sources.len);
Expand Down Expand Up @@ -262,7 +263,14 @@ pub fn load(
bun.assert(source.index.get() == i.get());
}
entry_point_kinds[source.index.get()] = EntryPoint.Kind.user_specified;
path_string.* = bun.PathString.init(source.path.text);

// Check if this entry point has an original name (from virtual entry resolution)
if (entry_point_original_names.get(i.get())) |original_name| {
path_string.* = bun.PathString.init(original_name);
} else {
path_string.* = bun.PathString.init(source.path.text);
}

source_index.* = source.index.get();
}

Expand Down Expand Up @@ -462,6 +470,7 @@ const BitSet = bun.bit_set.DynamicBitSetUnmanaged;

const EntryPoint = bun.bundle_v2.EntryPoint;
const Index = bun.bundle_v2.Index;
const IndexStringMap = bun.bundle_v2.IndexStringMap;
const JSAst = bun.bundle_v2.JSAst;
const JSMeta = bun.bundle_v2.JSMeta;
const Logger = bun.bundle_v2.Logger;
Expand Down
Loading