Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 7 additions & 5 deletions src/js_parser/p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ use crate::{
FindLabelSymbolResult, FnOnlyDataVisit, FnOrArrowDataParse, FnOrArrowDataVisit, FunctionKind,
IdentifierOpts, ImportItemForNamespaceMap, InvalidLoc, JSXImport, JSXTransformType, Jest,
LOC_MODULE_SCOPE as loc_module_scope, LocList, MacroState, ParseStatementOptions, ParsedPath,
PrependTempRefsOpts, ReactRefresh, Ref, RefMap, RefRefMap, RuntimeImports, ScopeOrder,
ScopeOrderList, StrictModeFeature, StringBoolMap, Substitution, TempRef, ThenCatchChain,
TransposeState, WrapMode, fs, is_eval_or_arguments, options, statement_cares_about_scope,
PrependTempRefsOpts, ReactRefresh, Ref, RefMap, RefRefMap, RequireUnwrap, RuntimeImports,
ScopeOrder, ScopeOrderList, StrictModeFeature, StringBoolMap, Substitution, TempRef,
ThenCatchChain, TransposeState, WrapMode, fs, is_eval_or_arguments, options,
statement_cares_about_scope,
};
use bun_ast as js_ast;
use bun_ast::DeclaredSymbol;
Expand Down Expand Up @@ -1147,7 +1148,8 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
// We cannot unwrap a require wrapped in a try/catch because
// import statements cannot be wrapped in a try/catch and
// require cannot return a promise.
&& !handles_import_errors;
&& !handles_import_errors
&& state.require_unwrap != RequireUnwrap::Disabled;

