rolldown 1.2.3

Fast JavaScript bundler in Rust, designed for the future of Vite
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use std::borrow::Cow;
use std::fmt::Write as _;

use oxc_str::CompactStr;
use rolldown_common::{
  Chunk, ChunkKind, ExportsKind, IndexModules, ModuleIdx, NormalizedBundlerOptions, OutputExports,
  OutputFormat, Platform, SymbolRef, SymbolRefDb, WrapKind,
};
use rolldown_utils::{
  concat_string,
  ecmascript::{property_access_str, to_module_import_export_name},
  indexmap::FxIndexSet,
};
use rustc_hash::FxHashSet;

use crate::esm_init_obligations::{WrappedEsmInitTarget, collect_entry_reexported_wrapper_inits};
use crate::{stages::link_stage::LinkStageOutput, types::generator::GenerateContext};

pub fn render_wrapped_entry_chunk(
  ctx: &GenerateContext<'_>,
  export_mode: Option<&OutputExports>,
) -> Option<String> {
  if let ChunkKind::EntryPoint { module: entry_id, .. } = ctx.chunk.kind {
    let entry_meta = &ctx.link_output.metas[entry_id];
    if matches!(entry_meta.wrap_kind(), WrapKind::Cjs) {
      let wrapper_ref = entry_meta.wrapper_ref.as_ref().unwrap();

      let wrapper_ref_name = ctx.finalized_string_pattern_for_symbol_ref(
        *wrapper_ref,
        ctx.chunk_idx,
        &ctx.chunk.canonical_names,
      );

      return match ctx.options.format {
        OutputFormat::Esm => {
          // export default require_xxx();
          Some(concat_string!("export default ", wrapper_ref_name.as_str(), "();\n"))
        }
        OutputFormat::Cjs => {
          if matches!(&export_mode, Some(OutputExports::Named)) {
            Some(render_object_define_property("default", &concat_string!(wrapper_ref_name, "()")))
          } else {
            // module.exports = require_xxx();
            Some(concat_string!("module.exports = ", wrapper_ref_name, "();\n"))
          }
        }
        OutputFormat::Iife | OutputFormat::Umd => {
          if matches!(&export_mode, Some(OutputExports::Named)) {
            Some(render_object_define_property("default", &concat_string!(wrapper_ref_name, "()")))
          } else {
            // return require_xxx();
            Some(concat_string!("return ", wrapper_ref_name, "();\n"))
          }
        }
      };
    }

    if let Some(targets) = ctx.order_wrap_state.consumer_local_namespace_targets(entry_id) {
      let mut rendered = String::new();
      for target in targets {
        let wrapper_ref = match target {
          WrappedEsmInitTarget::Module(module_idx) => {
            let target =
              ctx.esm_init_target(*module_idx).expect("entry init target should have a wrapper");
            debug_assert!(!target.tla_tainted);
            target.wrapper_ref
          }
          WrappedEsmInitTarget::CjsCarrier(key) => {
            ctx
              .order_wrap_state
              .order_cjs_carrier(*key)
              .expect("entry CJS carrier should exist")
              .wrapper_ref
          }
        };
        let wrapper_name = ctx.finalized_string_pattern_for_symbol_ref(
          wrapper_ref,
          ctx.chunk_idx,
          &ctx.chunk.canonical_names,
        );
        writeln!(rendered, "{wrapper_name}();").expect("writing to a string cannot fail");
      }
      return Some(rendered);
    }

    let reexport_init_calls = render_entry_reexported_wrapper_init_calls(ctx, entry_id, entry_meta);

    match ctx.esm_init_target(entry_id) {
      Some(target) => {
        let wrapper_ref_name = ctx.finalized_string_pattern_for_symbol_ref(
          target.wrapper_ref,
          ctx.chunk_idx,
          &ctx.chunk.canonical_names,
        );
        let own_init_call = if target.tla_tainted {
          concat_string!("await ", wrapper_ref_name, "();")
        } else {
          concat_string!(wrapper_ref_name, "();")
        };
        match reexport_init_calls {
          Some(mut calls) => {
            calls.push_str(&own_init_call);
            Some(calls)
          }
          None => Some(own_init_call),
        }
      }
      None => reexport_init_calls,
    }
  } else {
    None
  }
}

/// Off-strict, an entry can re-export bindings owned by an ESM-wrapped module hosted in another
/// chunk while every statement that could call that module's `init_*` was tree-shaken (a pure
/// re-export barrel chain resolves bindings symbol-to-symbol, keeping the barrels' forwarding
/// statements excluded). Cross-chunk registration still imports each such wrapper — the non-strict
/// arm of `add_depended_symbol_with_wrapped_esm_init` pairs every depended binding with its
/// wrapper — but nothing ever calls it, so the wrapped module never evaluates and its bindings
/// read as `undefined` at runtime (issue #10543).
///
/// The entry chunk owns these calls: it already imports every such wrapper (no new chunk-graph
/// edges, hence no new cyclic-evaluation hazards for eager top-level init calls in shared
/// chunks). ESM evaluates dependencies before the importer's body, so an entry hosting its own
/// body gets the calls as a body prelude from the finalizer
/// (`entry_reexported_wrapper_init_prelude`); this chunk-tail path serves the remaining shapes,
/// where the tail still precedes the entry body: a facade chunk hosts no body at all, and a
/// wrapped entry's body only runs inside the wrapper invoked right after these calls.
fn render_entry_reexported_wrapper_init_calls(
  ctx: &GenerateContext<'_>,
  entry_id: ModuleIdx,
  entry_meta: &crate::types::linking_metadata::LinkingMetadata,
) -> Option<String> {
  if ctx.options.is_strict_execution_order_enabled() {
    // Strict execution order routes entry initialization through order-wrap lowering
    // (consumer-local targets and entry facades) instead.
    return None;
  }
  let entry_hosted_here = ctx.chunk_graph.module_to_chunk[entry_id] == Some(ctx.chunk_idx);
  let entry_is_wrapped = ctx.esm_init_target(entry_id).is_some();
  if entry_hosted_here && !entry_is_wrapped {
    return None;
  }
  let inits = collect_entry_reexported_wrapper_inits(
    entry_id,
    entry_meta,
    &ctx.link_output.metas,
    &ctx.link_output.module_table.modules,
    &ctx.link_output.symbol_db,
    Some(&ctx.chunk.canonical_names),
  );
  let mut rendered = String::new();
  for init in inits {
    // An in-chunk wrapped entry was wrapped together with its whole static graph (wrap
    // propagation), so a same-chunk owner's init is already covered inside the chunk — by a
    // statement-position call or the excluded-statement metadata's same-chunk arm — and calling
    // it again here would be a pure duplicate. A facade chunk gets no such guarantee for the
    // modules it hosts, so only the in-chunk wrapped entry filters.
    if entry_hosted_here && ctx.chunk_graph.module_to_chunk[init.owner] == Some(ctx.chunk_idx) {
      continue;
    }
    let wrapper_name = ctx.finalized_string_pattern_for_symbol_ref(
      init.wrapper_ref,
      ctx.chunk_idx,
      &ctx.chunk.canonical_names,
    );
    if init.tla_tainted {
      // Defensive parity with `wrapped_esm_init_call_expr`'s `await_if_tla`; believed
      // unreachable today. Non-`esm` formats reject top-level await at scan time
      // (`AstScanner::handle_top_level_await`), so this cannot produce an `await` inside a
      // plain iife/umd/cjs factory. Under `esm`, every off-strict `WrapKind::Esm` cause is
      // blocked from combining with TLA: a `require` reaching a TLA subtree is a build error
      // (`REQUIRE_TLA`), and the dynamic-import-with-splitting-disabled cause is single-chunk,
      // where a statement-position or metadata init always covers the module first.
      writeln!(rendered, "await {wrapper_name}();").expect("writing to a string cannot fail");
    } else {
      writeln!(rendered, "{wrapper_name}();").expect("writing to a string cannot fail");
    }
  }
  (!rendered.is_empty()).then_some(rendered)
}

#[expect(clippy::too_many_lines)] // Dispatches over every output format and export mode inline.
pub fn render_chunk_exports(
  ctx: &GenerateContext<'_>,
  export_mode: Option<&OutputExports>,
) -> Option<String> {
  let GenerateContext { chunk, link_output, options, .. } = ctx;
  let mut export_items: Vec<(CompactStr, SymbolRef)> = ctx.render_export_items_index_vec
    [ctx.chunk_idx]
    .iter()
    .flat_map(|(symbol_ref, names)| {
      let symbol_ref = *symbol_ref;
      names.iter().map(move |name| (name.clone(), symbol_ref))
    })
    .collect();

  match options.format {
    OutputFormat::Esm => {
      // If this is an entry point with a CJS wrapper, render_wrapped_entry_chunk already handles
      // the default export, so we should filter it out from export_items to avoid duplicates.
      if let ChunkKind::EntryPoint { module: entry_id, .. } = chunk.kind {
        let entry_meta = &link_output.metas[entry_id];
        if matches!(entry_meta.wrap_kind(), WrapKind::Cjs) {
          export_items.retain(|(exported_name, _)| exported_name.as_str() != "default");
        }
      }

      if export_items.is_empty() && !matches!(ctx.options.platform, Platform::Node) {
        return None;
      }
      let mut s = String::new();
      let rendered_items = export_items
        .into_iter()
        .map(|(exported_name, export_ref)| {
          let canonical_ref = link_output.symbol_db.canonical_ref_for(export_ref);
          let symbol = link_output.symbol_db.get(canonical_ref);
          let canonical_name = link_output
            .symbol_db
            .canonical_name_for_or_original(canonical_ref, &chunk.canonical_names);
          if let Some(ns_alias) = &symbol.namespace_alias {
            let canonical_ns_name = link_output
              .symbol_db
              .canonical_name_for_or_original(ns_alias.namespace_ref, &chunk.canonical_names);
            let property_name = &ns_alias.property_name;
            s.push_str("var ");
            s.push_str(canonical_name);
            s.push_str(" = ");
            s.push_str(canonical_ns_name);
            s.push('.');
            s.push_str(property_name);
            s.push_str(";\n");
          }

          if canonical_name == exported_name {
            Cow::Borrowed(canonical_name)
          } else {
            Cow::Owned(concat_string!(
              canonical_name,
              " as ",
              to_module_import_export_name(&exported_name)
            ))
          }
        })
        .collect::<Vec<_>>();
      s.push_str("export { ");
      for (i, item) in rendered_items.iter().enumerate() {
        if i > 0 {
          s.push_str(", ");
        }
        s.push_str(item);
      }
      s.push_str(" };");
      Some(s)
    }
    OutputFormat::Cjs | OutputFormat::Iife | OutputFormat::Umd => {
      let mut s = String::new();
      match chunk.kind {
        ChunkKind::EntryPoint { module, .. } => {
          let module =
            &link_output.module_table[module].as_normal().expect("should be normal module");
          if !matches!(module.exports_kind, ExportsKind::Esm) {
            export_items.retain(|(_, export_ref)| {
              let canonical_ref = link_output.symbol_db.canonical_ref_for(*export_ref);
              canonical_ref.owner != module.idx
            });
          }
          if !export_items.is_empty() {
            let rendered_items = export_items
              .into_iter()
              .map(|(exported_name, export_ref)| {
                let canonical_ref = link_output.symbol_db.canonical_ref_for(export_ref);
                let exported_value = ctx.finalized_string_pattern_for_symbol_ref(
                  canonical_ref,
                  ctx.chunk_idx,
                  &chunk.canonical_names,
                );

                match export_mode {
                  Some(OutputExports::Named) => {
                    // A strict-execution-order wrapper (`init_*`) self-rebinds on first call
                    // (`function init_x() { return (init_x = __esmMin(cb))() }`), so any
                    // cross-chunk export of it must expose a *live* getter. A value snapshot
                    // (`exports.init_x = init_x`) would freeze the pre-rebind function and re-run
                    // the module body on every later call. On current inputs wrapper refs only
                    // render through the common-chunk arm below (an entry chunk holding an
                    // order-wrapped module is split into a facade), which is unconditionally a
                    // getter; this entry-chunk pin is defense-in-depth so no future topology or
                    // optimization can route a wrapper into the value-snapshot branch.
                    let is_order_wrapper_ref =
                      ctx.order_wrap_state.is_execution_order_wrapper_ref(canonical_ref);
                    let keep_live_binding = must_keep_live_binding(
                      export_ref,
                      &link_output.symbol_db,
                      options,
                      &link_output.module_table.modules,
                    );
                    // Today `must_keep_live_binding` keeps wrapper refs live on its own, but only
                    // because the facade ref happens to lack `IsNotReassigned` — an emergent
                    // property, not a guaranteed one. If it ever breaks (e.g. a single-assignment
                    // optimization starts flagging facades), fail loudly in debug builds instead
                    // of silently leaning on the explicit `is_order_wrapper_ref` disjunct below.
                    debug_assert!(
                      !is_order_wrapper_ref || keep_live_binding,
                      "a strict-execution-order wrapper ref must never take the value-snapshot \
                       export branch (`exports.{exported_name} = {exported_value}`): it would \
                       freeze the pre-rebind function and re-run the module body",
                    );
                    if is_order_wrapper_ref || keep_live_binding {
                      render_object_define_property(&exported_name, &exported_value)
                    } else if exported_name.as_str() == "__proto__" {
                      // `__proto__` has special semantics - assigning to it sets the prototype
                      // instead of creating a property. We must use Object.defineProperty to
                      // set an actual property named "__proto__".
                      render_object_define_property_value(&exported_name, &exported_value)
                    } else {
                      concat_string!(
                        property_access_str("exports", exported_name.as_str()),
                        " = ",
                        exported_value.as_str(),
                        ";"
                      )
                    }
                  }
                  Some(OutputExports::Default) => {
                    if matches!(options.format, OutputFormat::Cjs) {
                      concat_string!("module.exports = ", exported_value.as_str(), ";")
                    } else {
                      concat_string!("return ", exported_value.as_str(), ";")
                    }
                  }
                  Some(OutputExports::None) => String::new(),
                  _ => unreachable!(),
                }
              })
              .collect::<Vec<_>>();
            s.push_str(&rendered_items.join("\n"));
          }

          let meta = &ctx.link_output.metas[module.idx];
          let external_modules = meta
            .star_exports_from_external_modules
            .iter()
            .filter_map(|rec_idx| module.ecma_view.import_records[*rec_idx].resolved_module)
            .chain(ctx.chunk.entry_level_external_module_idx.iter().copied())
            .collect::<FxIndexSet<ModuleIdx>>();

          // Track already imported external modules to avoid duplicates
          // First check if any of these external modules have already been imported elsewhere in the chunk
          let mut imported_external_modules: FxHashSet<SymbolRef> = ctx
            .chunk
            .direct_imports_from_external_modules
            .iter()
            .map(|(idx, _)| {
              let external = &ctx.link_output.module_table[*idx]
                .as_external()
                .expect("Should be external module here");
              external.namespace_ref
            })
            .chain(ctx.chunk.import_symbol_from_external_modules.iter().map(|idx| {
              let external = &ctx.link_output.module_table[*idx]
                .as_external()
                .expect("Should be external module here");
              external.namespace_ref
            }))
            .collect();
          external_modules.iter().for_each(|idx| {
          let external = &ctx.link_output.module_table[*idx].as_external().expect("Should be external module here");
          let binding_ref_name = ctx
            .link_output
            .symbol_db
            .canonical_name_for_or_original(external.namespace_ref, &ctx.chunk.canonical_names);
          let import_stmt = concat_string!(
            "Object.keys(",binding_ref_name, ").forEach(function (k) {\n",
            "  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {\n",
            "    enumerable: true,\n",
            "    get: function () { return ",binding_ref_name,"[k]; }\n",
            "  });\n",
            "});\n"
          );

          s.push('\n');
          // Only generate require statement if this external module hasn't been imported yet
          if imported_external_modules.insert(external.namespace_ref) {
            writeln!(s, "var {} = require(\"{}\");", binding_ref_name, external.get_import_path(chunk, ctx.resolved_paths)).unwrap();
          }
          s.push_str(&import_stmt);
        });
        }
        ChunkKind::Common => {
          let rendered_items = export_items
            .into_iter()
            .map(|(exported_name, export_ref)| {
              let canonical_ref = link_output.symbol_db.canonical_ref_for(export_ref);
              let symbol = link_output.symbol_db.get(canonical_ref);
              let canonical_name = link_output
                .symbol_db
                .canonical_name_for_or_original(canonical_ref, &chunk.canonical_names);

              match &symbol.namespace_alias {
                Some(ns_alias) => {
                  let canonical_ns_name = link_output
                    .symbol_db
                    .canonical_name_for_or_original(ns_alias.namespace_ref, &chunk.canonical_names);
                  let property_name = &ns_alias.property_name;
                  render_object_define_property(
                    &exported_name,
                    &concat_string!(canonical_ns_name, ".", property_name),
                  )
                }
                _ => render_object_define_property(&exported_name, canonical_name),
              }
            })
            .collect::<Vec<_>>();
          s.push_str(&rendered_items.join("\n"));
        }
      }

      if s.is_empty() {
        return None;
      }
      Some(s)
    }
  }
}

#[inline]
pub fn render_object_define_property(key: &str, value: &str) -> String {
  concat_string!(
    "Object.defineProperty(exports, '",
    key,
    "', {
  enumerable: true,
  get: function () {
    return ",
    value,
    ";
  }
});"
  )
}

#[inline]
pub fn render_object_define_property_value(key: &str, value: &str) -> String {
  concat_string!(
    "Object.defineProperty(exports, '",
    key,
    "', {
  enumerable: true,
  value: ",
    value,
    "
});"
  )
}

pub fn get_export_items(chunk: &Chunk) -> Vec<(CompactStr, SymbolRef)> {
  let mut export_items = chunk
    .exports_to_other_chunks
    .iter()
    .flat_map(|(export_ref, alias_list)| {
      alias_list.iter().map(|alias| (alias.clone(), *export_ref))
    })
    .collect::<Vec<_>>();

  export_items.sort_unstable_by(|a, b| a.0.as_str().cmp(b.0.as_str()));

  export_items
}

pub fn get_chunk_export_names(chunk: &Chunk, graph: &LinkStageOutput) -> Vec<CompactStr> {
  if let ChunkKind::EntryPoint { module: entry_id, .. } = &chunk.kind {
    let entry_meta = &graph.metas[*entry_id];
    if matches!(entry_meta.wrap_kind(), WrapKind::Cjs) {
      return vec![CompactStr::new("default")];
    }
  }

  get_export_items(chunk).into_iter().map(|(exported_name, _)| exported_name).collect::<Vec<_>>()
}

