diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 86fc7ff7c7e4..06278a75a9e4 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -2557,6 +2557,8 @@ pub mod parse_worker { opts.ignore_dce_annotations = topts.ignore_dce_annotations && !task.source_index.is_runtime(); + opts.target = target; + // For files that are not user-specified entrypoints, set `import.meta.main` to `false`. // Entrypoints will have `import.meta.main` set as "unknown", unless we use `--compile`, // in which we inline `true`. diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index 8fb72a09715a..edafdf48cd6b 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -1555,6 +1555,7 @@ impl<'a> Transpiler<'a> { transform_only: self.options.transform_only, import_meta_main_value: None, lower_import_meta_main_for_node_js: false, + target, framework: None, repl_mode: self.options.repl_mode, }; diff --git a/src/js_parser/fold.rs b/src/js_parser/fold.rs index 08e2f4378ae0..f4df381d3253 100644 --- a/src/js_parser/fold.rs +++ b/src/js_parser/fold.rs @@ -514,6 +514,30 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O || (p.options.bundle && p.options.output_format == js_parser::options::Format::Cjs) { + if p.options.framework.is_none() + && (p.options.target.is_bun() || p.options.target.is_node()) + { + if name == b"dir" || name == b"dirname" { + p.record_usage(p.dirname_ref); + return Some(p.new_expr( + E::Identifier { + ref_: p.dirname_ref, + ..Default::default() + }, + name_loc, + )); + } else if name == b"path" || name == b"filename" { + p.record_usage(p.filename_ref); + return Some(p.new_expr( + E::Identifier { + ref_: p.filename_ref, + ..Default::default() + }, + name_loc, + )); + } + } + if name == b"dir" || name == b"dirname" { // Inline import.meta.dir return Some( diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index 9227cd63a118..a276cab544ef 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -93,6 +93,8 @@ pub struct Options<'a> { pub import_meta_main_value: Option, pub lower_import_meta_main_for_node_js: bool, + pub target: js_ast::Target, + /// When using react fast refresh or server components, the framework is /// able to customize what import sources are used. pub framework: Option<&'a options::Framework>, // TYPE_ONLY: was bun_runtime::bake::Framework @@ -132,6 +134,7 @@ impl<'a> Default for Options<'a> { transform_only: false, import_meta_main_value: None, lower_import_meta_main_for_node_js: false, + target: js_ast::Target::Browser, framework: None, repl_mode: false, } @@ -215,6 +218,7 @@ impl<'a> Options<'a> { transform_only: self.transform_only, import_meta_main_value: self.import_meta_main_value, lower_import_meta_main_for_node_js: self.lower_import_meta_main_for_node_js, + target: self.target, framework: self.framework, repl_mode: self.repl_mode, } @@ -282,6 +286,7 @@ impl<'a> Options<'a> { transform_only: false, import_meta_main_value: None, lower_import_meta_main_for_node_js: false, + target: js_ast::Target::Browser, framework: None, repl_mode: false, }; @@ -1015,77 +1020,59 @@ impl<'a> Parser<'a> { // if p.options.bundle || !p.options.features.commonjs_at_runtime { if uses_dirname || uses_filename { - let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); - let decls = p - .arena - .alloc_slice_fill_with::(count, |_| G::Decl::default()); - if uses_dirname { - decls[0] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.dirname_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( + let import_meta_names: Option<(&'static [u8], &'static [u8])> = if p.options.bundle + && p.options.output_format == options::Format::Esm + && p.options.framework.is_none() + { + if p.options.target.is_bun() { + Some((b"dir", b"path")) + } else if p.options.target.is_node() { + Some((b"dirname", b"filename")) + } else { + None + } + } else { + None + }; + + let defer_to_cjs_wrapper = p.options.bundle + && p.options.output_format == options::Format::Cjs + && p.options.framework.is_none() + && (p.options.target.is_bun() || p.options.target.is_node()); + + if import_meta_names.is_some() { + p.has_import_meta = true; + } + + if !defer_to_cjs_wrapper { + let dirname_value = if !uses_dirname { + None + } else if let Some((dir_name, _)) = import_meta_names { + Some(import_meta_dot(p, dir_name)) + } else { + Some(p.new_expr( E::String { data: p.source.path.name().dir.into(), ..Default::default() }, bun_ast::Loc::EMPTY, - )), + )) }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.dirname_ref, - is_top_level: true, - }); - } - if uses_filename { - decls[uses_dirname as usize] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.filename_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( + let filename_value = if !uses_filename { + None + } else if let Some((_, path_name)) = import_meta_names { + Some(import_meta_dot(p, path_name)) + } else { + Some(p.new_expr( E::String { data: p.source.path.text.into(), ..Default::default() }, bun_ast::Loc::EMPTY, - )), + )) }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.filename_ref, - is_top_level: true, - }); + inject_dirname_filename_part(p, &mut before, dirname_value, filename_value); } - - let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { - p.s( - S::Local { - kind: js_ast::LocalKind::KVar, - decls: { - let mut dl = G::DeclList::init_capacity(decls.len()); - for d in decls.iter_mut() { - dl.append_assume_capacity(core::mem::take(d)); - } - dl - }, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - }); - before.push(js_ast::Part { - stmts: part_stmts.into(), - declared_symbols, - tag: bun_ast::PartTag::DirnameFilename, - ..Default::default() - }); uses_dirname = false; uses_filename = false; } @@ -1680,85 +1667,10 @@ impl<'a> Parser<'a> { // if exports_kind == js_ast::ExportsKind::Esm && (uses_dirname || uses_filename) { debug_assert!(!p.options.bundle); - let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); - let decls = p - .arena - .alloc_slice_fill_with::(count, |_| G::Decl::default()); - if uses_dirname { - // var __dirname = import.meta - let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); - decls[0] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.dirname_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( - E::Dot { - name: b"dir".into(), - name_loc: bun_ast::Loc::EMPTY, - target: import_meta, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - )), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.dirname_ref, - is_top_level: true, - }); - } - if uses_filename { - // var __filename = import.meta.path - let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); - decls[uses_dirname as usize] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.filename_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( - E::Dot { - name: b"path".into(), - name_loc: bun_ast::Loc::EMPTY, - target: import_meta, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - )), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.filename_ref, - is_top_level: true, - }); - } - - let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { - p.s( - S::Local { - kind: js_ast::LocalKind::KVar, - decls: { - let mut dl = G::DeclList::init_capacity(decls.len()); - for d in decls.iter_mut() { - dl.append_assume_capacity(core::mem::take(d)); - } - dl - }, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - }); - before.push(js_ast::Part { - stmts: part_stmts.into(), - declared_symbols, - tag: bun_ast::PartTag::DirnameFilename, - ..Default::default() - }); + // var __dirname = import.meta.dir, __filename = import.meta.path + let dirname_value = uses_dirname.then(|| import_meta_dot(p, b"dir")); + let filename_value = uses_filename.then(|| import_meta_dot(p, b"path")); + inject_dirname_filename_part(p, &mut before, dirname_value, filename_value); } if exports_kind == js_ast::ExportsKind::Esm @@ -2267,6 +2179,92 @@ struct PragmaState { seen_bytecode: bool, } +fn import_meta_dot( + p: &mut P<'_, TS, SCAN_ONLY>, + name: &'static [u8], +) -> Expr { + let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); + p.new_expr( + E::Dot { + name: name.into(), + name_loc: bun_ast::Loc::EMPTY, + target: import_meta, + can_be_removed_if_unused: true, + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) +} + +fn inject_dirname_filename_part<'a, const TS: bool, const SCAN_ONLY: bool>( + p: &mut P<'a, TS, SCAN_ONLY>, + before: &mut BumpVec<'a, js_ast::Part>, + dirname_value: Option, + filename_value: Option, +) { + let count = (dirname_value.is_some() as usize) + (filename_value.is_some() as usize); + let mut declared_symbols = + bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); + let decls = p + .arena + .alloc_slice_fill_with::(count, |_| G::Decl::default()); + let mut decl_i = 0; + if let Some(value) = dirname_value { + decls[decl_i] = G::Decl { + binding: p.b( + B::Identifier { + r#ref: p.dirname_ref, + }, + bun_ast::Loc::EMPTY, + ), + value: Some(value), + }; + declared_symbols.append_assume_capacity(DeclaredSymbol { + ref_: p.dirname_ref, + is_top_level: true, + }); + decl_i += 1; + } + if let Some(value) = filename_value { + decls[decl_i] = G::Decl { + binding: p.b( + B::Identifier { + r#ref: p.filename_ref, + }, + bun_ast::Loc::EMPTY, + ), + value: Some(value), + }; + declared_symbols.append_assume_capacity(DeclaredSymbol { + ref_: p.filename_ref, + is_top_level: true, + }); + } + + let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { + p.s( + S::Local { + kind: js_ast::LocalKind::KVar, + decls: { + let mut dl = G::DeclList::init_capacity(decls.len()); + for d in decls.iter_mut() { + dl.append_assume_capacity(core::mem::take(d)); + } + dl + }, + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) + }); + before.push(js_ast::Part { + stmts: part_stmts.into(), + declared_symbols, + tag: bun_ast::PartTag::DirnameFilename, + ..Default::default() + }); +} + #[cfg(target_arch = "wasm32")] pub type MacroContext = Option<*mut c_void>; #[cfg(not(target_arch = "wasm32"))] diff --git a/src/jsc/bindings/JSCommonJSModule.cpp b/src/jsc/bindings/JSCommonJSModule.cpp index e18cc0c15b55..79ba7f308dc6 100644 --- a/src/jsc/bindings/JSCommonJSModule.cpp +++ b/src/jsc/bindings/JSCommonJSModule.cpp @@ -895,7 +895,7 @@ JSCommonJSModule* JSCommonJSModule::create( { auto& vm = JSC::getVM(globalObject); auto key = requireMapKey->value(globalObject); - auto index = key->reverseFind(PLATFORM_SEP, key->length()); + auto index = lastPathSeparatorIndex(key.data); JSString* dirname; if (index != WTF::notFound) { @@ -1484,7 +1484,7 @@ std::optional createCommonJSModule( } if (!moduleObject) { - size_t index = sourceURL.reverseFind(PLATFORM_SEP, sourceURL.length()); + size_t index = lastPathSeparatorIndex(sourceURL); JSString* dirname; JSString* filename = requireMapKey; if (index != WTF::notFound) { @@ -1601,7 +1601,7 @@ std::optional createCommonJSModule( } if (!moduleObject) { - size_t index = sourceURL.reverseFind(PLATFORM_SEP, sourceURL.length()); + size_t index = lastPathSeparatorIndex(sourceURL); JSString* dirname; JSString* filename = requireMapKey; if (index != WTF::notFound) { @@ -1641,7 +1641,7 @@ JSObject* JSCommonJSModule::createBoundRequireFunction(VM& vm, JSGlobalObject* l auto scope = DECLARE_THROW_SCOPE(vm); JSString* filename = JSC::jsStringWithCache(vm, pathString); - auto index = pathString.reverseFind(PLATFORM_SEP, pathString.length()); + auto index = lastPathSeparatorIndex(pathString); JSString* dirname; if (index != WTF::notFound) { dirname = JSC::jsSubstring(globalObject, filename, 0, index); diff --git a/src/jsc/bindings/PathInlines.h b/src/jsc/bindings/PathInlines.h index dc39d5a58939..1d6271b0249b 100644 --- a/src/jsc/bindings/PathInlines.h +++ b/src/jsc/bindings/PathInlines.h @@ -55,6 +55,21 @@ ALWAYS_INLINE bool isAbsolutePath(WTF::String input) #undef IS_LETTER #undef IS_SLASH +ALWAYS_INLINE size_t lastPathSeparatorIndex(const WTF::String& path) +{ +#if OS(WINDOWS) + size_t slash = path.reverseFind(POSIX_PATH_SEP, path.length()); + size_t backslash = path.reverseFind(WINDOWS_PATH_SEP, path.length()); + if (slash == WTF::notFound) + return backslash; + if (backslash == WTF::notFound) + return slash; + return std::max(slash, backslash); +#else + return path.reverseFind(POSIX_PATH_SEP, path.length()); +#endif +} + extern "C" BunString ResolvePath__joinAbsStringBufCurrentPlatformBunString(JSC::JSGlobalObject*, BunString); /// CWD is determined by the global object's current cwd. diff --git a/test/bundler/bundler_edgecase.test.ts b/test/bundler/bundler_edgecase.test.ts index 45021b293479..299370398682 100644 --- a/test/bundler/bundler_edgecase.test.ts +++ b/test/bundler/bundler_edgecase.test.ts @@ -2146,6 +2146,54 @@ describe("bundler", () => { api.expectFile("/out.js").toMatch(/[^\.:]module/); // `.module` and `node:module` are not ok. }, }); + // __dirname/__filename lowering is target-sensitive; lock the per-target + // output shape so a property-name mixup can't silently pass when both + // targets are run under Bun (which aliases import.meta.dir/.dirname). #4216 + itBundled("edgecase/DirnameFilenameTargetBun#4216", { + target: "bun", + files: { + "/entry.ts": `console.log(capture(__dirname), capture(__filename));`, + }, + capture: ["__dirname", "__filename"], + onAfterBundle(api) { + // Word-boundary match: `import.meta.dir` is a prefix of the Node + // spelling `import.meta.dirname`, so a bare toContain can't tell + // them apart. + api.expectFile("/out.js").toMatch(/import\.meta\.dir\b/); + api.expectFile("/out.js").toMatch(/import\.meta\.path\b/); + api.expectFile("/out.js").not.toContain("import.meta.dirname"); + api.expectFile("/out.js").not.toContain("import.meta.filename"); + api.expectFile("/out.js").not.toContain('"/entry.ts"'); + }, + }); + itBundled("edgecase/DirnameFilenameTargetNode#4216", { + target: "node", + files: { + "/entry.ts": `console.log(capture(__dirname), capture(__filename));`, + }, + capture: ["__dirname", "__filename"], + onAfterBundle(api) { + api.expectFile("/out.js").toContain("import.meta.dirname"); + api.expectFile("/out.js").toContain("import.meta.filename"); + // Make sure we emit the Node spellings, not Bun's. + api.expectFile("/out.js").not.toMatch(/import\.meta\.dir\b/); + api.expectFile("/out.js").not.toMatch(/import\.meta\.path\b/); + }, + }); + itBundled("edgecase/DirnameFilenameTargetNodeCjs#4216", { + target: "node", + format: "cjs", + files: { + "/entry.ts": `console.log(capture(__dirname), capture(__filename), capture(import.meta.dir), capture(import.meta.path));`, + }, + capture: ["__dirname", "__filename", "__dirname", "__filename"], + onAfterBundle(api) { + // No declaration; references fall through to the host module wrapper. + api.expectFile("/out.js").not.toMatch(/var __dirname\b/); + api.expectFile("/out.js").not.toMatch(/var __filename\b/); + api.expectFile("/out.js").not.toContain("import.meta"); + }, + }); itBundled("edgecase/IdentifierInEnum#13081", { files: { "/entry.ts": ` diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index 350841445132..861a66ad6eea 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isWindows, tempDir, tmpdirSync } from "harness"; -import fs, { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { bunEnv, bunExe, isWindows, nodeExe, tempDir, tmpdirSync } from "harness"; +import fs, { cpSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import path, { join } from "node:path"; describe.concurrent( @@ -186,12 +186,21 @@ console.log(utils());`, }); const baseDir = baseDirPath + ""; + // `--compile` bundles for Bun's runtime, so `__dirname`/`__filename` + // resolve to the compiled executable's virtual `$bunfs` path at runtime + // instead of the build machine's source path (#4216). `--bytecode + // --format=esm` additionally covers the module-record import.meta flag: + // the injected `import.meta.dir` is the only import.meta reference here, + // and cached bytecode only links it when the parser marks the module + // accordingly. (`--bytecode` alone would imply CJS and skip that path.) const { exited } = Bun.spawn({ cmd: [ bunExe(), "build", path.join(baseDir, "我/我.ts"), "--compile", + "--bytecode", + "--format=esm", "--outfile", path.join(baseDir, "exe.exe"), ], @@ -211,8 +220,70 @@ console.log(utils());`, const text = await proc.stdout.text(); await proc.exited; - expect(text).toContain(path.join(baseDir, "我") + "\n"); - expect(text).toContain(path.join(baseDir, "我", "我.ts") + "\n"); + const bunfsRoot = isWindows ? "B:\\~BUN\\root" : "/$bunfs/root"; + expect(text).toBe(bunfsRoot + "\n" + path.join(bunfsRoot, "exe.exe") + "\n"); + + // The browser target has no runtime source for `__dirname`, so it still + // inlines the source path as a string literal. Exercise the UTF-8 path + // round-trip this test originally covered there. + await using browserBuild = Bun.spawn({ + cmd: [bunExe(), "build", path.join(baseDir, "我/我.ts"), "--target=browser"], + env: bunEnv, + cwd: baseDir, + stdout: "pipe", + stderr: "pipe", + }); + const [browserOut, browserErr, browserExit] = await Promise.all([ + browserBuild.stdout.text(), + browserBuild.stderr.text(), + browserBuild.exited, + ]); + expect(browserErr).not.toContain("error:"); + expect(browserOut).toContain(JSON.stringify(path.join(baseDir, "我"))); + expect(browserOut).toContain(JSON.stringify(path.join(baseDir, "我", "我.ts"))); + expect(browserExit).toBe(0); + }); + + test("__dirname and __filename from the CJS wrapper in compiled executables", async () => { + using dir = tempDir("bun-build-dirname-cjs", { + "entry.ts": "console.log(__dirname); console.log(__filename);", + }); + const base = String(dir); + + // `--bytecode` without `--format` implies CJS output: no declaration is + // injected, so `__dirname`/`__filename` come from the module wrapper. + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + path.join(base, "entry.ts"), + "--compile", + "--bytecode", + "--outfile", + path.join(base, "exe.exe"), + ], + env: bunEnv, + cwd: base, + stdout: "pipe", + stderr: "pipe", + }); + const [, buildErr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(buildErr).not.toContain("error:"); + expect(buildExit).toBe(0); + + await using proc = Bun.spawn({ + cmd: [path.join(base, "exe.exe")], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + // The wrapper params equal the standalone graph key, which is + // forward-slashed on every platform (`B:/~BUN/root`, not `B:\~BUN\root`). + const bunfsRoot = isWindows ? "B:/~BUN/root" : "/$bunfs/root"; + expect(stdout).toBe(bunfsRoot + "\n" + bunfsRoot + "/exe.exe\n"); + expect(exitCode).toBe(0); }); test.skipIf(!isWindows)("should be able to handle pretty path when using pnpm + #14685", async () => { @@ -517,3 +588,167 @@ describe("CLI argument error messages", () => { expect(exitCode).toBe(1); }); }); + +// https://github.com/oven-sh/bun/issues/4216 +describe.concurrent("__dirname/__filename resolve at runtime in bundled output", () => { + for (const target of ["bun", "node"] as const) { + // Node-target bundles run under a real `node` so the emitted + // `import.meta.dirname`/`filename` are exercised on the runtime they + // target, not just on Bun's implementation of them. + const missingNode = target === "node" && !nodeExe(); + + test.skipIf(missingNode)(`--target=${target}`, async () => { + using src = tempDir("dirname-4216-src", { + "nested/entry.js": ` + const dep = require("./dep.cjs"); + console.log(JSON.stringify({ + dirname: __dirname, + filename: __filename, + depDirname: dep.dir, + depFilename: dep.file, + })); + `, + "nested/dep.cjs": ` + module.exports = { dir: __dirname, file: __filename }; + `, + }); + const srcDir = String(src); + + // Build into a subdirectory of the source dir. + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + join(srcDir, "nested/entry.js"), + "--target", + target, + "--outfile", + join(srcDir, "build/bundle.mjs"), + ], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [, buildStderr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(buildStderr).not.toContain("error:"); + expect(buildExit).toBe(0); + + const bundleSource = await Bun.file(join(srcDir, "build/bundle.mjs")).text(); + // The build machine's absolute source path must not appear in the output. + expect(bundleSource).not.toContain(join(srcDir, "nested")); + + // Copy the bundle somewhere unrelated to the build directory and run it + // from there, so a hardcoded build-time path cannot accidentally resolve. + using runDir = tempDir("dirname-4216-run", {}); + const runPath = join(String(runDir), "moved.mjs"); + cpSync(join(srcDir, "build/bundle.mjs"), runPath); + + await using proc = Bun.spawn({ + cmd: [target === "node" ? nodeExe()! : bunExe(), runPath], + env: bunEnv, + cwd: String(runDir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const out = JSON.parse(stdout.trim()); + // All four should point at the *runtime* bundle location, not the source + // tree. The wrapped CJS dep sees the same chunk-level `import.meta` as the + // entry, so its __dirname/__filename match. + expect(out).toEqual({ + dirname: String(runDir), + filename: runPath, + depDirname: String(runDir), + depFilename: runPath, + }); + expect(exitCode).toBe(0); + }); + + test.skipIf(missingNode)(`--target=${target} --format=cjs`, async () => { + // Also reference `import.meta.dir`/`.path` so the test catches any + // divergence between them and `__dirname`/`__filename` in CJS output. + using src = tempDir("dirname-4216-cjs", { + "entry.js": ` + console.log(JSON.stringify({ + dirname: __dirname, + filename: __filename, + metaDir: import.meta.dir, + metaPath: import.meta.path, + })); + `, + }); + const srcDir = String(src); + + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + join(srcDir, "entry.js"), + "--target", + target, + "--format=cjs", + "--outfile", + join(srcDir, "bundle.cjs"), + ], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [, buildStderr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(buildStderr).not.toContain("error:"); + expect(buildExit).toBe(0); + + // The output must not re-declare __dirname/__filename with the build path; + // the CJS wrapper (Bun's `@bun-cjs` or Node's native module wrapper) + // already provides them. + const bundleSource = await Bun.file(join(srcDir, "bundle.cjs")).text(); + expect(bundleSource).not.toContain(srcDir); + + using runDir = tempDir("dirname-4216-cjs-run", {}); + const runPath = join(String(runDir), "moved.cjs"); + cpSync(join(srcDir, "bundle.cjs"), runPath); + + await using proc = Bun.spawn({ + cmd: [target === "node" ? nodeExe()! : bunExe(), runPath], + env: bunEnv, + cwd: String(runDir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(JSON.parse(stdout.trim())).toEqual({ + dirname: String(runDir), + filename: runPath, + metaDir: String(runDir), + metaPath: runPath, + }); + expect(exitCode).toBe(0); + }); + } + + // --target=browser has no runtime `import.meta.dir` equivalent, so it keeps + // the legacy behavior of inlining the build-time path as a string literal. + test.concurrent("--target=browser still inlines a string literal", async () => { + using src = tempDir("dirname-4216-browser", { + "entry.js": `console.log(__dirname, __filename);`, + }); + const srcDir = String(src); + + await using build = Bun.spawn({ + cmd: [bunExe(), "build", join(srcDir, "entry.js"), "--target", "browser"], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(stderr).not.toContain("error:"); + expect(stdout).toContain("var __dirname ="); + expect(stdout).not.toContain("import.meta"); + expect(exitCode).toBe(0); + }); +});