swc_bundler/bundler/chunk/computed_key.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
use std::mem::take;
use anyhow::{bail, Error};
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{contains_top_level_await, find_pat_ids, private_ident, ExprFactory};
use swc_ecma_visit::{noop_fold_type, Fold};
use crate::{
bundler::chunk::merge::Ctx,
modules::Modules,
util::{is_injected, ExportMetadata},
Bundler, Load, ModuleId, Resolve,
};
impl<L, R> Bundler<'_, L, R>
where
L: Load,
R: Resolve,
{
// Converts
///
/// ```ts
/// export const arr = [1, 2, 3];
/// ```
///
/// to
///
/// ```ts
/// const _mod = (function(){
/// const arr = [1, 2, 3];
/// return {
/// arr,
/// };
/// })();
/// ```
pub(super) fn wrap_esm(
&self,
ctx: &Ctx,
id: ModuleId,
module: Modules,
) -> Result<Modules, Error> {
let span = DUMMY_SP;
let module_var_name = match self.scope.wrapped_esm_id(id) {
Some(v) => v,
None => bail!("{:?} should not be wrapped with a function", id),
};
let is_async = module.iter().any(|m| contains_top_level_await(m.1));
let mut additional_items = Vec::new();
module.iter().for_each(|(module_id, item)| {
match item {
// Handle `export *`-s from dependency modules.
//
// See: https://github.com/denoland/deno/issues/9200
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport {
ref specifiers,
with: Some(with),
..
})) if is_injected(with) => {
for s in specifiers {
if let ExportSpecifier::Named(ExportNamedSpecifier {
orig,
exported: Some(exported),
..
}) = s
{
let exported = match exported {
ModuleExportName::Ident(ident) => ident,
ModuleExportName::Str(..) => {
unimplemented!("module string names unimplemented")
}
};
if ctx.transitive_remap.get(&exported.ctxt).is_some() {
let specifier = ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig: orig.clone(),
exported: Some(ModuleExportName::Ident(exported.clone())),
is_type_only: false,
});
additional_items.push((
module_id,
NamedExport {
span: DUMMY_SP,
specifiers: vec![specifier],
src: None,
type_only: false,
with: Some(
ExportMetadata {
injected: true,
..Default::default()
}
.into_with(),
),
}
.into(),
));
}
}
}
}
_ => {}
}
});
let mut export_visitor = ExportToReturn {
synthesized_ctxt: self.synthesized_ctxt,
return_props: Default::default(),
};
let mut module = module.fold_with(&mut export_visitor);
module.append_all(additional_items);
let return_stmt = ReturnStmt {
span: DUMMY_SP,
arg: Some(
ObjectLit {
span: DUMMY_SP,
props: take(&mut export_visitor.return_props),
}
.into(),
),
}
.into();
module.iter().for_each(|(_, v)| {
if let ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ref export)) = v {
// We handle this later.
let mut map = ctx.export_stars_in_wrapped.lock();
let data = ExportMetadata::decode(export.with.as_deref());
if let Some(export_ctxt) = data.export_ctxt {
map.entry(id).or_default().push(export_ctxt);
}
}
});
let module_fn: Expr = FnExpr {
function: Box::new(Function {
params: Default::default(),
body: Some(BlockStmt {
span: DUMMY_SP,
stmts: vec![return_stmt],
..Default::default()
}),
is_generator: false,
is_async,
..Default::default()
}),
ident: None,
}
.into();
let mut module_expr = CallExpr {
span: DUMMY_SP,
callee: module_fn.as_callee(),
args: Default::default(),
..Default::default()
}
.into();
if is_async {
module_expr = AwaitExpr {
span: DUMMY_SP,
arg: Box::new(module_expr),
}
.into();
}
let var_decl = VarDecl {
span,
ctxt: self.injected_ctxt,
declare: false,
kind: VarDeclKind::Const,
decls: vec![VarDeclarator {
span: DUMMY_SP,
definite: false,
name: Pat::Ident(module_var_name.into_ident().into()),
init: Some(Box::new(module_expr)),
}],
};
module.append(id, var_decl.into());
// print_hygiene(
// "wrap",
// &self.cm,
// &Module {
// span: DUMMY_SP,
// body: module_items.clone(),
// shebang: None,
// },
// );
Ok(module)
}
}
struct ExportToReturn {
return_props: Vec<PropOrSpread>,
synthesized_ctxt: SyntaxContext,
}
impl ExportToReturn {
fn export_id(&mut self, mut i: Ident) {
i.ctxt = SyntaxContext::empty();
self.return_props
.push(PropOrSpread::Prop(Box::new(Prop::Shorthand(i))));
}
fn export_key_value(&mut self, key: Ident, value: Ident) {
self.return_props
.push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(key.into()),
value: value.into(),
}))));
}
}
impl Fold for ExportToReturn {
noop_fold_type!();
fn fold_stmt(&mut self, s: Stmt) -> Stmt {
s
}
fn fold_module_item(&mut self, item: ModuleItem) -> ModuleItem {
let decl = match item {
ModuleItem::ModuleDecl(decl) => decl,
ModuleItem::Stmt(_) => return item,
};
let stmt = match decl {
ModuleDecl::Import(_) => return decl.into(),
ModuleDecl::ExportDecl(export) => {
match &export.decl {
Decl::Class(ClassDecl { ident, .. }) | Decl::Fn(FnDecl { ident, .. }) => {
self.export_id(ident.clone());
}
Decl::Var(decl) => {
let ids: Vec<Ident> = find_pat_ids(decl);
ids.into_iter().for_each(|id| self.export_id(id));
}
_ => unreachable!(),
}
Some(ModuleItem::from(export.decl))
}
ModuleDecl::ExportDefaultDecl(export) => match export.decl {
DefaultDecl::Class(expr) => {
let ident = expr.ident;
let ident = ident.unwrap_or_else(|| private_ident!("_default_decl"));
self.export_key_value(
Ident::new_no_ctxt("default".into(), export.span),
ident.clone(),
);
Some(
ClassDecl {
ident,
class: expr.class,
declare: false,
}
.into(),
)
}
DefaultDecl::Fn(expr) => {
let ident = expr.ident;
let ident = ident.unwrap_or_else(|| private_ident!("_default_decl"));
self.export_key_value(
Ident::new_no_ctxt("default".into(), export.span),
ident.clone(),
);
Some(
FnDecl {
ident,
function: expr.function,
declare: false,
}
.into(),
)
}
DefaultDecl::TsInterfaceDecl(_) => None,
},
ModuleDecl::ExportDefaultExpr(_) => None,
ModuleDecl::ExportAll(export) => return export.into(),
ModuleDecl::ExportNamed(export) => {
for specifier in &export.specifiers {
match specifier {
ExportSpecifier::Namespace(_) => {}
ExportSpecifier::Default(_) => {}
ExportSpecifier::Named(named) => match &named.exported {
Some(ModuleExportName::Ident(exported)) => {
// As injected named exports are converted to variables by other
// passes, we should not create a variable for it.
if let ModuleExportName::Ident(orig) = &named.orig {
self.export_key_value(exported.clone(), orig.clone());
} else {
unimplemented!("module string names unimplemented")
}
}
Some(ModuleExportName::Str(..)) => {
unimplemented!("module string names unimplemented")
}
None => {
if let ModuleExportName::Ident(orig) = &named.orig {
self.export_id(orig.clone());
} else {
unimplemented!("module string names unimplemented")
}
}
},
}
}
let md = ExportMetadata::decode(export.with.as_deref());
// Ignore export {} specified by user.
if export.src.is_none()
&& md.export_ctxt.unwrap_or_default() != self.synthesized_ctxt
{
None
} else {
return export.into();
}
}
ModuleDecl::TsImportEquals(_) => None,
ModuleDecl::TsExportAssignment(_) => None,
ModuleDecl::TsNamespaceExport(_) => None,
};
if let Some(stmt) = stmt {
stmt
} else {
EmptyStmt { span: DUMMY_SP }.into()
}
}
}