Skip to content
Merged
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
2 changes: 1 addition & 1 deletion docs/runtime/plugins.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ await Bun.build({

### Namespaces

`onLoad` and `onResolve` accept an optional `namespace` string. Every module has a namespace, which prefixes the import in transpiled code. For instance, a loader with a `filter: /\.yaml$/` and `namespace: "yaml:"` transforms an import from `./myfile.yaml` into `yaml:./myfile.yaml`.
`onLoad` and `onResolve` accept an optional `namespace` string. Every module has a namespace, which prefixes its path. For instance, when `onResolve` returns `{ path: "./myfile.yaml", namespace: "yaml" }`, the module is `yaml:./myfile.yaml`.

The default namespace is `"file"` and you don't need to specify it: `import myModule from "./my-module.ts"` is the same as `import myModule from "file:./my-module.ts"`.

Expand Down
6 changes: 0 additions & 6 deletions src/ast/import_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,6 @@ bitflags::bitflags! {
/// If true, this import can be removed if it's unused
const IS_EXTERNAL_WITHOUT_SIDE_EFFECTS = 1 << 11;

/// Tell the printer to print the record as "foo:my-path" instead of "path"
/// where "foo" is the namespace
///
/// Used to prevent running resolve plugins multiple times for the same path
const PRINT_NAMESPACE_IN_PATH = 1 << 12;

const WRAP_WITH_TO_ESM = 1 << 13;
const WRAP_WITH_TO_COMMONJS = 1 << 14;

Expand Down
51 changes: 3 additions & 48 deletions src/bundler/linker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ use bun_url::URL;

use crate::options::{self, BundleOptions, ImportPathFormat};
use crate::options_impl::Target as BundleTarget;
use crate::transpiler::{
BunPluginTarget, ParseResult, PluginResolver, PluginRunner, ResolveQueue, ResolveResults,
};
use crate::transpiler::{ParseResult, ResolveQueue, ResolveResults};

pub struct Linker {
// arena field dropped — global mimalloc (callers pass `bun.default_allocator`)
Expand All @@ -35,8 +33,6 @@ pub struct Linker {
pub log: *mut Log,
pub(crate) resolve_queue: *mut ResolveQueue,
pub(crate) resolve_results: *mut ResolveResults,

pub plugin_runner: Option<*mut dyn PluginResolver>,
}

const RUNTIME_SOURCE_PATH: &[u8] = b"bun:wrap";
Expand Down Expand Up @@ -240,15 +236,12 @@ impl Linker {
log,
resolve_queue,
resolve_results,
plugin_runner: None,
}
}

/// Re-seat the self-referential back-pointers after the owning
/// `Transpiler` has been moved to its final address. Only re-assigns the
/// pointer fields; does NOT reset
/// `plugin_runner`. Use instead of `init` from
/// `Transpiler::wire_after_move`.
/// `Transpiler` has been moved to its final address. Use instead of `init`
/// from `Transpiler::wire_after_move`.
pub(crate) fn reseat_self_refs(
&mut self,
log: *mut Log,
Expand Down Expand Up @@ -436,44 +429,6 @@ impl Linker {
continue;
}
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
}
Comment thread
dylan-conway marked this conversation as resolved.
Resolved

if let Some(runner) = self.plugin_runner {
let import_record = &mut result.ast.import_records.as_mut_slice()[record_i];
if PluginRunner::could_be_plugin(import_record.path.text) {
// SAFETY: `plugin_runner` is `Some` only when set
// by the owning `Transpiler` to a live JSC-heap
// `PluginRunner`; the transpiler is single-threaded
// and holds no other borrow of it for the duration
// of `on_resolve`, so shared access is sound.
let runner = unsafe { &*runner };
if let Some(path) = runner.on_resolve(
import_record.path.text,
file_path.text,
self.log_mut(),
import_record.range.loc,
if IS_BUN {
BunPluginTarget::Bun
} else if target == options::Target::Browser {
BunPluginTarget::Browser
} else {
BunPluginTarget::Node
},
)? {
import_record.path = self.generate_import_path(
source_dir,
path.text,
false,
path.namespace,
origin,
import_path_format,
)?;
import_record
.flags
.insert(ImportRecordFlags::PRINT_NAMESPACE_IN_PATH);
continue;
}
}
}
}
}

Expand Down
25 changes: 1 addition & 24 deletions src/bundler/transpiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,8 @@ pub enum BunPluginTarget {
// is what matters at the ABI.
bun_core::assert_ffi_discr!(BunPluginTarget, u8; Bun = 0, Node = 1, Browser = 2);

/// The JSC-aware resolve hook.
///
/// The body calls `JSGlobalObject.runOnResolvePlugins`, so it cannot be
/// defined at this tier (`bun_jsc` depends on this crate). `bun_jsc` provides
/// the concrete `PluginRunner { global_object: *mut JSGlobalObject }` and
/// implements this trait; `Linker.plugin_runner` holds it as
/// `*mut dyn PluginResolver` so the linker stays JSC-free while the body lives
/// in exactly one place (no fn-ptr field, no `*mut c_void` erasure).
pub trait PluginResolver {
fn on_resolve(
&self,
specifier: &[u8],
importer: &[u8],
log: &mut bun_ast::Log,
loc: bun_ast::Loc,
target: BunPluginTarget,
) -> crate::Result<Option<bun_paths::fs::Path<'static>>>;
}

/// Namespace for the static byte-level helpers
/// (`extractNamespace` / `couldBePlugin`). The stateful struct (with
/// `global_object`) lives in `bun_jsc::PluginRunner` where `JSGlobalObject` is
/// nameable; only the JSC-free helpers stay at this tier.
/// (`extractNamespace` / `couldBePlugin`).
pub struct PluginRunner;

impl PluginRunner {
Expand Down Expand Up @@ -368,8 +347,6 @@ impl<'a> Transpiler<'a> {
self.options.log = log;
self.resolver.log = core::ptr::NonNull::new(log).expect("wire_after_move: log is non-null");
self.resolver.fs = self.fs;
// Only reseat the back-pointers — do NOT `Linker::init` here: that
// would clobber `plugin_runner`, which must be preserved across the move.
self.linker.reseat_self_refs(
log,
core::ptr::addr_of_mut!(self.resolve_queue),
Expand Down
29 changes: 3 additions & 26 deletions src/js_printer/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,6 @@ use renamer as rename;
// revisit if profiling shows allocation pressure during link.
pub type MangledProps = bun_collections::ArrayHashMap<Ref, Box<[u8]>>;

/// The namespace the printed specifier of `record` starts with (`namespace:path`), if any.
fn printed_namespace(record: &ImportRecord) -> Option<&'static [u8]> {
(record
.flags
.contains(ImportRecordFlags::PRINT_NAMESPACE_IN_PATH)
&& !record.path.is_file())
.then_some(record.path.namespace)
}

/// js_printer is the sole producer of ModuleInfo records; the bundler/runtime
/// only consume the serialized form.
pub mod analyze_transpiled_module {
Expand Down Expand Up @@ -709,16 +700,6 @@ pub mod analyze_transpiled_module {
StringID(idx)
}

/// Interns the specifier `print_import_record_path` prints for `record`, so the
/// module record requests the same module as the printed source.
pub(crate) fn str_for_import_record(&mut self, record: &super::ImportRecord) -> StringID {
let path = record.path.text;
match super::printed_namespace(record) {
Some(namespace) => self.str(&[namespace, b":".as_slice(), path].concat()),
None => self.str(path),
}
}

pub(crate) fn request_module(
&mut self,
import_record_path: StringID,
Expand Down Expand Up @@ -5621,7 +5602,7 @@ pub(crate) mod __gated_printer {

if Self::MAY_HAVE_MODULE_INFO {
if let Some(mi) = self.module_info() {
let irp_id = mi.str_for_import_record(import_record);
let irp_id = mi.str(import_record.path.text);
mi.request_module(
irp_id,
analyze_transpiled_module::FetchParameters::None,
Expand Down Expand Up @@ -5805,7 +5786,7 @@ pub(crate) mod __gated_printer {
// `name_for_symbol` (which needs `&mut self`) can run between uses.
let irp_id = {
let mi = self.module_info().expect("infallible: module_info enabled");
let id = mi.str_for_import_record(import_record);
let id = mi.str(import_record.path.text);
mi.request_module(id, analyze_transpiled_module::FetchParameters::None);
id
};
Expand Down Expand Up @@ -6332,7 +6313,7 @@ pub(crate) mod __gated_printer {
use analyze_transpiled_module::FetchParameters as FP;
let (irp_id, fetch_parameters) = {
let mi = self.module_info().expect("infallible: module_info enabled");
let irp_id = mi.str_for_import_record(record);
let irp_id = mi.str(record.path.text);
let fetch_parameters: FP = if IS_BUN_PLATFORM {
if let Some(loader) = record.loader {
use bun_ast::Loader;
Expand Down Expand Up @@ -6515,10 +6496,6 @@ pub(crate) mod __gated_printer {

let quote = best_quote_char_for_string(import_record.path.text, false);
self.print(quote);
if let Some(namespace) = printed_namespace(import_record) {
self.print_string_characters_utf8(namespace, quote);
self.print(b":");
}
self.print_string_characters_utf8(import_record.path.text, quote);
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
self.print(quote);
}
Expand Down
3 changes: 1 addition & 2 deletions src/jsc/JSGlobalObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1372,8 +1372,7 @@ impl JSGlobalObject {
// see one nominal type (the previous local duplicate diverged from lib.rs).
pub use crate::GregorianDateTime;

/// The enum is defined once in `bun_bundler::transpiler` (the lowest tier that names it,
/// for `Linker::link`'s call into `PluginResolver::on_resolve`) and re-exported
/// The enum is defined once in `bun_bundler::transpiler` and re-exported
/// here so the C++ FFI signature and all `bun_jsc` callers share one nominal
/// type — no mirror enum, no transmute.
pub use bun_bundler::transpiler::BunPluginTarget;
Expand Down
2 changes: 1 addition & 1 deletion src/jsc/ModuleLoader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ unsafe extern "C" fn Bun__runVirtualModule(
specifier_ptr: *const bun_core::String,
) -> JSValue {
jsc::mark_binding();
if global.bun_vm().plugin_runner.is_none() {
if !global.bun_vm().has_plugins {
return JSValue::ZERO;
}

Expand Down
Loading
Loading