Unverified Commit e3ababa0 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Trace export usage through client component proxies (#98621)

## Summary

Turbopack previously widened export usage to every export when a Server
Component crossed a client-component proxy. As a result, importing one
named export from a `use client` module retained unrelated
implementations in both browser and SSR bundles.

This extends Turbopack's import annotations with a generic export-usage
passthrough. The server transform for `use client` modules marks its
generated namespace import as passthrough, so the ordinary binding-usage
fixed point carries the Server Component's used export set into
`EcmascriptClientReferenceModule`. Its client-reference edges use the
same signal to forward that set to browser and SSR targets.
Side-effect-only evaluation references retain their evaluation semantics
instead of inheriting the annotation. The forwarded names remain
namespace-observable because React Flight resolves client references by
their original export names, so unused exports can be removed without
changing the protocol-visible identity. An importer whose usage is `All`
still forwards `All`.

The client-component tree-shaking test now checks that unused markers
are absent from every browser chunk and verifies the same behavior in
Turbopack SSR chunks.

## Verification

- `cargo fmt --all -- --check`
- `cargo check -p next-core`
- `cargo test -p turbopack-core module_graph::binding_usage_info::tests
--lib`
- `pnpm build-all`
- `pnpm test-start-turbo
test/production/app-dir/client-components-tree-shaking/index.test.ts`
- `pnpm test-start-webpack
test/production/app-dir/client-components-tree-shaking/index.test.ts`

<!-- NEXT_JS_LLM -->


<!-- fleet 10716dab-2d36-4687-94ae-cd7bdfeac985 -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 000390a8
......@@ -20,7 +20,7 @@ use turbopack_core::{
output::OutputAssetsReference,
reference::{ModuleReference, ModuleReferences},
reference_type::ReferenceType,
resolve::ModuleResolveResult,
resolve::{BindingUsage, ExportUsage, ImportUsage, ModuleResolveResult},
source::OptionSource,
virtual_source::VirtualSource,
};
......@@ -394,4 +394,14 @@ impl ModuleReference for EcmascriptClientReference {
merge_tag: self.merge_tag.clone(),
})
}
fn binding_usage(&self) -> BindingUsage {
BindingUsage {
import: ImportUsage::TopLevel,
export: ExportUsage::Passthrough {
// React Flight resolves the target module with the original export name.
namespace_object_may_escape: true,
},
}
}
}
......@@ -93,10 +93,33 @@ describe('app-dir client-components-tree-shaking', () => {
chunkContents.some((content) => content.includes('client-comp-imported'))
).toBe(true)
expect(
chunkContents.every((content) => content.includes('client-comp-unused'))
chunkContents.some((content) => content.includes('client-comp-unused'))
).toBe(false)
expect(
chunkContents.every((content) => content.includes('client-comp-default'))
chunkContents.some((content) => content.includes('client-comp-default'))
).toBe(false)
if (process.env.IS_TURBOPACK_TEST) {
const ssrChunkContents = await next.readFiles(
'.next/server/chunks/ssr',
(filename) => filename.endsWith('.js')
)
expect(
ssrChunkContents.some((content) =>
content.includes('client-comp-imported')
)
).toBe(true)
expect(
ssrChunkContents.some((content) =>
content.includes('client-comp-unused')
)
).toBe(false)
expect(
ssrChunkContents.some((content) =>
content.includes('client-comp-default')
)
).toBe(false)
}
})
})
......@@ -265,17 +265,33 @@ pub async fn compute_binding_usage_info(
}
}
let entry = used_exports.entry(target);
let is_first_visit = matches!(entry, Entry::Vacant(_));
if matches!(
&ref_data.binding_usage.export,
ExportUsage::PartialNamespaceObject(_)
) {
// `target` is read through a namespace value. We know which names are used, but
// not that every read of them was lowered to a direct named access.
partial_namespace_modules.insert(target);
}
if entry.or_default().add(&ref_data.binding_usage.export) || is_first_visit {
let is_first_visit = !used_exports.contains_key(&target);
let changed = match &ref_data.binding_usage.export {
ExportUsage::Passthrough {
namespace_object_may_escape,
} => {
if *namespace_object_may_escape {
partial_namespace_modules.insert(target);
}
let passthrough_usage = used_exports
.get(&parent)
.context("parent module must have usage info")?
.clone();
used_exports
.entry(target)
.or_default()
.add_usage_info(&passthrough_usage)
}
export_usage => {
if matches!(export_usage, ExportUsage::PartialNamespaceObject(_)) {
// `target` is read through a namespace value. We know which names are
// used, but not that every read was lowered to a direct named access.
partial_namespace_modules.insert(target);
}
used_exports.entry(target).or_default().add(export_usage)
}
};
if changed || is_first_visit {
// First visit, or the used exports changed. This can cause more imports to get
// used downstream.
Ok(GraphTraversalAction::Continue)
......@@ -421,6 +437,34 @@ impl ModuleExportUsageInfo {
changed
}
(_, ExportUsage::Evaluation) => false,
(_, ExportUsage::Passthrough { .. }) => {
// Passthrough is normally resolved before `add`. If it reaches this fallback,
// preserve correctness by widening rather than panicking during graph analysis.
*self = Self::All;
true
}
}
}
/// Merge another module's resolved export usage into this one. Returns true if self changed.
fn add_usage_info(&mut self, usage: &Self) -> bool {
match (&mut *self, usage) {
(Self::All, _) | (_, Self::Evaluation) => false,
(_, Self::All) => {
*self = Self::All;
true
}
(Self::Evaluation, Self::Exports(exports)) => {
*self = Self::Exports(exports.clone());
true
}
(Self::Exports(left), Self::Exports(right)) => {
let mut changed = false;
for export in right {
changed |= left.insert(export.clone());
}
changed
}
}
}
......@@ -432,3 +476,31 @@ impl ModuleExportUsageInfo {
}
}
}
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
use super::ModuleExportUsageInfo;
use crate::resolve::ExportUsage;
#[test]
fn resolved_usage_merges_exports() {
let mut usage = ModuleExportUsageInfo::Exports([rcstr!("first")].into_iter().collect());
let additional = ModuleExportUsageInfo::Exports([rcstr!("second")].into_iter().collect());
assert!(usage.add_usage_info(&additional));
assert!(usage.is_export_used(&rcstr!("first")));
assert!(usage.is_export_used(&rcstr!("second")));
}
#[test]
fn unresolved_passthrough_falls_back_to_all() {
let mut usage = ModuleExportUsageInfo::Evaluation;
assert!(usage.add(&ExportUsage::Passthrough {
namespace_object_may_escape: false,
}));
assert!(matches!(usage, ModuleExportUsageInfo::All));
}
}
......@@ -176,6 +176,13 @@ pub enum ExportUsage {
All,
/// Only side effects are used.
Evaluation,
/// Use the same exports that are used from the referencing module. This is used by transparent
/// module proxies that forward their export surface to another module.
Passthrough {
/// The forwarded exports are read through a namespace object, so their original names may
/// be observed even when the individual used names are known.
namespace_object_may_escape: bool,
},
}
impl Display for ExportUsage {
......@@ -194,6 +201,18 @@ impl Display for ExportUsage {
}
ExportUsage::All => write!(f, "all"),
ExportUsage::Evaluation => write!(f, "evaluation"),
ExportUsage::Passthrough {
namespace_object_may_escape,
..
} => write!(
f,
"passthrough{}",
if *namespace_object_may_escape {
" namespace"
} else {
""
}
),
}
}
}
......
......@@ -11,7 +11,7 @@ use swc_core::{
};
use turbopack_ecmascript::{
TURBOPACK_HELPER,
annotations::{ANNOTATION_TRANSITION, with_clause},
annotations::{ANNOTATION_EXPORT_USAGE, ANNOTATION_TRANSITION, with_clause},
runtime_functions::TURBOPACK_EXPORT_NAMESPACE,
};
......@@ -29,6 +29,7 @@ pub fn create_proxy_module(transition_name: &str, target_import: &str) -> Progra
with: Some(with_clause(&[
(TURBOPACK_HELPER.as_str(), "true"),
(ANNOTATION_TRANSITION, transition_name),
(ANNOTATION_EXPORT_USAGE, "passthrough"),
])),
span: DUMMY_SP,
phase: Default::default(),
......
......@@ -70,6 +70,10 @@ pub struct ImportAnnotations {
static ANNOTATION_TRANSITION: LazyLock<Wtf8Atom> =
LazyLock::new(|| crate::annotations::ANNOTATION_TRANSITION.into());
/// Changes how export usage is propagated to the referenced module
static ANNOTATION_EXPORT_USAGE: LazyLock<Wtf8Atom> =
LazyLock::new(|| crate::annotations::ANNOTATION_EXPORT_USAGE.into());
/// Changes the type of the resolved module (only "json" is supported currently)
static ATTRIBUTE_MODULE_TYPE: LazyLock<Wtf8Atom> = LazyLock::new(|| atom!("type").into());
......@@ -222,6 +226,12 @@ impl ImportAnnotations {
.map(|v| v.to_string_lossy())
}
/// Whether this import forwards the importing module's export usage
pub fn export_usage_passthrough(&self) -> bool {
self.get(&ANNOTATION_EXPORT_USAGE)
.is_some_and(|value| value == "passthrough")
}
/// Returns the content on the chunking-type annotation
pub fn chunking_type(&self) -> Option<SpecifiedChunkingType> {
self.chunking_type
......@@ -1701,6 +1711,15 @@ mod tests {
})
}
/// Helper to create a string property name
fn str_key(s: &str) -> PropName {
PropName::Str(Str {
span: DUMMY_SP,
value: Atom::from(s).into(),
raw: None,
})
}
/// Helper to create a key-value property
fn kv_prop(key: PropName, value: Box<Expr>) -> PropOrSpread {
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key, value })))
......@@ -1757,6 +1776,20 @@ mod tests {
assert!(annotations.module_type().is_some());
}
#[test]
fn test_parse_export_usage_passthrough() {
let with = ObjectLit {
span: DUMMY_SP,
props: vec![kv_prop(
str_key(crate::annotations::ANNOTATION_EXPORT_USAGE),
str_lit("passthrough"),
)],
};
let annotations = ImportAnnotations::parse(Some(&with)).unwrap();
assert!(annotations.export_usage_passthrough());
}
#[test]
fn test_parse_empty_with() {
let annotations = ImportAnnotations::parse(None);
......
......@@ -9,6 +9,9 @@ pub const ANNOTATION_CHUNKING_TYPE: &str = "turbopack-chunking-type";
/// Enables a specified transition for the annotated import
pub const ANNOTATION_TRANSITION: &str = "turbopack-transition";
/// Forwards the importing module's used exports to the referenced module
pub const ANNOTATION_EXPORT_USAGE: &str = "turbopack-export-usage";
pub fn with_clause<'a>(
entries: impl IntoIterator<Item = &'a (&'a str, &'a str)>,
) -> Box<ObjectLit> {
......
......@@ -470,6 +470,8 @@ struct EsmReferenceExtras {
module_type: Option<RcStr>,
/// The chunking-type annotation (drives `chunking_type`).
chunking_type: Option<SpecifiedChunkingType>,
/// Whether the importing module's used exports should be forwarded to the target.
export_usage_passthrough: bool,
/// A module to resolve to directly, bypassing resolution (from a matched inner asset).
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
}
......@@ -489,6 +491,7 @@ impl EsmReferenceExtras {
.and_then(|a| a.module_type())
.map(|m| RcStr::from(&*m.to_string_lossy())),
chunking_type: annotations.and_then(|a| a.chunking_type()),
export_usage_passthrough: annotations.is_some_and(|a| a.export_usage_passthrough()),
resolve_override,
};
(extras != EsmReferenceExtras::default()).then(|| Box::new(extras))
......@@ -739,8 +742,19 @@ impl ModuleReference for EsmAssetReference {
BindingUsage {
import: self.import_usage.clone(),
export: match &self.export_name {
Some(ModulePart::Export(export_name)) => ExportUsage::Named(export_name.clone()),
// Evaluation references preserve their side-effect-only semantics even when the
// corresponding import forwards export usage.
Some(ModulePart::Evaluation) => ExportUsage::Evaluation,
_ if self
.extras
.as_deref()
.is_some_and(|extras| extras.export_usage_passthrough) =>
{
ExportUsage::Passthrough {
namespace_object_may_escape: true,
}
}
Some(ModulePart::Export(export_name)) => ExportUsage::Named(export_name.clone()),
_ => ExportUsage::All,
},
}
......
......@@ -183,7 +183,8 @@ impl EcmascriptModulePartReference {
ExportUsage::Named(export) => Some(export.clone()),
ExportUsage::PartialNamespaceObject(_)
| ExportUsage::All
| ExportUsage::Evaluation => None,
| ExportUsage::Evaluation
| ExportUsage::Passthrough { .. } => None,
},
scope_hoisting_context,
)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment