Unverified Commit 8eabe35e authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Bundle Analyzer Agent Skill: Show modules in generated JS/CSS files (#99173)

## Summary

Before this PR, an agent could see a route's generated files and follow
imports to find modules relevant to that route. It could not reliably
tell **which exact modules landed in a particular JavaScript or CSS
file**. This PR adds that per-file mapping, so an agent can trace a
large generated file back to the modules it contains.

Files that cannot be mapped are marked as such rather than shown as
empty. The graph checks the module information before reporting a match.

## Verification

- The broad graph-dump converter unit suite is removed in the root and
not reintroduced here; existing e2e and producer code are unchanged. The
snapshot-selection unit suite is removed too, without replacement tests;
its targeted mocked-history/path coverage is intentionally dropped.
Neither analyzer unit suite remains; Next package no-emit types pass.
Unique removed edge-case coverage was explicitly accepted.
- Earlier stack verification included Rust analyzer tests, analyzer e2e
and a full build; these are historical results, not validation of the
new signed heads. **New-head CI is pending.**

<!-- NEXT_JS_LLM -->

<!-- fleet d7bdbc2b-b0bc-4591-99eb-dccb0fa49c73 -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 8d3606c1
......@@ -32,7 +32,11 @@ import {
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import {
AnalyzeData,
ModulesData,
assertMatchingModuleIndex,
} from '@/lib/analyze-data'
import {
analyzeDataUrl,
fetchAnalyzeData,
......@@ -245,6 +249,7 @@ function useAnalyzerModel(compare: boolean) {
if (!analyzeData) {
return { moduleDepthMap: new Map(), sourceLoadScopes: new Map() }
}
assertMatchingModuleIndex(modulesData, analyzeData, 'Current snapshot')
const activeEntries = computeActiveEntries(modulesData, analyzeData)
return {
......@@ -614,6 +619,13 @@ function ComparisonContent({
baselineAnalyzeData: AnalyzeData | null
layoutProps: ComparisonLayoutProps
}) {
if (baselineAnalyzeData) {
assertMatchingModuleIndex(
layoutProps.baselineModulesData,
baselineAnalyzeData,
'Baseline snapshot'
)
}
const baselineModuleDepthMap = baselineAnalyzeData
? computeModuleDepthMap(
layoutProps.baselineModulesData,
......
......@@ -35,6 +35,7 @@ interface EdgesDataReference {
}
interface AnalyzeDataHeader {
module_index_hash: string
sources: AnalyzeSource[]
chunk_parts: AnalyzeChunkPart[]
output_files: AnalyzeOutputFile[]
......@@ -45,6 +46,7 @@ interface AnalyzeDataHeader {
}
interface ModulesDataHeader {
module_index_hash: string
modules: AnalyzeModule[]
module_dependents: EdgesDataReference
async_module_dependents: EdgesDataReference
......@@ -92,6 +94,14 @@ export class ModulesData {
}
}
moduleIndexHash(): string {
const hash = this.modulesHeader.module_index_hash
if (typeof hash !== 'string' || !hash) {
throw new Error('Missing analyzer module-index fingerprint')
}
return hash
}
module(index: ModuleIndex): AnalyzeModule | undefined {
return this.modulesHeader.modules[index]
}
......@@ -202,6 +212,19 @@ export class ModulesData {
}
}
/** Only join a route to the module table from the same snapshot. */
export function assertMatchingModuleIndex(
modules: ModulesData,
route: AnalyzeData,
side: string
): void {
const moduleHash = modules.moduleIndexHash()
const routeHash = route.moduleIndexHash()
if (moduleHash !== routeHash) {
throw new Error(`${side}: analyzer module-index fingerprint mismatch`)
}
}
/**
* Represents route-specific analyze data
*/
......@@ -237,6 +260,14 @@ export class AnalyzeData {
// Accessor methods for header data
moduleIndexHash(): string {
const hash = this.analyzeHeader.module_index_hash
if (typeof hash !== 'string' || !hash) {
throw new Error('Missing analyzer module-index fingerprint')
}
return hash
}
source(index: SourceIndex): AnalyzeSource | undefined {
return this.analyzeHeader.sources[index]
}
......
mod membership;
use std::{borrow::Cow, io::Write};
use anyhow::Result;
use bincode::{Decode, Encode};
use byteorder::{BE, WriteBytesExt};
use either::Either;
use membership::output_chunk_modules;
use next_core::app_structure::FileSystemPathVec;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::Serialize;
......@@ -16,6 +19,7 @@ use turbo_tasks_fs::{
File, FileContent, FileSystemPath,
rope::{Rope, RopeBuilder},
};
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_analyze::split_chunk::{split_output_asset_into_parts, split_traced_file_into_parts};
use turbopack_core::{
SOURCE_URL_PROTOCOL,
......@@ -86,7 +90,7 @@ pub struct AnalyzeSource {
pub path: RcStr,
}
#[derive(Serialize)]
#[derive(Clone, Debug, PartialEq, Eq, NonLocalValue, Encode, Decode, Serialize)]
pub struct AnalyzeModule {
pub ident: RcStr,
pub path: RcStr,
......@@ -130,6 +134,69 @@ pub struct AnalyzeClientReferenceEntry {
#[turbo_tasks::value(transparent)]
pub struct AnalyzeRouteEntries(Vec<AnalyzeRouteEntry>);
/// Snapshot-scoped module order shared by both artifact writers. Never regenerate
/// indices independently from a route graph or use them across analyzer snapshots.
#[turbo_tasks::value(shared)]
pub struct AnalyzeModuleIndex {
pub modules: Vec<AnalyzeModule>,
pub by_ident: FxHashMap<RcStr, u32>,
/// Fingerprint of the exact ordered module identities serialized in modules.data.
pub module_index_hash: RcStr,
}
#[turbo_tasks::function]
pub async fn analyze_module_index(module_graph: Vc<ModuleGraph>) -> Result<Vc<AnalyzeModuleIndex>> {
let mut all_modules = FxIndexSet::default();
let graph = module_graph.await?;
graph.traverse_edges_dfs(
graph.all_entry_modules(),
&mut (),
|_, node, _| {
all_modules.insert(node);
Ok(GraphTraversalAction::Continue)
},
|_, _, _| Ok(()),
true,
)?;
let mut modules = Vec::with_capacity(all_modules.len());
let mut by_ident = FxHashMap::default();
let idents_and_paths = all_modules
.iter()
.copied()
.map(async |module| {
let ident = module.ident();
let ident_str = ident.to_string().owned().await?;
let path = ident.await?.path.to_string_ref().await?;
anyhow::Ok((ident_str, path))
})
.join()
.await;
for pair in idents_and_paths {
let (ident, path) = pair?;
if by_ident.contains_key(&ident) {
continue;
}
by_ident.insert(ident.clone(), modules.len() as u32);
modules.push(AnalyzeModule { ident, path });
}
let module_index_hash = format!(
"{:016x}",
hash_xxh3_hash64(
modules
.iter()
.map(|module| (module.ident.as_str(), module.path.as_str()))
.collect::<Vec<_>>()
)
)
.into();
Ok(AnalyzeModuleIndex {
modules,
by_ident,
module_index_hash,
}
.cell())
}
pub fn analyze_route_entry_id(
route: &str,
role: &str,
......@@ -147,11 +214,16 @@ struct EdgesDataReference {
#[derive(Serialize)]
struct AnalyzeDataHeader {
/// Supported by the agent graph-dump decoder; UI readers ignore this field.
/// The header and modules.data must use the same supported schema version.
pub schema_version: u32,
pub module_index_hash: RcStr,
pub sources: Vec<AnalyzeSource>,
pub chunk_parts: Vec<AnalyzeChunkPart>,
pub output_files: Vec<AnalyzeOutputFile>,
/// Exact indices into this snapshot's modules.data.modules, one row per output file.
pub output_file_modules: EdgesDataReference,
pub output_file_async_loaders: EdgesDataReference,
pub output_file_module_coverage: Vec<AnalyzeOutputFileCoverage>,
/// Exact endpoint roots; nested client references do not become roots.
pub route_entries: Vec<AnalyzeRouteEntry>,
/// Edges from chunks to chunk parts
......@@ -166,8 +238,9 @@ struct AnalyzeDataHeader {
#[derive(Serialize)]
struct ModulesDataHeader {
/// Supported by the agent graph-dump decoder; UI readers ignore this field.
/// The header and modules.data must use the same supported schema version.
pub schema_version: u32,
pub module_index_hash: RcStr,
pub modules: Vec<AnalyzeModule>,
/// Edges from modules to modules
pub module_dependents: EdgesDataReference,
......@@ -183,9 +256,20 @@ struct ModulesDataHeader {
pub traced_module_dependencies: EdgesDataReference,
}
#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
enum AnalyzeOutputFileCoverage {
Exact,
Unsupported,
NotAChunk,
}
struct AnalyzeOutputFileBuilder {
output_file: AnalyzeOutputFile,
chunk_part_indices: Vec<u32>,
module_indices: Vec<u32>,
async_loader_indices: Vec<u32>,
module_coverage: AnalyzeOutputFileCoverage,
}
struct AnalyzeSourceBuilder {
......@@ -209,12 +293,15 @@ struct AnalyzeDataBuilder {
source_index_map: FxHashMap<RcStr, u32>,
chunk_parts: Vec<AnalyzeChunkPart>,
output_files: Vec<AnalyzeOutputFileBuilder>,
output_file_index_map: FxHashMap<RcStr, u32>,
route_entries: Vec<AnalyzeRouteEntry>,
module_index_hash: RcStr,
}
struct ModulesDataBuilder {
modules: Vec<AnalyzeModuleBuilder>,
module_index_map: FxHashMap<RcStr, u32>,
module_index_hash: RcStr,
}
struct EdgesDataSectionBuilder {
......@@ -235,12 +322,14 @@ impl EdgesDataSectionBuilder {
}
impl AnalyzeDataBuilder {
fn new(route_entries: Vec<AnalyzeRouteEntry>) -> Self {
fn new(route_entries: Vec<AnalyzeRouteEntry>, module_index_hash: RcStr) -> Self {
Self {
module_index_hash,
sources: vec![],
source_index_map: FxHashMap::default(),
chunk_parts: vec![],
output_files: vec![],
output_file_index_map: FxHashMap::default(),
route_entries,
}
}
......@@ -270,10 +359,18 @@ impl AnalyzeDataBuilder {
}
fn add_output_file(&mut self, output_file: AnalyzeOutputFile) -> u32 {
if let Some(&index) = self.output_file_index_map.get(&output_file.filename) {
return index;
}
let i = self.output_files.len() as u32;
self.output_file_index_map
.insert(output_file.filename.clone(), i);
self.output_files.push(AnalyzeOutputFileBuilder {
output_file,
chunk_part_indices: vec![],
module_indices: vec![],
async_loader_indices: vec![],
module_coverage: AnalyzeOutputFileCoverage::NotAChunk,
});
i
}
......@@ -312,13 +409,25 @@ impl AnalyzeDataBuilder {
let output_file_chunk_parts =
EdgesData::from_iterator(self.output_files.iter().map(|of| &of.chunk_part_indices));
let output_file_modules =
EdgesData::from_iterator(self.output_files.iter().map(|of| &of.module_indices));
let output_file_async_loaders =
EdgesData::from_iterator(self.output_files.iter().map(|of| &of.async_loader_indices));
let mut binary_section = EdgesDataSectionBuilder::new();
let header = AnalyzeDataHeader {
schema_version: ANALYZE_SCHEMA_VERSION,
module_index_hash: self.module_index_hash,
sources: self.sources.into_iter().map(|s| s.source).collect(),
chunk_parts: self.chunk_parts,
output_file_module_coverage: self
.output_files
.iter()
.map(|of| of.module_coverage)
.collect(),
output_file_modules: binary_section.add_edges(&output_file_modules),
output_file_async_loaders: binary_section.add_edges(&output_file_async_loaders),
output_files: self
.output_files
.into_iter()
......@@ -343,8 +452,9 @@ impl AnalyzeDataBuilder {
}
impl ModulesDataBuilder {
fn new() -> Self {
fn new(module_index_hash: RcStr) -> Self {
Self {
module_index_hash,
modules: vec![],
module_index_map: FxHashMap::default(),
}
......@@ -420,6 +530,7 @@ impl ModulesDataBuilder {
let header = ModulesDataHeader {
schema_version: ANALYZE_SCHEMA_VERSION,
module_index_hash: self.module_index_hash,
modules: self.modules.into_iter().map(|s| s.module).collect(),
module_dependents: binary_section.add_edges(&module_dependents),
async_module_dependents: binary_section.add_edges(&async_module_dependents),
......@@ -484,6 +595,7 @@ pub async fn analyze_output_assets(
output_assets: Vc<OutputAssets>,
traced_files: Vc<FileSystemPathVec>,
route_entries: Vc<AnalyzeRouteEntries>,
module_graph: Vc<ModuleGraph>,
) -> Result<Vc<AnalyzedRoute>> {
let output_assets = all_assets_from_entries(output_assets);
let mut summary = RouteBundleSummary {
......@@ -495,9 +607,10 @@ pub async fn analyze_output_assets(
},
};
let route_entries = route_entries.await?.iter().cloned().collect();
let module_index = analyze_module_index(module_graph).await?;
let mut builder = AnalyzeDataBuilder::new(route_entries);
let mut builder =
AnalyzeDataBuilder::new(route_entries, module_index.module_index_hash.clone());
let prefix = format!("{SOURCE_URL_PROTOCOL}///");
// Process the output assets and extract chunk parts.
......@@ -531,6 +644,18 @@ pub async fn analyze_output_assets(
let output_file_index = builder.add_output_file(AnalyzeOutputFile {
filename: filename.clone(),
});
if let Either::Left(asset) = &asset {
let (indices, coverage, async_loaders) =
output_chunk_modules(*asset, &filename, &module_index).await?;
let file = &mut builder.output_files[output_file_index as usize];
file.module_indices.extend(indices);
file.module_indices.sort_unstable();
file.module_indices.dedup();
file.async_loader_indices.extend(async_loaders);
file.async_loader_indices.sort_unstable();
file.async_loader_indices.dedup();
file.module_coverage = coverage;
}
let chunk_parts = match asset {
Either::Left(asset) => split_output_asset_into_parts(*asset).await?,
Either::Right(path) => split_traced_file_into_parts(path).await?,
......@@ -601,9 +726,9 @@ pub async fn analyze_output_assets(
#[turbo_tasks::function]
pub async fn analyze_module_graphs(module_graph: Vc<ModuleGraph>) -> Result<Vc<FileContent>> {
let mut builder = ModulesDataBuilder::new();
let module_index = analyze_module_index(module_graph).await?;
let mut builder = ModulesDataBuilder::new(module_index.module_index_hash.clone());
let mut all_modules = FxIndexSet::default();
let mut all_edges = FxIndexSet::default();
let mut all_async_edges = FxIndexSet::default();
let mut all_traced_edges = FxIndexSet::default();
......@@ -614,7 +739,6 @@ pub async fn analyze_module_graphs(module_graph: Vc<ModuleGraph>) -> Result<Vc<F
module_graph.all_entry_modules(),
&mut (),
|parent, node, _| {
all_modules.insert(node);
let Some((parent_node, reference)) = parent else {
return Ok(GraphTraversalAction::Continue);
};
......@@ -658,19 +782,8 @@ pub async fn analyze_module_graphs(module_graph: Vc<ModuleGraph>) -> Result<Vc<F
Ok(Some((from_ident, to_ident)))
}
let modules = all_modules
.iter()
.copied()
.map(async |module| {
let ident = module.ident().to_string().owned().await?;
let path = module.ident().await?.path.to_string_ref().await?;
anyhow::Ok((ident, path))
})
.join()
.await;
for module in modules {
let (ident, path) = module?;
builder.ensure_module(&ident, &path);
for module in &module_index.modules {
builder.ensure_module(&module.ident, &module.path);
}
let all_edges = all_edges
......@@ -741,6 +854,7 @@ pub struct AnalyzeDataOutputAsset {
pub output_assets: ResolvedVc<OutputAssets>,
pub traced_files: ResolvedVc<FileSystemPathVec>,
pub route_entries: ResolvedVc<AnalyzeRouteEntries>,
pub module_graph: ResolvedVc<ModuleGraph>,
}
#[turbo_tasks::value_impl]
......@@ -751,12 +865,14 @@ impl AnalyzeDataOutputAsset {
output_assets: ResolvedVc<OutputAssets>,
traced_files: ResolvedVc<FileSystemPathVec>,
route_entries: ResolvedVc<AnalyzeRouteEntries>,
module_graph: ResolvedVc<ModuleGraph>,
) -> Result<Vc<Self>> {
Ok(Self {
path,
output_assets,
traced_files,
route_entries,
module_graph,
}
.cell())
}
......@@ -766,9 +882,13 @@ impl AnalyzeDataOutputAsset {
impl Asset for AnalyzeDataOutputAsset {
#[turbo_tasks::function]
fn content(&self) -> Vc<AssetContent> {
let file_content =
analyze_output_assets(*self.output_assets, *self.traced_files, *self.route_entries)
.file_content();
let file_content = analyze_output_assets(
*self.output_assets,
*self.traced_files,
*self.route_entries,
*self.module_graph,
)
.file_content();
AssetContent::file(file_content)
}
}
......
//! Enumerate emitted chunk modules against this snapshot's ordered module index.
use anyhow::{Context, Result, anyhow};
use rustc_hash::FxHashMap;
use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexSet, ResolvedVc, ValueToString, Vc};
use turbopack_browser::ecmascript::{
EcmascriptBrowserChunk, EcmascriptBrowserRuntimeChunk, EcmascriptBrowserSingleEntryChunk,
EcmascriptBrowserWorkerEntrypoint,
};
use turbopack_core::{
chunk::{Chunk, ChunkItem},
module::Module,
output::OutputAsset,
};
use turbopack_css::chunk::CssChunk;
use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule,
chunk::{EcmascriptChunk, EcmascriptChunkItemOrBatchWithAsyncInfo},
single_file_ecmascript_output::SingleFileEcmascriptOutput,
};
use turbopack_nodejs::{EcmascriptBuildNodeChunk, EcmascriptBuildNodeRuntimeChunk};
use crate::analyze::{AnalyzeModuleIndex, AnalyzeOutputFileCoverage};
async fn insert_chunk_item(
module: Vc<Box<dyn Module>>,
module_index: &AnalyzeModuleIndex,
indices: &mut FxIndexSet<u32>,
async_loaders: &mut FxIndexSet<u32>,
) -> Result<()> {
let module = module.to_resolved().await?;
let loader_target_ident =
if let Some(loader) = ResolvedVc::try_downcast_type::<AsyncLoaderModule>(module) {
Some(loader.await?.inner.ident().to_string().owned().await?)
} else {
None
};
insert_chunk_item_ident(
module.ident().to_string().owned().await?,
loader_target_ident,
&module_index.by_ident,
indices,
async_loaders,
)
}
fn insert_chunk_item_ident(
ident: RcStr,
loader_target_ident: Option<RcStr>,
by_ident: &FxHashMap<RcStr, u32>,
indices: &mut FxIndexSet<u32>,
async_loaders: &mut FxIndexSet<u32>,
) -> Result<()> {
let lookup_ident = loader_target_ident.as_ref().unwrap_or(&ident);
let &index = by_ident.get(lookup_ident).ok_or_else(|| {
if loader_target_ident.is_some() {
anyhow!(
"Async loader {ident} target {lookup_ident} is missing from the analyzer module \
index"
)
} else {
anyhow!("Chunk module {ident} is missing from the analyzer module index")
}
})?;
if loader_target_ident.is_some() {
async_loaders.insert(index);
} else {
indices.insert(index);
}
Ok(())
}
/// Get exact constituent module identities only for chunk types whose items we
/// can enumerate. Empty rows marked unsupported must not be treated as empty chunks.
pub(super) async fn output_chunk_modules(
asset: ResolvedVc<Box<dyn OutputAsset>>,
filename: &str,
module_index: &AnalyzeModuleIndex,
) -> Result<(Vec<u32>, AnalyzeOutputFileCoverage, Vec<u32>)> {
if ResolvedVc::try_downcast_type::<EcmascriptBrowserRuntimeChunk>(asset).is_some()
|| ResolvedVc::try_downcast_type::<EcmascriptBuildNodeRuntimeChunk>(asset).is_some()
|| ResolvedVc::try_downcast_type::<SingleFileEcmascriptOutput>(asset).is_some()
|| ResolvedVc::try_downcast_type::<EcmascriptBrowserSingleEntryChunk>(asset).is_some()
|| ResolvedVc::try_downcast_type::<EcmascriptBrowserWorkerEntrypoint>(asset).is_some()
{
return Ok((vec![], AnalyzeOutputFileCoverage::NotAChunk, vec![]));
}
let mut indices = FxIndexSet::default();
let mut async_loaders = FxIndexSet::default();
let mut enumerated = true;
let ecmascript_content = if let Some(browser_chunk) =
ResolvedVc::try_downcast_type::<EcmascriptBrowserChunk>(asset)
{
let chunk: ResolvedVc<Box<dyn Chunk>> = browser_chunk.chunk().to_resolved().await?;
let chunk = ResolvedVc::try_downcast_type::<EcmascriptChunk>(chunk)
.ok_or_else(|| anyhow::anyhow!("browser output did not contain an ecmascript chunk"))?;
Some(chunk.chunk_content())
} else {
ResolvedVc::try_downcast_type::<EcmascriptBuildNodeChunk>(asset)
.map(|node_chunk| node_chunk.chunk_content())
};
if let Some(content) = ecmascript_content {
let content = content.await?;
for chunk_item in &content.chunk_items {
match chunk_item {
EcmascriptChunkItemOrBatchWithAsyncInfo::ChunkItem(item) => {
insert_chunk_item(
item.chunk_item.module(),
module_index,
&mut indices,
&mut async_loaders,
)
.await
.with_context(|| format!("Analyzing output {filename}"))?;
}
EcmascriptChunkItemOrBatchWithAsyncInfo::Batch(batch) => {
for item in &batch.await?.chunk_items {
insert_chunk_item(
item.chunk_item.module(),
module_index,
&mut indices,
&mut async_loaders,
)
.await
.with_context(|| format!("Analyzing output {filename}"))?;
}
}
}
}
} else if let Some(chunk) = ResolvedVc::try_downcast_type::<CssChunk>(asset) {
let content = chunk.await?.content.await?;
for chunk_item in &content.chunk_items {
insert_chunk_item(
chunk_item.module(),
module_index,
&mut indices,
&mut async_loaders,
)
.await
.with_context(|| format!("Analyzing output {filename}"))?;
}
} else if filename.ends_with(".js") || filename.ends_with(".css") {
// Other emitted JS/CSS wrappers cannot enumerate their module members.
enumerated = false;
} else {
return Ok((vec![], AnalyzeOutputFileCoverage::NotAChunk, vec![]));
}
let coverage = if enumerated {
AnalyzeOutputFileCoverage::Exact
} else {
AnalyzeOutputFileCoverage::Unsupported
};
Ok((
indices.into_iter().collect(),
coverage,
async_loaders.into_iter().collect(),
))
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use rustc_hash::FxHashMap;
use turbo_rcstr::RcStr;
use turbo_tasks::FxIndexSet;
use crate::analyze::membership::insert_chunk_item_ident;
fn insert(ident: &str, loader_target: Option<&str>) -> Result<(Vec<u32>, Vec<u32>)> {
let by_ident = FxHashMap::from_iter([
(RcStr::from("target"), 7),
(RcStr::from("ordinary (async loader)"), 9),
]);
let mut indices = FxIndexSet::default();
let mut async_loaders = FxIndexSet::default();
insert_chunk_item_ident(
ident.into(),
loader_target.map(RcStr::from),
&by_ident,
&mut indices,
&mut async_loaders,
)?;
Ok((
indices.into_iter().collect(),
async_loaders.into_iter().collect(),
))
}
#[test]
fn confirmed_async_loader_is_not_a_member() {
let (indices, async_loaders) = insert("target (async loader)", Some("target")).unwrap();
assert!(indices.is_empty());
assert_eq!(async_loaders, [7]);
}
#[test]
fn missing_async_loader_target_is_an_error() {
let error = insert("missing (async loader)", Some("missing")).unwrap_err();
assert_eq!(
error.to_string(),
"Async loader missing (async loader) target missing is missing from the analyzer \
module index"
);
}
#[test]
fn ordinary_members_are_not_classified_by_ident_suffix() {
let (indices, async_loaders) = insert("ordinary (async loader)", None).unwrap();
assert_eq!(indices, [9]);
assert!(async_loaders.is_empty());
let error = insert("unknown (async loader)", None).unwrap_err();
assert!(
error
.to_string()
.contains("Chunk module unknown (async loader)")
);
}
}
......@@ -251,6 +251,7 @@ async fn get_analyze_data_operation(
output_assets,
traced_files,
route_entries,
*whole_app_module_graphs.await?.full,
)
.to_resolved()
.await?;
......@@ -258,9 +259,14 @@ async fn get_analyze_data_operation(
let summary = if let EndpointGroupKey::Route(route) = key {
Some(RouteSummary {
route: route.to_string(),
bundles: analyze_output_assets(output_assets, traced_files, route_entries)
.await?
.summary,
bundles: analyze_output_assets(
output_assets,
traced_files,
route_entries,
*whole_app_module_graphs.await?.full,
)
.await?
.summary,
})
} else {
None
......
......@@ -27,6 +27,7 @@
"type",
"schema_version",
"snapshot_name",
"module_index_hash",
"route_count",
"selected_routes"
],
......@@ -41,6 +42,11 @@
"minLength": 1,
"description": "Generated or provided snapshot name. Reusing an explicit name replaces its earlier capture."
},
"module_index_hash": {
"type": "string",
"minLength": 1,
"description": "Fingerprint of the ordered, snapshot-scoped modules.data indices; not proof of identical graphs or builds."
},
"route_count": {
"$ref": "#/$defs/index",
"description": "Total routes in this snapshot."
......@@ -175,13 +181,32 @@
},
"output": {
"type": "object",
"required": ["type", "route", "filename"],
"required": [
"type",
"route",
"filename",
"modules",
"async_loaders",
"coverage"
],
"properties": {
"type": { "const": "output" },
"route": { "type": "string", "description": "Owning route path." },
"filename": {
"type": "string",
"description": "Snapshot-scoped emitted path, not stable across builds or proof of a browser request."
},
"modules": {
"$ref": "#/$defs/identities",
"description": "Sorted identities of the output chunk's real members, joined to this snapshot's module index. Async loader stubs and their targets are represented separately in async_loaders. Unsupported coverage may have partial membership."
},
"async_loaders": {
"$ref": "#/$defs/identities",
"description": "Sorted target module identities of typed async loader stubs contained in this chunk. Each target is recorded only after joining the snapshot module index through the loader's inner module."
},
"coverage": {
"description": "Membership evidence: exact enumerates and joins every real chunk member and async loader target; unsupported means the output type cannot enumerate its members; not_a_chunk identifies non-chunk outputs, including runtime, precompiled polyfill and separately compiled worker outputs by concrete type. Attribution part records remain available.",
"enum": ["exact", "unsupported", "not_a_chunk"]
}
},
"additionalProperties": true,
......
......@@ -14,6 +14,7 @@ type Part = {
}
type ModuleHeader = {
schema_version: number
module_index_hash: string
modules: Module[]
module_dependencies: EdgeRef
async_module_dependencies: EdgeRef
......@@ -21,6 +22,7 @@ type ModuleHeader = {
}
type RouteHeader = {
schema_version: number
module_index_hash: string
sources: Source[]
chunk_parts: Part[]
output_files: Array<{ filename: string }>
......@@ -36,6 +38,9 @@ type RouteHeader = {
reference_kind: 'ecmascript' | 'css'
}>
}>
output_file_modules: EdgeRef
output_file_async_loaders: EdgeRef
output_file_module_coverage: Array<'exact' | 'unsupported' | 'not_a_chunk'>
}
type Data<H> = { header: H; binary: Buffer }
......@@ -183,11 +188,13 @@ function parseModules(file: string) {
field
)
}
return { modules, edges }
if (typeof header.module_index_hash !== 'string' || !header.module_index_hash)
throw new Error('Missing analyzer module-index fingerprint')
return { modules, edges, hash: header.module_index_hash }
}
function parseRoutes(file: string) {
const { header } = readData<RouteHeader>(file)
function parseRoutes(file: string, modules: ReturnType<typeof parseModules>) {
const { header, binary } = readData<RouteHeader>(file)
if (
!Array.isArray(header.sources) ||
!Array.isArray(header.output_files) ||
......@@ -208,10 +215,49 @@ function parseRoutes(file: string) {
throw new Error('Invalid analyzer part size')
}
}
if (header.module_index_hash !== modules.hash) {
throw new Error('Analyzer module-index fingerprint mismatch')
}
const membership = validateEdges(
binary,
header.output_file_modules,
outputs.length,
modules.modules.length,
'output modules'
)
const asyncLoaders = validateEdges(
binary,
header.output_file_async_loaders,
outputs.length,
modules.modules.length,
'output async loaders'
)
if (
!Array.isArray(header.output_file_module_coverage) ||
header.output_file_module_coverage.length !== outputs.length
) {
throw new Error('Missing analyzer output coverage')
}
if (
header.output_file_module_coverage.some(
(coverage) =>
coverage !== 'exact' &&
coverage !== 'unsupported' &&
coverage !== 'not_a_chunk'
)
) {
throw new Error('Invalid analyzer output coverage')
}
for (const output of outputs)
if (typeof output.filename !== 'string')
throw new Error('Invalid output filename')
return { paths, header, entries: header.route_entries ?? null }
return {
paths,
header,
entries: header.route_entries ?? null,
membership,
asyncLoaders,
}
}
function writeRecord(record: object): void {
......@@ -250,11 +296,13 @@ export function dumpAnalyzeGraph(
)
if (routeFilter !== undefined && selected.length === 0)
throw new Error(`Unknown analyzer route: ${routeFilter}`)
const { modules, edges } = parseModules(join(directory, 'modules.data'))
const moduleData = parseModules(join(directory, 'modules.data'))
const { modules, edges, hash } = moduleData
writeRecord({
type: 'meta',
schema_version: 1,
snapshot_name: snapshotName,
module_index_hash: hash,
route_count: routes.length,
selected_routes: selected.length,
})
......@@ -274,7 +322,10 @@ export function dumpAnalyzeGraph(
// Retain only the current route's data. A later validation error may leave
// partial output; callers must check the exit status before using it.
for (const route of selected) {
const { paths, header, entries } = parseRoutes(routeFile(directory, route))
const { paths, header, entries, membership, asyncLoaders } = parseRoutes(
routeFile(directory, route),
moduleData
)
const prefix = { route }
writeRecord({
type: 'route',
......@@ -287,6 +338,15 @@ export function dumpAnalyzeGraph(
type: 'output',
...prefix,
filename: header.output_files[i].filename,
modules: membership
.row(i)
.map((id) => modules[id].ident)
.sort(),
async_loaders: asyncLoaders
.row(i)
.map((id) => modules[id].ident)
.sort(),
coverage: header.output_file_module_coverage[i],
})
}
for (const part of header.chunk_parts) {
......
'use client'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
const DynamicTarget = dynamic(() => import('./dynamic-target'))
export default function ClientEntry() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(new URL('./pwa', import.meta.url))
}
}, [])
return (
<>
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
<button
onClick={async () => {
const { asyncValue } = await import('./async-target')
setCount(asyncValue)
}}
>
Load async target
</button>
<DynamicTarget />
</>
)
}
export default function DynamicTarget() {
return <p>Dynamic target</p>
}
/// <reference lib="webworker" />
declare const self: ServiceWorkerGlobalScope
self.addEventListener('install', () => {
self.skipWaiting()
})
export {}
......@@ -22,10 +22,51 @@ type RouteEntry = {
}>
}
function readAnalyzeHeader<T>(filename: string): T {
type EdgesReference = { offset: number; length: number }
type ChunkGraphHeader = {
schema_version: number
module_index_hash: string
output_files: Array<{ filename: string }>
output_file_modules: EdgesReference
output_file_async_loaders: EdgesReference
output_file_module_coverage: Array<'exact' | 'unsupported' | 'not_a_chunk'>
}
function readAnalyzeFile<T>(filename: string) {
const buffer = readFileSync(filename)
const jsonLength = buffer.readUInt32BE(0)
return JSON.parse(buffer.subarray(4, 4 + jsonLength).toString('utf8')) as T
const binaryStart = 4 + jsonLength
expect(binaryStart).toBeLessThanOrEqual(buffer.length)
return {
header: JSON.parse(buffer.subarray(4, binaryStart).toString('utf8')) as T,
binary: buffer.subarray(binaryStart),
}
}
function readAnalyzeHeader<T>(filename: string): T {
return readAnalyzeFile<T>(filename).header
}
function readRows(binary: Buffer, reference: EdgesReference): number[][] {
const { offset, length } = reference
expect(offset + length).toBeLessThanOrEqual(binary.length)
const section = binary.subarray(offset, offset + length)
const count = section.readUInt32BE(0)
const offsets = Array.from({ length: count }, (_, i) =>
section.readUInt32BE(4 + 4 * i)
)
const total = offsets.at(-1) ?? 0
expect(section.length).toBe(4 * (1 + count + total))
let start = 0
return offsets.map((end) => {
expect(end).toBeGreaterThanOrEqual(start)
const row = Array.from({ length: end - start }, (_, i) =>
section.readUInt32BE(4 * (1 + count + start + i))
)
start = end
return row
})
}
// TODO(deploy-test-completion): Re-enable this suite in deploy mode.
......@@ -200,6 +241,87 @@ describe('next analyze', () => {
])
expect(alias.exitCode).toBe(0)
expect(alias.stdout).toBe(named.stdout)
const outputRecords = records.filter(
(record) => record.type === 'output' && record.route === '/'
)
for (const output of records.filter((record) => record.type === 'output')) {
expect(output.modules).toEqual([...output.modules].sort())
expect(output.async_loaders).toEqual([...output.async_loaders].sort())
}
const clientEntries = records.filter(
(record) =>
record.type === 'module' &&
record.path.endsWith('/app/client-entry.tsx') &&
record.ident.includes('[app-client]')
)
const asyncTargets = records.filter(
(record) =>
record.type === 'module' &&
record.ident.includes('[app-client]') &&
(record.path.endsWith('/app/async-target.ts') ||
record.path.endsWith('/app/dynamic-target.tsx'))
)
expect(clientEntries.length).toBeGreaterThan(0)
expect(
asyncTargets.some((record) =>
record.path.endsWith('/app/async-target.ts')
)
).toBe(true)
expect(
asyncTargets.some(
(record) =>
record.path.endsWith('/app/dynamic-target.tsx') &&
record.ident.includes('next/dynamic entry')
)
).toBe(true)
const asyncDependencies = clientEntries.flatMap(
(record) => record.dependencies.async
)
for (const target of asyncTargets) {
// The import graph records the target, not a synthetic loader module.
if (
target.ident.includes('next/dynamic entry') ||
target.path.endsWith('/app/async-target.ts')
) {
expect(asyncDependencies).toContain(target.ident)
}
}
const importerOutputs = outputRecords.filter((record) =>
clientEntries.some((entry) => record.modules.includes(entry.ident))
)
expect(importerOutputs.length).toBeGreaterThan(0)
for (const target of asyncTargets.filter(
(target) =>
target.ident.includes('next/dynamic entry') ||
target.path.endsWith('/app/async-target.ts')
)) {
expect(
importerOutputs.some((output) =>
output.async_loaders.includes(target.ident)
)
).toBe(true)
}
for (const target of asyncTargets) {
expect(
outputRecords.some((output) => output.modules.includes(target.ident))
).toBe(true)
}
for (const output of importerOutputs) {
expect(output.coverage).toBe('exact')
// Joining a loader's target must not attribute that target to the importer.
for (const target of asyncTargets) {
expect(output.modules).not.toContain(target.ident)
}
}
expect(
outputRecords
.flatMap((record) => record.modules)
.some((ident: string) => ident.endsWith('async loader)'))
).toBe(false)
const filtered = await next.runCommand([
'analyze',
'export',
......@@ -285,6 +407,45 @@ describe('next analyze', () => {
} finally {
writeFileSync(moduleFile, originalModules)
}
const routeFile = path.join(snapshotDir, 'analyze.data')
const routeOriginal = readFileSync(routeFile)
try {
const oldHeaderLength = routeOriginal.readUInt32BE(0)
const header = JSON.parse(
routeOriginal.toString('utf8', 4, 4 + oldHeaderLength)
)
const altered = Buffer.from(
JSON.stringify({ ...header, module_index_hash: 'wrong' })
)
const length = Buffer.alloc(4)
length.writeUInt32BE(altered.length)
writeFileSync(
routeFile,
Buffer.concat([
length,
altered,
routeOriginal.subarray(4 + oldHeaderLength),
])
)
const mismatch = await next.runCommand([
'analyze',
'export',
'--snapshot',
name,
])
expect(mismatch.exitCode).not.toBe(0)
const partial = mismatch.stdout
.trim()
.split('\n')
.map((line) => JSON.parse(line))
expect(partial[0]).toMatchObject({ type: 'meta', snapshot_name: name })
expect(partial.some((record) => record.type === 'module')).toBe(true)
expect(partial.some((record) => record.route === '/')).toBe(false)
expect(mismatch.stderr).toContain('module-index fingerprint mismatch')
} finally {
writeFileSync(routeFile, routeOriginal)
}
}, 120_000)
it('replays a snapshot created by next build --analyze', async () => {
......@@ -490,6 +651,74 @@ describe('next analyze', () => {
expect(entry).not.toHaveProperty('initial')
expect(entry).not.toHaveProperty('load_scope')
}
const routeGraphs = [
'analyze.data',
'legacy/analyze.data',
'api/ping/analyze.data',
].map((route) =>
readAnalyzeFile<ChunkGraphHeader>(path.join(dataDir, route))
)
for (const { header, binary } of routeGraphs) {
const rows = readRows(binary, header.output_file_modules)
for (const [i, row] of rows.entries()) {
if (header.output_file_module_coverage[i] === 'not_a_chunk') {
expect(row).toEqual([])
}
}
}
expect(
routeGraphs.some(({ header, binary }) => {
const rows = readRows(binary, header.output_file_modules)
return header.output_files.some(
(output, i) =>
output.filename.includes('/server/chunks/') &&
output.filename.endsWith('.js') &&
header.output_file_module_coverage[i] === 'exact' &&
rows[i].length > 0
)
})
).toBe(true)
const runtimeOutputs = routeGraphs.flatMap(({ header }) =>
header.output_files.flatMap((output, i) =>
output.filename.includes('[turbopack]_runtime')
? [header.output_file_module_coverage[i]]
: []
)
)
expect(runtimeOutputs.length).toBeGreaterThan(0)
expect(
runtimeOutputs.every((coverage) => coverage === 'not_a_chunk')
).toBe(true)
const workers = routeGraphs.flatMap(({ header }) =>
header.output_files.flatMap((output, index) =>
output.filename.includes('/service-worker/')
? [header.output_file_module_coverage[index]]
: []
)
)
expect(workers.length).toBeGreaterThan(0)
expect(workers.every((coverage) => coverage === 'not_a_chunk')).toBe(
true
)
const appGraph = routeGraphs[0].header
const appRows = readRows(
routeGraphs[0].binary,
appGraph.output_file_modules
)
expect(
appRows.some((row) =>
row.some((index) => modules[index].ident.includes('client-entry'))
)
).toBe(true)
expect(appGraph.output_file_module_coverage).toContain('exact')
expect(
appRows.some(
(row, index) =>
appGraph.output_files[index].filename.endsWith('.css') &&
row.some((module) => modules[module].ident.includes('page.css'))
)
).toBe(true)
})
})
})
......
......@@ -50,9 +50,13 @@ export function validateGraphDump(output: string): void {
throw new Error(`Unknown route for graph record ${index}`)
}
if (record.type === 'output') {
outputs.add(JSON.stringify([key, record.filename]))
const outputKey = JSON.stringify([key, record.filename])
if (outputs.has(outputKey)) {
throw new Error(`Duplicate analyzer output: ${record.filename}`)
}
outputs.add(outputKey)
} else if (
(record.type === 'part' || record.type === 'unjoined') &&
record.type === 'part' &&
!outputs.has(JSON.stringify([key, record.filename]))
) {
throw new Error(`Unknown output for graph record ${index}`)
......
......@@ -24,7 +24,7 @@ use crate::BrowserChunkingContext;
#[turbo_tasks::value(shared)]
#[derive(ValueToString)]
#[value_to_string("Ecmascript Browser Runtime Chunk")]
pub(crate) struct EcmascriptBrowserRuntimeChunk {
pub struct EcmascriptBrowserRuntimeChunk {
chunking_context: ResolvedVc<BrowserChunkingContext>,
include_async_module_runtime: bool,
}
......
......@@ -27,7 +27,7 @@ use crate::{
#[turbo_tasks::value(shared)]
#[derive(ValueToString)]
#[value_to_string("Ecmascript Browser Single Entry Chunk")]
pub(crate) struct EcmascriptBrowserSingleEntryChunk {
pub struct EcmascriptBrowserSingleEntryChunk {
chunking_context: ResolvedVc<BrowserChunkingContext>,
path: FileSystemPath,
chunk: ResolvedVc<EcmascriptChunk>,
......
......@@ -6,4 +6,7 @@ pub(crate) mod worker;
pub use chunk::EcmascriptBrowserChunk;
pub use content::EcmascriptBrowserChunkContent;
pub use evaluate::{
runtime::EcmascriptBrowserRuntimeChunk, single_entry_chunk::EcmascriptBrowserSingleEntryChunk,
};
pub use worker::EcmascriptBrowserWorkerEntrypoint;
......@@ -10,7 +10,7 @@ use turbopack_core::{
source_map::{GenerateSourceMap, SourceMapAsset},
version::VersionedContent,
};
use turbopack_ecmascript::chunk::EcmascriptChunk;
use turbopack_ecmascript::chunk::{EcmascriptChunk, EcmascriptChunkContent};
use super::content::EcmascriptNodeChunkContent;
use crate::NodeJsChunkingContext;
......@@ -19,7 +19,7 @@ use crate::NodeJsChunkingContext;
#[turbo_tasks::value(shared)]
#[derive(ValueToString)]
#[value_to_string("Ecmascript Build Node Chunk")]
pub(crate) struct EcmascriptBuildNodeChunk {
pub struct EcmascriptBuildNodeChunk {
chunking_context: ResolvedVc<NodeJsChunkingContext>,
chunk: ResolvedVc<EcmascriptChunk>,
}
......@@ -39,6 +39,12 @@ impl EcmascriptBuildNodeChunk {
.cell()
}
/// Constituent chunk items and batches, before the Node.js output wrapper.
#[turbo_tasks::function]
pub fn chunk_content(&self) -> Vc<EcmascriptChunkContent> {
self.chunk.chunk_content()
}
#[turbo_tasks::function]
async fn source_map(self: Vc<Self>) -> Result<Vc<SourceMapAsset>> {
let this = self.await?;
......
......@@ -22,7 +22,7 @@ use crate::NodeJsChunkingContext;
#[turbo_tasks::value(shared)]
#[derive(ValueToString)]
#[value_to_string("Ecmascript Build Node Runtime Chunk")]
pub(crate) struct EcmascriptBuildNodeRuntimeChunk {
pub struct EcmascriptBuildNodeRuntimeChunk {
chunking_context: ResolvedVc<NodeJsChunkingContext>,
include_async_module_runtime: bool,
}
......
......@@ -6,3 +6,6 @@ pub mod ecmascript;
pub mod fs;
pub use chunking_context::{NodeJsChunkingContext, NodeJsChunkingContextBuilder};
pub use ecmascript::node::{
chunk::EcmascriptBuildNodeChunk, entry::runtime::EcmascriptBuildNodeRuntimeChunk,
};
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