pub fn get_chunk_export_names_with_ctx(ctx: &GenerateContext<'_>) -> Vec<CompactStr> {
  let GenerateContext { chunk, link_output, render_export_items_index_vec, .. } = ctx;
  if let ChunkKind::EntryPoint { module: entry_id, .. } = &chunk.kind {
    let entry_meta = &link_output.metas[*entry_id];
    if matches!(entry_meta.wrap_kind(), WrapKind::Cjs) {
      return vec![CompactStr::new("default")];
    }
  }
  render_export_items_index_vec[ctx.chunk_idx].values().flatten().cloned().collect::<Vec<_>>()
}

fn must_keep_live_binding(
  export_ref: SymbolRef,
  symbol_db: &SymbolRefDb,
  options: &NormalizedBundlerOptions,
  modules: &IndexModules,
) -> bool {
  let canonical_ref = symbol_db.canonical_ref_for(export_ref);

  if canonical_ref.is_declared_by_const(symbol_db) {
    return false;
  }

  if canonical_ref.is_not_reassigned(symbol_db) {
    // For unknown case, we consider it as reassigned.
    return false;
  }

  if !options.external_live_bindings
    && canonical_ref.is_created_by_import_stmt_that_target_external(symbol_db, modules)
  {
    return false;
  }

  true
}