if should_unwrap_require {
let import_record_index = self.add_import_record_by_range_and_path(
Expand Down Expand Up @@ -1190,7 +1192,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
.insert(namespace_ref, ImportItemForNamespaceMap::default());
self.record_usage(namespace_ref);

if !state.is_require_immediately_assigned_to_decl {
if state.require_unwrap != RequireUnwrap::IntoDecl {
return self.new_expr(
E::Identifier {
ref_: namespace_ref,
Expand Down
21 changes: 16 additions & 5 deletions src/js_parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -691,11 +691,23 @@ pub struct VisitDeclOpts {
pub(crate) could_be_macro: bool,
}

/// What a `require()` of a package on the CommonJS unwrap list becomes at the visited position.
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum RequireUnwrap {
/// A reference to the namespace of the `import * as ns` it becomes.
#[default]
Namespace,
/// `const x = require("pkg")`: the import takes over `x` and `visit_decls` drops the declarator.
IntoDecl,
/// Stays a plain `require()`, as inside a try/catch: `using` disposes the required value itself.
Disabled,
}

#[derive(Clone, Copy)]
pub struct TransposeState {
pub(crate) is_await_target: bool,
pub(crate) is_then_catch_target: bool,
pub(crate) is_require_immediately_assigned_to_decl: bool,
pub(crate) require_unwrap: RequireUnwrap,
pub(crate) loc: bun_ast::Loc,
pub(crate) import_record_tag: Option<bun_ast::ImportRecordTag>,
pub(crate) import_loader: Option<bun_ast::Loader>,
Expand All @@ -707,7 +719,7 @@ impl Default for TransposeState {
Self {
is_await_target: false,
is_then_catch_target: false,
is_require_immediately_assigned_to_decl: false,
require_unwrap: RequireUnwrap::Namespace,
loc: bun_ast::Loc::EMPTY,
import_record_tag: None,
import_loader: None,
Expand Down Expand Up @@ -1011,9 +1023,8 @@ pub struct ExprIn {
/// tests.
pub(crate) assign_target: js_ast::AssignTarget,

/// Currently this is only used when unwrapping a call to `require()`
/// with `__toESM()`.
pub(crate) is_immediately_assigned_to_decl: bool,
/// Set by `visit_decls` when the expression initializes a declarator.
pub(crate) require_unwrap: RequireUnwrap,

pub(crate) property_access_for_method_call_maybe_should_replace_with_undefined: bool,
}
Expand Down
17 changes: 13 additions & 4 deletions src/js_parser/visit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use crate::lexer as js_lexer;
use crate::p::{LowerUsingDeclarationsContext, P};
use crate::parser::{
ExprIn, FnOnlyDataVisit, FnOrArrowDataVisit, ImportItemForNamespaceMap, PrependTempRefsOpts,
Ref, RelocateVarsMode, ScopeOrder, StmtsKind, StrictModeFeature, StringVoidMap, VisitArgsOpts,
VisitDeclOpts, is_eval_or_arguments,
Ref, RelocateVarsMode, RequireUnwrap, ScopeOrder, StmtsKind, StrictModeFeature, StringVoidMap,
VisitArgsOpts, VisitDeclOpts, is_eval_or_arguments,
};
use bun_alloc::{ArenaVec as BumpVec, ArenaVecExt as _};
use bun_ast as js_ast;
Expand Down Expand Up @@ -242,8 +242,17 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
pub(crate) fn visit_decls<const IS_POSSIBLY_DECL_TO_REMOVE: bool>(
&mut self,
decls: &mut [G::Decl],
was_const: bool,
kind: LocalKind,
is_export: bool,
) -> usize {
let was_const = kind == LocalKind::KConst;
let require_unwrap = if kind.is_using() {
RequireUnwrap::Disabled
} else if is_export {
RequireUnwrap::Namespace
} else {
RequireUnwrap::IntoDecl
};
let mut j: usize = 0;
// Iterate by index so kept entries can be written back through `decls[j]`
// while scanning ahead.
Expand Down Expand Up @@ -320,7 +329,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
self.visit_expr_in_out(
&mut val,
ExprIn {
is_immediately_assigned_to_decl: true,
require_unwrap,
..Default::default()
},
);
Expand Down
12 changes: 9 additions & 3 deletions src/js_parser/visit/visit_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ use crate::lexer as js_lexer;
use crate::p::P;
use crate::parser::{
ExprIn, FnOrArrowDataVisit, IdentifierOpts, PrependTempRefsOpts, ReactRefresh, Ref,
StrictModeFeature, ThenCatchChain, TransposeState, VisitArgsOpts, float_to_int32, prefill,
RequireUnwrap, StrictModeFeature, ThenCatchChain, TransposeState, VisitArgsOpts,
float_to_int32, prefill,
};
use crate::scan::scan_side_effects::SideEffects;
use bun_alloc::ArenaVecExt as _;
Expand Down Expand Up @@ -2019,8 +2020,13 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
if e_.args.len_u32() == 1 {
let first = e_.args.slice()[0];
let state = TransposeState {
is_require_immediately_assigned_to_decl: in_.is_immediately_assigned_to_decl
&& matches!(first.data, Data::EString(..)),
require_unwrap: match in_.require_unwrap {
// Only a string literal can take over the declaration.
RequireUnwrap::IntoDecl if !matches!(first.data, Data::EString(..)) => {
RequireUnwrap::Namespace
}
mode => mode,
},
..Default::default()
};
match &first.data {
Expand Down
5 changes: 2 additions & 3 deletions src/js_parser/visit/visit_stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1132,11 +1132,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
p.cur_scope().is_after_const_local_prefix = was_after_after_const_local_prefix;

// visit_decls returns the surviving decl count; truncate `data.decls.len` to it.
let was_const = data.kind == S::Kind::KConst;
let new_len = if !(data.is_export && p.options.features.replace_exports.entries.len() > 0) {
p.visit_decls::<false>(data.decls.slice_mut(), was_const)
p.visit_decls::<false>(data.decls.slice_mut(), data.kind, data.is_export)
} else {
p.visit_decls::<true>(data.decls.slice_mut(), was_const)
p.visit_decls::<true>(data.decls.slice_mut(), data.kind, data.is_export)
};
// Drop the whole statement when every decl was
// eliminated; otherwise we'd emit an empty `var;`/`let;`/`const;`.
Expand Down
118 changes: 118 additions & 0 deletions test/bundler/bundler_cjs2esm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,124 @@ describe("bundler", () => {
stdout: "react\nreact",
},
});
// `const x = require("react")` is normally replaced by the import it becomes.
// An exported declaration has to survive as a declaration, or the export is
// dropped with it.
itBundled("cjs2esm/UnwrappedModuleRequireExported", {
files: {
"/entry.js": /* js */ `
import { constReact, varReact, letReact, first, second, third } from "./lib.js";
import { importEquals, NS } from "./lib-ts.ts";
console.log(constReact.react, varReact.react, letReact.react);
console.log(first.react, second, third.react);
console.log(importEquals.react, NS.react.react);
`,
"/lib.js": /* js */ `
export const constReact = require("react");
export var varReact = require("react");
export let letReact = require("react");
export const first = require("react"),
second = "second",
third = require("react");
`,
"/lib-ts.ts": /* ts */ `
export import importEquals = require("react");
export namespace NS {
export const react = require("react");
}
`,
...fakeReactNodeModules,
},
run: {
stdout: "react react react\nreact second react\nreact react",
},
});
// Same against a package that converts to ESM. The unexported declaration is
// still folded into the import; the exported one stays a declaration.
itBundled("cjs2esm/UnwrappedModuleRequireExportedConverted", {
files: {
"/entry.js": /* js */ `
import { exported } from "./lib.js";
console.log(exported.react);
`,
"/lib.js": /* js */ `
export const exported = require("react");
const unexported = require("react");
console.log(unexported.react);
`,
"/node_modules/react/index.js": /* js */ `
exports.react = "react";
`,
"/node_modules/react/package.json": /* json */ `
{
"name": "react",
"version": "2.0.0",
"main": "index.js"
}
`,
},
onAfterBundle: api => {
const code = api.readFile("out.js");
expect(code).toMatch(/var exported = \(?exports_react\)?;/);
expect(code).not.toContain("unexported");
},
run: {
stdout: "react\nreact",
},
});
// A `using` declaration disposes the required value itself, so its require()
// is not unwrapped at all: the import namespace __toESM() builds has no
// symbol-keyed properties and only getters. The expected output is what the
// entry prints unbundled.
itBundled("cjs2esm/UnwrappedModuleRequireUsing", {
files: {
"/entry.js": /* js */ `
import reactExports from "react";
import schedulerExports from "scheduler";
{
using react = require("react");
await using scheduler = require("scheduler");
using conditional = require(Math.random() < 2 ? "react" : "scheduler");
console.log(react.react, scheduler.scheduler, conditional.react);
console.log(react === reactExports, scheduler === schedulerExports, conditional === reactExports);
}
console.log("after", reactExports.disposed, schedulerExports.disposed);
`,
"/node_modules/react/index.js": /* js */ `
module.exports = {
react: "react",
[Symbol.dispose]() {
this.disposed = true;
console.log("dispose react");
},
};
`,
"/node_modules/react/package.json": /* json */ `
{
"name": "react",
"version": "2.0.0",
"main": "index.js"
}
`,
"/node_modules/scheduler/index.js": /* js */ `
exports.scheduler = "scheduler";
exports[Symbol.asyncDispose] = async function () {
this.disposed = true;
console.log("dispose scheduler");
};
`,
"/node_modules/scheduler/package.json": /* json */ `
{
"name": "scheduler",
"version": "1.0.0",
"main": "index.js"
}
`,
},
run: {
stdout: "react scheduler react\ntrue true true\ndispose react\ndispose scheduler\ndispose react\nafter true true",
},
});
itBundled("cjs2esm/ReactSpecificUnwrapping", {
files: {
"/entry.js": /* js */ `
Expand Down
Loading