diff --git a/docs/runtime/plugins.mdx b/docs/runtime/plugins.mdx index 24e13c182f88..b30a3817badf 100644 --- a/docs/runtime/plugins.mdx +++ b/docs/runtime/plugins.mdx @@ -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"`. diff --git a/src/ast/import_record.rs b/src/ast/import_record.rs index 6e582f84e53e..8255ccbe3760 100644 --- a/src/ast/import_record.rs +++ b/src/ast/import_record.rs @@ -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; diff --git a/src/bundler/linker.rs b/src/bundler/linker.rs index 4f8fcdeae52c..a6ae71a22bfb 100644 --- a/src/bundler/linker.rs +++ b/src/bundler/linker.rs @@ -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`) @@ -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"; @@ -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, @@ -426,52 +419,6 @@ impl Linker { import_record.path = PFs::Path::init(&import_record.path.text[b"bun:".len()..]); import_record.path.namespace = b"bun"; - - // don't link bun - continue; - } - - // Resolve dynamic imports lazily for perf - if import_record.kind == ImportKind::Dynamic { - continue; - } - } - - 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; - } } } } diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index 7387ca6e96d8..00a19a246bdf 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -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>>; -} - /// 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 { @@ -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), diff --git a/src/js_printer/lib.rs b/src/js_printer/lib.rs index ecddeae2c578..4040862321d0 100644 --- a/src/js_printer/lib.rs +++ b/src/js_printer/lib.rs @@ -67,15 +67,6 @@ use renamer as rename; // revisit if profiling shows allocation pressure during link. pub type MangledProps = bun_collections::ArrayHashMap>; -/// 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 { @@ -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, @@ -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, @@ -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 }; @@ -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; @@ -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); self.print(quote); } diff --git a/src/jsc/JSGlobalObject.rs b/src/jsc/JSGlobalObject.rs index 11115339f3f0..dd311859b914 100644 --- a/src/jsc/JSGlobalObject.rs +++ b/src/jsc/JSGlobalObject.rs @@ -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; diff --git a/src/jsc/ModuleLoader.rs b/src/jsc/ModuleLoader.rs index 29f0cf036c08..6191f8494ba0 100644 --- a/src/jsc/ModuleLoader.rs +++ b/src/jsc/ModuleLoader.rs @@ -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; } diff --git a/src/jsc/PluginRunner.rs b/src/jsc/PluginRunner.rs deleted file mode 100644 index ff4c34313489..000000000000 --- a/src/jsc/PluginRunner.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! The concrete JSC-aware plugin-resolve hook. -//! -//! LAYERING: the static byte helpers (`extract_namespace` / `could_be_plugin`) -//! live in `bun_bundler::transpiler::PluginRunner` (JSC-free, lowest tier). -//! The stateful struct lives here because its only field is a typed -//! `*mut JSGlobalObject`. `bun_bundler::Linker` references it through -//! `*mut dyn PluginResolver`, so the linker stays JSC-free without -//! type-erasing to `*mut c_void` or duplicating the body behind a fn-ptr. - -use std::io::Write as _; - -use bun_bundler::transpiler::{BunPluginTarget, PluginResolver}; -use bun_core::String as BunString; -use bun_paths::fs::Path as FsPath; - -use crate::JSGlobalObject; -use bun_ptr::BackRef; - -pub struct PluginRunner { - pub(crate) global_object: BackRef, -} - -// Re-export the JSC-free static helpers so callers in this crate can keep -// writing `PluginRunner::could_be_plugin(...)` without naming `bun_bundler`. -impl PluginRunner { - /// Borrow the JS global stored by `Bun__onDidAppendPlugin`. - /// - /// SAFETY (invariant): `global_object` is the live `*mut JSGlobalObject` - /// installed by `Bun__onDidAppendPlugin`; the VM (and its global) outlives - /// every `Linker::link` call that reaches plugin hooks. Never null. - #[inline] - fn global(&self) -> &JSGlobalObject { - self.global_object.get() - } - - #[inline] - pub fn extract_namespace(specifier: &[u8]) -> &[u8] { - bun_bundler::transpiler::PluginRunner::extract_namespace(specifier) - } -} - -impl PluginResolver for PluginRunner { - fn on_resolve( - &self, - specifier: &[u8], - importer: &[u8], - log: &mut bun_ast::Log, - loc: bun_ast::Loc, - target: BunPluginTarget, - ) -> bun_bundler::Result>> { - let global = self.global(); - let js_err = bun_bundler::Error::Js; - - let namespace_slice = Self::extract_namespace(specifier); - let namespace = if !namespace_slice.is_empty() && namespace_slice != b"file" { - BunString::from_bytes(namespace_slice) - } else { - BunString::EMPTY - }; - let Some(on_resolve_plugin) = global - .run_on_resolve_plugins( - &namespace, - &BunString::from_bytes(specifier).substring(if namespace.length() > 0 { - namespace.length() + 1 - } else { - 0 - }), - &BunString::from_bytes(importer), - target, - ) - .map_err(js_err)? - else { - return Ok(None); - }; - let Some(path_value) = on_resolve_plugin.get(global, "path").map_err(js_err)? else { - return Ok(None); - }; - if path_value.is_empty_or_undefined_or_null() { - return Ok(None); - } - if !path_value.is_string() { - log.add_error(None, loc, b"Expected \"path\" to be a string"); - return Ok(None); - } - - let file_path = path_value.to_bun_string(global).map_err(js_err)?; - - if file_path.length() == 0 { - log.add_error( - None, - loc, - b"Expected \"path\" to be a non-empty string in onResolve plugin", - ); - return Ok(None); - } else if - // TODO: validate this better - file_path.eq_ascii(b".") - || file_path.eq_ascii(b"..") - || file_path.eq_ascii(b"...") - || file_path.eq_ascii(b" ") - { - log.add_error(None, loc, b"Invalid file path from onResolve plugin"); - return Ok(None); - } - let mut static_namespace = true; - let user_namespace: BunString = 'brk: { - if let Some(namespace_value) = - on_resolve_plugin.get(global, "namespace").map_err(js_err)? - { - if !namespace_value.is_string() { - log.add_error(None, loc, b"Expected \"namespace\" to be a string"); - return Ok(None); - } - - let namespace_str = namespace_value.to_bun_string(global).map_err(js_err)?; - if namespace_str.length() == 0 { - break 'brk BunString::static_("file"); - } - - if namespace_str.eq_ascii(b"file") { - break 'brk BunString::static_("file"); - } - - if namespace_str.eq_ascii(b"bun") { - break 'brk BunString::static_("bun"); - } - - if namespace_str.eq_ascii(b"node") { - break 'brk BunString::static_("node"); - } - - static_namespace = false; - - break 'brk namespace_str; - } - - break 'brk BunString::static_("file"); - }; - - // `FsPath<'static>` borrows, so the formatted buffer is leaked to - // model the caller-owns-forever contract (these are - // never freed — the linker arena owns them for the build). - // PERF: profile if hot. - let mut path_buf: Vec = Vec::new(); - write!(&mut path_buf, "{}", file_path).expect("unreachable"); - let path_static: &'static [u8] = path_buf.leak(); - - if static_namespace { - // `byte_slice()` borrows `&self`; re-match to recover the - // `'static` literal so the result typechecks as `FsPath<'static>` - // without an extra alloc. - let ns: &'static [u8] = if user_namespace.eq_ascii(b"bun") { - b"bun" - } else if user_namespace.eq_ascii(b"node") { - b"node" - } else { - b"file" - }; - Ok(Some(FsPath::init_with_namespace(path_static, ns))) - } else { - let mut ns_buf: Vec = Vec::new(); - write!(&mut ns_buf, "{}", user_namespace).expect("unreachable"); - let ns_static: &'static [u8] = ns_buf.leak(); - Ok(Some(FsPath::init_with_namespace(path_static, ns_static))) - } - } -} diff --git a/src/jsc/RuntimeTranspilerCache.rs b/src/jsc/RuntimeTranspilerCache.rs index 1ba5bf2d76bb..ff170d4c8c38 100644 --- a/src/jsc/RuntimeTranspilerCache.rs +++ b/src/jsc/RuntimeTranspilerCache.rs @@ -63,7 +63,8 @@ bun_core::declare_scope!(cache, visible); /// Version 33: The cached ESM record keeps the namespace of an import that a plugin /// `onResolve` rewrote (`namespace:path`). Older entries request the bare path, and /// the cache-HIT path reinstates #33904 for them. -const EXPECTED_VERSION: u32 = 33; +/// Version 34: An import that a plugin `onResolve` answers is printed as it is written. +const EXPECTED_VERSION: u32 = 34; /// Source files smaller than this are not written to / read from the on-disk /// transpiler cache. Originally 50 KiB, which excluded almost every file in a diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index 6d3903fb4654..883487998df5 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -216,7 +216,8 @@ pub struct VirtualMachine { /// (`exit_tears_down_napi_envs`). The list is never walked again, so a hook /// pushed after this (a finalizer deferred from the final collection) would only leak. pub(crate) has_run_cleanup_hooks: bool, - pub plugin_runner: Option, + /// `Bun.plugin()` was called in the current global. + pub has_plugins: bool, pub is_main_thread: bool, pub exit_handler: ExitHandler, @@ -509,7 +510,7 @@ pub unsafe extern "C" fn Bun__standaloneInternalModuleBytecode( #[unsafe(no_mangle)] pub unsafe extern "C" fn Bun__hasPluginRunner(vm: *mut VirtualMachine) -> bool { // SAFETY: `vm` is the live per-thread VM the C++ global object holds. - unsafe { (*vm).plugin_runner.is_some() } + unsafe { (*vm).has_plugins } } #[unsafe(no_mangle)] @@ -5258,7 +5259,7 @@ impl VirtualMachine { // Bare/`node:` builtins: answer from the alias table before paying for UTF-8 copies and the resolver. // (Alias names are ASCII, so the Latin-1 bytes are the UTF-8 bytes whenever they can match.) - if jsc_vm.plugin_runner.is_none() && specifier.is_8bit() { + if !jsc_vm.has_plugins && specifier.is_8bit() { if let Some(hardcoded) = ModuleLoader::HardcodedModule::Alias::get( specifier.latin1(), bun_ast::Target::Bun, @@ -5279,7 +5280,7 @@ impl VirtualMachine { let source_utf8 = source.to_utf8(); let answer: bun_core::String; - if jsc_vm.plugin_runner.is_some() { + if jsc_vm.has_plugins { use bun_bundler::transpiler::PluginRunner; let spec = specifier_utf8.slice(); if PluginRunner::could_be_plugin(spec) { @@ -5827,10 +5828,8 @@ impl VirtualMachine { self.main_hash = 0; self.main_resolved_path = bun_core::String::EMPTY; self.unhandled_error_counter = 0; - // The finished file's plugins are dropped with its global; the next - // `Bun.plugin()` call reinstalls the runner against the new global. - self.transpiler.linker.plugin_runner = None; - self.plugin_runner = None; + // The finished file's plugins are dropped with its global. + self.has_plugins = false; let old_global = self.global; // `old_global` valid for VM lifetime (safe ZST-handle deref); diff --git a/src/jsc/bindings/BunPlugin.cpp b/src/jsc/bindings/BunPlugin.cpp index 22073305f513..95902eb608ce 100644 --- a/src/jsc/bindings/BunPlugin.cpp +++ b/src/jsc/bindings/BunPlugin.cpp @@ -36,8 +36,8 @@ namespace Zig { -extern "C" void Bun__onDidAppendPlugin(void* bunVM, JSGlobalObject* globalObject); -using OnAppendPluginCallback = void (*)(void*, JSGlobalObject* globalObject); +extern "C" void Bun__onDidAppendPlugin(void* bunVM); +using OnAppendPluginCallback = void (*)(void*); static bool isValidNamespaceString(String& namespaceString) { @@ -95,7 +95,7 @@ static JSC::EncodedJSValue jsFunctionAppendOnLoadPluginBody(JSC::JSGlobalObject* } plugin.append(vm, filter->regExp(), func.getObject(), namespaceString); - callback(ctx, globalObject); + callback(ctx); RETURN_IF_EXCEPTION(scope, {}); return JSValue::encode(callframe->thisValue()); @@ -212,7 +212,7 @@ static JSC::EncodedJSValue jsFunctionAppendOnResolvePluginBody(JSC::JSGlobalObje } plugin.append(vm, filter->regExp(), uncheckedDowncast(func), namespaceString); - callback(ctx, globalObject); + callback(ctx); RETURN_IF_EXCEPTION(scope, {}); return JSValue::encode(callframe->thisValue()); diff --git a/src/jsc/bindings/ZigGlobalObject.cpp b/src/jsc/bindings/ZigGlobalObject.cpp index a9b5b9f50cca..ef7ae978c681 100644 --- a/src/jsc/bindings/ZigGlobalObject.cpp +++ b/src/jsc/bindings/ZigGlobalObject.cpp @@ -3561,24 +3561,6 @@ JSC::Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject* jsGlobalObject ASSERT(!globalObject->onLoadPlugins.mustDoExpensiveRelativeLookup); } - // The transpiler has put a static import through onResolve already (Linker::link) and printed what that gave, so - // a key in a namespace that has an onLoad handler is final. The filesystem resolver would not find it. - // - // FIXME(module-loader): this ignores the plugin's filter, and bypasses any onResolve handler for an import that - // is written as "ns:..." in the source. - if (!globalObject->onLoadPlugins.namespaces.isEmpty()) { - if (auto colon = keyString.find(':'); colon != WTF::notFound && !(colon == 1 && isASCIIAlpha(keyString[0]))) { - // colon == 1 with a leading ASCII letter is a Windows drive - // ("C:\\..."), never a plugin namespace. - auto ns = keyString.left(colon); - for (const auto& registered : globalObject->onLoadPlugins.namespaces) { - if (registered == ns) { - return Identifier::fromString(vm, keyString); - } - } - } - } - ErrorableString res; BunString keyZ = Bun::toString(keyString); BunString referrerZ = Bun::toString(referrerString); @@ -3691,39 +3673,11 @@ JSC::JSPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* jsGlobalO } } - { - if (moduleName.startsWith("file://"_s)) { - auto url = WTF::URL(moduleName); - if (url.isValid() && !url.isEmpty()) { - moduleName = url.fileSystemPath(); - } - } - - ErrorableString res; - BunString moduleNameZ = Bun::toString(moduleName); - BunString sourceOriginZ = Bun::toString(sourceOriginStringHolder); - BunString queryZ = BunStringEmpty; - Zig__GlobalObject__resolve(&res, globalObject, &moduleNameZ, &sourceOriginZ, &queryZ); - RETURN_IF_EXCEPTION(scope, JSC::JSPromise::rejectedPromiseWithCaughtException(globalObject, scope)); - if (!res.success) [[unlikely]] { - throwException(scope, res.result.err, globalObject); - return JSC::JSPromise::rejectedPromiseWithCaughtException(globalObject, scope); - } - auto resolved = res.result.value.transferToWTFString(); - auto query = queryZ.transferToWTFString(); - - if (query.isEmpty()) { - resolvedIdentifier = JSC::Identifier::fromString(vm, resolved); - } else { - resolvedIdentifier = JSC::Identifier::fromString(vm, makeString(resolved, query)); - } - } - // The C++ module loader now extracts `with.type` into a // ScriptFetchParameters before calling this hook, so `parameters` is // already the parsed RefPtr (or null). Just forward it. - auto result = loader->requestImportModule(globalObject, resolvedIdentifier, - JSC::Identifier(), WTF::move(parameters), nullptr, /* deferred */ false, referrerAsyncOrder); + auto result = loader->requestImportModule(globalObject, JSC::Identifier::fromString(vm, moduleName), + JSC::Identifier::fromString(vm, sourceOriginStringHolder), WTF::move(parameters), nullptr, /* deferred */ false, referrerAsyncOrder); if (scope.exception()) [[unlikely]] { return JSC::JSPromise::rejectedPromiseWithCaughtException(globalObject, scope); } diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 7c9a1c4dd872..7bfe9b5d2aed 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -412,8 +412,6 @@ pub mod http_server_agent; pub mod js_secrets; #[path = "NodeModuleModule.rs"] pub mod node_module_module; -#[path = "PluginRunner.rs"] -pub mod plugin_runner; #[path = "PosixSignalHandle.rs"] pub mod posix_signal_handle; #[path = "resolve_path_jsc.rs"] diff --git a/src/jsc/virtual_machine_exports.rs b/src/jsc/virtual_machine_exports.rs index 15e371b99ce9..340f40054658 100644 --- a/src/jsc/virtual_machine_exports.rs +++ b/src/jsc/virtual_machine_exports.rs @@ -1,11 +1,9 @@ use core::ffi::c_void; -use crate::plugin_runner::PluginRunner; use crate::{ CallFrame, JSGlobalObject, JSPromise, JSValue, JsResult, Strong, Task, VirtualMachineRef as VirtualMachine, }; -use bun_bundler::transpiler::PluginResolver; use bun_core::String as BunString; use bun_sourcemap::SourceProviderMap; use bun_sourcemap::parsed_source_map::AnySourceProvider; @@ -180,19 +178,8 @@ pub fn handle_handled_promise(global: &JSGlobalObject, promise: &JSPromise) { } // HOST_EXPORT(Bun__onDidAppendPlugin, c) -pub fn on_did_append_plugin(jsc_vm: &mut VirtualMachine, global: &JSGlobalObject) { - if jsc_vm.plugin_runner.is_some() { - return; - } - - // `Option::insert` returns `&mut PluginRunner` into the VM-owned slot; - // `plugin_runner` and `transpiler` are disjoint fields so the split borrow - // is fine. The slot is embedded in `*jsc_vm` and stable for the VM's - // lifetime, so taking a raw pointer into it for the linker BACKREF is sound. - let runner = jsc_vm.plugin_runner.insert(PluginRunner { - global_object: bun_ptr::BackRef::new(global), - }); - jsc_vm.transpiler.linker.plugin_runner = Some(std::ptr::from_mut::(runner)); +pub fn on_did_append_plugin(jsc_vm: &mut VirtualMachine) { + jsc_vm.has_plugins = true; } #[cfg(windows)] diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 9f565cf3f15b..5fb4c09a5ec6 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -4215,11 +4215,11 @@ pub(crate) unsafe extern "C" fn Bun__transpileFile( 'transpile_async: { let concurrent_loader = lr.loader.unwrap_or(Loader::File); // SAFETY: per fn contract — `jsc_vm` is the live per-thread VM. - let (has_loaded, is_in_preload, plugin_runner_is_none, store_enabled) = unsafe { + let (has_loaded, is_in_preload, has_plugins, store_enabled) = unsafe { ( (*jsc_vm).has_loaded, (*jsc_vm).is_in_preload, - (*jsc_vm).plugin_runner.is_none(), + (*jsc_vm).has_plugins, (*jsc_vm).transpiler_store.enabled, ) }; @@ -4230,7 +4230,7 @@ pub(crate) unsafe extern "C" fn Bun__transpileFile( && !lr.is_main // Plugins make this complicated. // TODO: allow running concurrently when no onLoad handlers match a plugin. - && plugin_runner_is_none + && !has_plugins && store_enabled // With the Node compile cache enabled, transpile on-thread so the // fetch hook sees every module. @@ -4437,8 +4437,6 @@ pub(crate) extern "C" fn Bun__transpileVirtualModule( // launder provenance through a shared ref and the `&mut *jsc_vm` / // transpiler writes below would be UB under Stacked Borrows. let jsc_vm: *mut VirtualMachine = global.bun_vm_ptr(); - // Note: spec asserted `jsc_vm.plugin_runner != null` then dropped the - // assert ("not required for build.module()") — keep parity (no assert). let specifier_slice = specifier_str.to_utf8(); let specifier = specifier_slice.slice(); diff --git a/test/js/bun/plugin/plugins.test.ts b/test/js/bun/plugin/plugins.test.ts index 07708673a211..c4ca731687c7 100644 --- a/test/js/bun/plugin/plugins.test.ts +++ b/test/js/bun/plugin/plugins.test.ts @@ -1164,45 +1164,51 @@ describe.concurrent("what onResolve answers without a namespace is resolved from }); }); -// The loader asked for a path that these had resolved to be resolved again, so onResolve was fed its own results. -describe.concurrent("onResolve is asked once about", () => { - it.each([ - [ - "import.meta.require()", - ["--preload", "./plugin.ts", "entry.ts"], - `console.log(import.meta.require("./a.mjs").from);`, - ], - // What Bun loads itself has no importer. - ["a later preload", ["--preload", "./plugin.ts", "--preload", "./a.mjs", "entry.ts"], ""], - ["Module.runMain()", ["--preload", "./plugin.ts", "entry.ts"], `require("node:module").runMain("./a.mjs");`], - ["a test file", ["test", "--preload", "./plugin.ts", "./a.test.mjs"], ""], - ])("%s", async (_, args, source) => { - const file = (name: string) => `export const from = "${name}"; console.log("loaded", from);`; - const aTest = `import { test } from "bun:test"; test("passes", () => {});`; - using dir = tempDir("plugin-onresolve-once", { - "a.mjs": file("a.mjs"), - "b.mjs": file("b.mjs"), - "c.mjs": file("c.mjs"), - "d.mjs": file("d.mjs"), - "a.test.mjs": file("a.test.mjs") + aTest, - "b.test.mjs": file("b.test.mjs") + aTest, - "c.test.mjs": file("c.test.mjs") + aTest, - "plugin.ts": ` - import { basename, join } from "node:path"; - const next = { a: "b", b: "c", c: "d" }; - Bun.plugin({ - name: "redirect", - setup(build) { - build.onResolve({ filter: /[\\\\/][abc](\\.test)?\\.mjs$/ }, ({ path }) => { - const name = basename(path); - console.log("onResolve", name); - return { path: join(import.meta.dir, next[name[0]] + name.slice(1)) }; - }); - }, - }); - `, - "entry.ts": source, - }); +// The loader asked for a path that import() or require() had resolved to be resolved again, and the transpiler put every +// specifier it could read through onResolve before the code ran. Either way onResolve was fed its own results. +describe.concurrent("onResolve", () => { + const files = { + "a.mjs": `export const from = "a.mjs";`, + "b.mjs": `export const from = "b.mjs";`, + "c.mjs": `export const from = "c.mjs";`, + "d.mjs": `export const from = "d.mjs";`, + "a.cjs": `exports.from = "a.cjs";`, + "b.cjs": `exports.from = "b.cjs";`, + "c.cjs": `exports.from = "c.cjs";`, + "a.js": `console.log("a.js");`, + "b.js": `console.log("b.js");`, + "c.js": `console.log("c.js");`, + "a.test.js": `console.log("a.test.js"); require("bun:test").test("passes", () => {});`, + "b.test.js": `console.log("b.test.js"); require("bun:test").test("passes", () => {});`, + "c.test.js": `console.log("c.test.js"); require("bun:test").test("passes", () => {});`, + "plugin.ts": ` + import { basename, join } from "node:path"; + const next = { a: "b", b: "c", c: "d" }; + Bun.plugin({ + name: "redirect", + setup(build) { + build.onResolve({ filter: /[\\\\/][abc](\\.test)?\\.[cm]?js$/ }, ({ path }) => { + const name = basename(path); + console.log("onResolve", name); + return { path: join(import.meta.dir, next[name[0]] + name.slice(1)) }; + }); + build.onResolve({ filter: /\\.virtual$/ }, ({ path }) => { + console.log("onResolve", basename(path)); + return { path: "from " + basename(path), namespace: "virtual" }; + }); + build.onResolve({ filter: /\\.throws$/ }, () => { + throw new Error("from onResolve"); + }); + build.onLoad({ filter: /.*/, namespace: "virtual" }, ({ path }) => ({ + contents: "export const from = " + JSON.stringify(path) + ";", + loader: "js", + })); + }, + }); + `, + }; + async function run(name: string, source: string, args = ["--preload", "./plugin.ts", name]) { + using dir = tempDir("plugin-onresolve-once", { ...files, [name]: source }); await using proc = Bun.spawn({ cmd: [bunExe(), ...args], cwd: String(dir), @@ -1210,10 +1216,74 @@ describe.concurrent("onResolve is asked once about", () => { stdout: "pipe", stderr: "pipe", }); - const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); - const asked = args[0] === "test" ? "a.test.mjs" : "a.mjs"; - const lines = stdout.split("\n").filter(line => line.startsWith("onResolve") || line.startsWith("loaded")); - expect(lines).toEqual(["onResolve " + asked, "loaded b" + asked.slice(1)]); - expect(exitCode).toBe(0); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout: stdout.trim().split("\n"), stderr, exitCode }; + } + + it.each([ + ["import()", "entry.mjs", `console.log((await import("./a.mjs")).from);`, "a.mjs", "b.mjs"], + ["an import statement", "entry.mjs", `import { from } from "./a.mjs"; console.log(from);`, "a.mjs", "b.mjs"], + [ + "export from", + "entry.mjs", + `export { from } from "./a.mjs"; import * as self from "./entry.mjs"; console.log(self.from);`, + "a.mjs", + "b.mjs", + ], + ["import.meta.require()", "entry.mjs", `console.log(import.meta.require("./a.mjs").from);`, "a.mjs", "b.mjs"], + ["require() of an ES module", "entry.cjs", `console.log(require("./a.mjs").from);`, "a.mjs", "b.mjs"], + ["require() of a CommonJS module", "entry.cjs", `console.log(require("./a.cjs").from);`, "a.cjs", "b.cjs"], + ["module.require()", "entry.cjs", `console.log(module.require("./a.cjs").from);`, "a.cjs", "b.cjs"], + [ + "require.resolve()", + "entry.cjs", + `console.log(require("node:path").basename(require.resolve("./a.cjs")));`, + "a.cjs", + "b.cjs", + ], + ])("is asked once by %s", async (_, name, source, asked, loaded) => { + expect(await run(name, source)).toEqual({ stdout: ["onResolve " + asked, loaded], stderr: "", exitCode: 0 }); + }); + + // What Bun loads itself has no importer. + it.each([ + ["a later preload", "", ["--preload", "./plugin.ts", "--preload", "./a.js", "entry.cjs"], "a.js", "b.js"], + ["Module.runMain()", `require("node:module").runMain("./a.js");`, undefined, "a.js", "b.js"], + ["a test file", "", ["test", "--preload", "./plugin.ts", "./a.test.js"], "a.test.js", "b.test.js"], + ])("is asked once about %s", async (_, source, args, asked, loaded) => { + const { stdout, exitCode } = await run("entry.cjs", source, args); + // (bun test prints its version first.) + expect({ stdout: stdout.slice(-2), exitCode }).toEqual({ stdout: ["onResolve " + asked, loaded], exitCode: 0 }); + }); + + it.each([ + ["an import statement", "entry.mjs", `import { from } from "./x.virtual"; console.log(from);`, "from x.virtual"], + ["import()", "entry.mjs", `console.log((await import("./x.virtual")).from);`, "from x.virtual"], + ["require()", "entry.cjs", `console.log(require("./x.virtual").from);`, "from x.virtual"], + ["module.require()", "entry.cjs", `console.log(module.require("./x.virtual").from);`, "from x.virtual"], + ["require.resolve()", "entry.cjs", `console.log(require.resolve("./x.virtual"));`, "virtual:from x.virtual"], + ])("can move what %s asks for into a namespace", async (_, name, source, expected) => { + expect(await run(name, source)).toEqual({ stdout: ["onResolve x.virtual", expected], stderr: "", exitCode: 0 }); + }); + + it("is not asked about a require() that does not run", async () => { + const source = ` + if (process.env.NOT_SET) require("./a.cjs"); + function notCalled() { return require.resolve("./b.cjs"); } + console.log("done"); + `; + expect(await run("entry.cjs", source)).toEqual({ stdout: ["done"], stderr: "", exitCode: 0 }); + }); + + it("throws where the require() is", async () => { + const source = ` + console.log("before"); + try { require("./x.throws"); } catch (error) { console.log("caught", error.message); } + `; + expect(await run("entry.cjs", source)).toEqual({ + stdout: ["before", "caught from onResolve"], + stderr: "", + exitCode: 0, + }); }); });