Unverified Commit 66170577 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: emit/collect (#96631)

Only add this for using it for Server Actions for now
Undocumented, not API stable. But we can't really put it behind a flag,
because the next-custom-transform is going to add it

New traits:
```rust
/// A module that can collect other modules during the collect phase.
#[turbo_tasks::value_trait]
pub trait CollectingModule: Module {
    /// The namespace that this module is interesed in
    #[turbo_tasks::function]
    fn namespace(self: Vc<Self>) -> Vc<RcStr>;

    #[turbo_tasks::function]
    fn as_chunk_item(
        self: Vc<Self>,
        module_graph: Vc<ModuleGraph>,
        chunking_context: Vc<Box<dyn ChunkingContext>>,
        entry_chunk_group: Vc<Modules>,
    ) -> Vc<Box<dyn ChunkItem>>;
}

#[turbo_tasks::value_trait]
pub trait EmittedModuleReference: ModuleReference + ValueToString {
    #[turbo_tasks::function]
    fn data(self: Vc<Self>) -> Vc<CompileTimeDefineValue>;
}

```

Example:

```javascript
__turbopack_emit__('./c.js', {
  namespace: 'my-test',
  data: 'data-for-c', // optional
  exports: ['c'], // optional
  with: ... // optional, import attributes like with ESM
})

// -------------------------

const getList = __turbopack_collect__({
  namespace: 'my-test',
})
const list = getList();
```

Shortcomings in the current version (which are not a blocker for now
however):
- data-only emit not implemented
- stylegroups aren't properly implemented. emitting styles is probably
broken
- pages router is still a problem: it has two separate
ChunkGroup::Entry, so you only see what was emitted on the current
runtime, not both

Recreation of https://github.com/vercel/next.js/pull/91100
parent 30e73d2d
......@@ -50,6 +50,8 @@ export default defineConfig([
...globals.commonjs,
...globals.node,
...globals.jest,
__turbopack_emit__: true,
__turbopack_collect__: true,
},
parser: babelParser,
ecmaVersion: 2020,
......
This diff is collapsed.
import type { NextConfig } from 'next'
const config: NextConfig = {
experimental: {
turbopackModuleIds: 'named',
preloadEntriesOnStart: false,
},
}
export default config
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-api',
})
import './lib'
import { collectResult } from '../../collect-result'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export async function GET(_req) {
return Response.json(await collectResult(getList), { status: 200 })
}
'use client'
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-client-a',
})
__turbopack_emit__('../shared-app-client.js', {
namespace: 'my-test',
data: 'data-for-shared-app-client-a',
scope: 'app',
})
import './lib'
import { collectResult } from '../../../collect-result'
export const dynamic = 'force-dynamic'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export default async function page() {
const result = await collectResult(getList)
return (
<div>
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
'use client'
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-client-b',
})
__turbopack_emit__('../shared-app-client.js', {
namespace: 'my-test',
data: 'data-for-shared-app-client-b',
scope: 'app',
})
import './lib'
import { collectResult } from '../../../collect-result'
export const dynamic = 'force-dynamic'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export default async function page() {
const result = await collectResult(getList)
return (
<div>
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
__turbopack_emit__('./layout-target.js', {
namespace: 'my-test',
data: 'data-for-layout',
})
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-rsc-a',
})
import './lib'
import '../shared-app'
import '../shared-page'
import { collectResult } from '../../../collect-result'
export const dynamic = 'force-dynamic'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export default async function page() {
const result = await collectResult(getList)
return (
<div>
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-rsc-b',
})
import './lib'
import '../shared-app'
import '../shared-page'
import { collectResult } from '../../../collect-result'
export const dynamic = 'force-dynamic'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export default async function page() {
const result = await collectResult(getList)
return (
<div>
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-b',
})
import '../shared-app'
import '../shared-page'
import { collectResult } from '../../../collect-result'
export const dynamic = 'force-dynamic'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export default async function page() {
const result = await collectResult(getList)
return (
<div>
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
__turbopack_emit__('./target.js', {
namespace: 'my-test',
data: 'data-for-shared-app',
scope: 'app',
})
__turbopack_emit__('./target.js', {
namespace: 'my-test',
data: 'data-for-shared-page',
})
export async function collectResult(getList) {
const list = await Promise.all(
getList().map(async (v) => ({
id: v.id,
data: v.data,
import: (await v.import()).default,
}))
)
return {
list,
// Read after the imports above have resolved, so that anything reachable
// only through a lazily loaded chunk is installed by now.
// eslint-disable-next-line no-undef
modules: Array.from(__turbopack_modules__.keys()),
}
}
'use client'
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-pages-a',
})
__turbopack_emit__('../../shared-pages-client.js', {
namespace: 'my-test',
data: 'data-for-shared-pages-a',
scope: 'app',
})
__turbopack_emit__('./unique.js', {
namespace: 'my-test',
data: 'data-for-unique-pages-client-only',
})
__turbopack_emit__('../../shared-pages-client.js', {
namespace: 'my-test',
data: 'data-for-shared-pages-client-only',
scope: 'app',
})
export default function () {
return 'client'
}
import '../../pages-lib/a/lib'
import { collectResult } from '../../collect-result'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export async function getServerSideProps() {
return {
props: {
result: await collectResult(getList),
},
}
}
export default function Page({ result }) {
return (
<div>
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
import dynamic from 'next/dynamic'
import { collectResult } from '../../collect-result'
const Client = dynamic(() => import('../../pages-lib/client-only/lib'), {
ssr: false,
})
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export async function getServerSideProps() {
return {
props: {
result: await collectResult(getList),
},
}
}
export default function Page({ result }) {
return (
<div>
<Client />
<code id="list">{JSON.stringify(result, null, 2)}</code>
</div>
)
}
import { NextResponse } from 'next/server'
import { collectResult } from './collect-result'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
export async function proxy(request) {
if (request.nextUrl.pathname === '/proxy') {
return Response.json(await collectResult(getList), { status: 200 })
}
return NextResponse.next()
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { getList } from '../shared'
export default function Page() {
return <p>{getList().length}</p>
}
import { getList } from './shared'
export default function Page() {
return <p>{getList().length}</p>
}
export const getList = __turbopack_collect__({
namespace: 'test',
})
import { nextTestSetup } from 'e2e-utils'
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'turbopack-collect-multiple-entries',
() => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('fails when a collecting module is shared between entries', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain('Invalid use of __turbopack_collect__')
expect(cliOutput).toContain(
'must not be reachable from multiple entry chunk groups'
)
})
}
)
......@@ -4,7 +4,10 @@ use bitfield::bitfield;
use turbo_rcstr::RcStr;
use turbo_tasks::{OperationVc, ResolvedVc, trace::TraceRawVcs};
use crate::chunk::available_modules::{AvailableModules, AvailableModulesSet};
use crate::{
chunk::available_modules::{AvailableModules, AvailableModulesSet},
module::Modules,
};
bitfield! {
#[turbo_tasks::task_input]
......@@ -20,6 +23,8 @@ pub struct AvailabilityInfo {
flags: AvailabilityFlags,
/// There are modules already available.
available_modules: Option<ResolvedVc<AvailableModules>>,
/// The root ChunkGroup::Entry
entry_group: Option<ResolvedVc<Modules>>,
}
impl AvailabilityInfo {
......@@ -27,6 +32,7 @@ impl AvailabilityInfo {
Self {
flags: AvailabilityFlags::default(),
available_modules: None,
entry_group: None,
}
}
......@@ -44,11 +50,13 @@ impl AvailabilityInfo {
.to_resolved()
.await?,
),
entry_group: self.entry_group,
}
} else {
Self {
flags: self.flags,
available_modules: Some(AvailableModules::new(modules).to_resolved().await?),
entry_group: self.entry_group,
}
})
}
......@@ -59,6 +67,7 @@ impl AvailabilityInfo {
Self {
flags,
available_modules: self.available_modules,
entry_group: self.entry_group,
}
}
......@@ -66,6 +75,18 @@ impl AvailabilityInfo {
self.flags.is_in_async_module()
}
pub fn with_entry_group(self, entry_group: ResolvedVc<Modules>) -> Self {
Self {
flags: self.flags,
available_modules: self.available_modules,
entry_group: Some(entry_group),
}
}
pub fn entry_group(&self) -> Option<ResolvedVc<Modules>> {
self.entry_group
}
pub async fn ident(&self) -> Result<Option<RcStr>> {
Ok(if let Some(available_modules) = self.available_modules {
Some(available_modules.hash().await?.to_string().into())
......
use std::sync::atomic::AtomicBool;
use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use bincode::{Decode, Encode};
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument;
use turbo_rcstr::rcstr;
use turbo_tasks::{
......@@ -19,6 +19,8 @@ use crate::{
available_modules::{AvailableModuleItem, AvailableModulesSet},
chunk_item_batch::{ChunkItemBatchGroup, ChunkItemOrBatchWithAsyncModuleInfo},
},
emit_collect::CollectingModule,
module::{Module, Modules},
module_graph::{
GraphTraversalAction, ModuleGraph,
chunk_group_info::ChunkGroup,
......@@ -70,6 +72,7 @@ pub async fn make_chunk_group(
chunkable_items,
batch_groups,
async_modules,
collecting_modules,
available_modules: _,
} = &*inner;
......@@ -106,6 +109,36 @@ pub async fn make_chunk_group(
.try_join()
.await?;
chunk_items.extend(
collecting_modules
.into_iter()
.map(async |module| {
let Some(entry_chunk_group) = new_availability_info.entry_group() else {
bail!("unexpected collect module in non-entry chunk group",);
};
let chunk_item = module
.as_chunk_item(*module_graph, *chunking_context, *entry_chunk_group)
.to_resolved()
.await?;
let chunk_type = chunk_item
.into_trait_ref()
.await?
.ty()
.to_resolved()
.await?;
Ok(ChunkItemOrBatchWithAsyncModuleInfo::ChunkItem(
ChunkItemWithAsyncModuleInfo {
chunk_item,
chunk_type,
module: Some(ResolvedVc::upcast(*module)),
async_info: None,
},
))
})
.try_join()
.await?,
);
// Insert async chunk loaders for every referenced async module
let async_availability_info =
if is_nested_async_availability_enabled || !availability_info.is_in_async_module() {
......@@ -184,13 +217,28 @@ pub async fn chunk_group_content(
options: ChunkGroupContentOptions,
) -> Result<ChunkGroupContent> {
let availability_info = options.availability_info;
let entry_group: Option<ResolvedVc<Modules>> =
if let ChunkGroup::Entry(entry_modules) = &chunk_group {
Some(ResolvedVc::cell(entry_modules.clone()))
} else {
None
};
let chunk_group_content = chunk_group_content_operation(module_graph, chunk_group, options);
let available_modules = available_modules_operation(chunk_group_content);
let availability_info = availability_info.with_modules(available_modules).await?;
let availability_info = if let Some(entry_group) = entry_group {
availability_info.with_entry_group(entry_group)
} else {
availability_info
};
let inner = chunk_group_content.connect().await?;
Ok(ChunkGroupContent {
inner,
availability_info: availability_info.with_modules(available_modules).await?,
availability_info,
})
}
......@@ -220,12 +268,14 @@ async fn chunk_group_content_operation(
unsorted_items: ModuleToChunkableMap,
chunkable_items: FxIndexSet<ChunkableModuleOrBatch>,
async_modules: FxIndexSet<ResolvedVc<Box<dyn ChunkableModule>>>,
collecting_modules: FxIndexSet<ResolvedVc<Box<dyn CollectingModule>>>,
}
let mut state = TraverseState {
unsorted_items: FxHashMap::default(),
chunkable_items: FxIndexSet::default(),
async_modules: FxIndexSet::default(),
collecting_modules: FxIndexSet::default(),
};
let available_modules = match availability_info.available_modules() {
......@@ -233,15 +283,26 @@ async fn chunk_group_content_operation(
None => None,
};
let mut entries = Vec::with_capacity(chunk_group.entries_count());
for entry in chunk_group.entries() {
entries.push(module_batches_graph.get_entry_index(entry).await?);
}
let entries = chunk_group
.entries()
.map(|entry| module_batches_graph.get_entry_index(entry))
.try_join()
.await?;
let active_page_entries: Option<FxHashSet<ResolvedVc<Box<dyn Module>>>> =
if let ChunkGroup::Entry(entry_modules) = &chunk_group {
Some(entry_modules.iter().copied().collect())
} else if let Some(entry_group) = availability_info.entry_group() {
Some(entry_group.await?.iter().copied().collect())
} else {
None
};
{
let _span = tracing::trace_span!("traversal").entered();
module_batches_graph.traverse_edges_from_entries_dfs(
entries,
active_page_entries.as_ref(),
&mut state,
|parent_info, &node, state| {
if matches!(node, ModuleOrBatch::None(_)) {
......@@ -259,6 +320,14 @@ async fn chunk_group_content_operation(
return Ok(GraphTraversalAction::Exclude);
}
if let Some(collecting_module) = parent_info
.and_then(|(_, edge)| edge.module)
.and_then(ResolvedVc::try_downcast::<Box<dyn CollectingModule>>)
{
state.collecting_modules.insert(collecting_module);
return Ok(GraphTraversalAction::Continue);
}
let Some(chunkable_node) = ChunkableModuleOrBatch::from_module_or_batch(node)
else {
return Ok(GraphTraversalAction::Exclude);
......@@ -284,7 +353,9 @@ async fn chunk_group_content_operation(
};
Ok(match edge.ty {
ChunkingType::Parallel { .. } | ChunkingType::Shared { .. } => {
ChunkingType::Parallel { .. }
| ChunkingType::Shared { .. }
| ChunkingType::Collected { .. } => {
if is_available {
GraphTraversalAction::Exclude
} else if state
......@@ -327,6 +398,17 @@ async fn chunk_group_content_operation(
// handled above before the sidecast
unreachable!();
}
ChunkingType::PerEntry => {
// TODO currently not implemented
bail!(
"ChunkingType::PerEntry is currently only supported for \
CollectingModule"
);
}
ChunkingType::Emitted { .. } => {
// Already handled during module graph construction
GraphTraversalAction::Exclude
}
ChunkingType::Isolated { .. } => {
// TODO currently not implemented
GraphTraversalAction::Exclude
......@@ -422,6 +504,7 @@ async fn chunk_group_content_operation(
chunkable_items,
batch_groups,
async_modules: state.async_modules,
collecting_modules: state.collecting_modules,
available_modules,
}
.cell())
......
......@@ -54,7 +54,7 @@ pub async fn attach_async_info_to_chunkable_module(
Ok(ChunkItemWithAsyncModuleInfo {
chunk_item,
chunk_type,
module: Some(module),
module: Some(ResolvedVc::upcast(module)),
async_info,
})
}
......
......@@ -76,15 +76,13 @@ pub async fn make_production_chunks(
},
..
} => Prepared::ChunkItem(
if let Some(module_chunk_groups) =
module_chunk_groups.get(&ResolvedVc::upcast(module)).await?
{
if let Some(module_chunk_groups) = module_chunk_groups.get(&module).await? {
module_chunk_groups
} else {
// Merged modules don't have a chunk group in chunk_group_info, so
// lookup using the original module.
let original_module = merged_modules
.get_original_module(ResolvedVc::upcast(module))
.get_original_module(module)
.await?
.context("every module should have a chunk group")?;
module_chunk_groups
......
......@@ -38,6 +38,7 @@ pub use crate::chunk::{
use crate::{
asset::Asset,
chunk::{availability_info::AvailabilityInfo, available_modules::AvailableModulesSet},
emit_collect::CollectingModule,
ident::AssetIdent,
module::Module,
module_graph::{
......@@ -364,6 +365,17 @@ pub enum ChunkingType {
_ty: ChunkGroupType,
merge_tag: Option<RcStr>,
},
/// Declare an emitted module (corresponds to __turboack_emit__).
Emitted {
namespace: RcStr,
/// false = emit to current entry, true = emit to all entries
emit_to_all_entries: bool,
},
/// During the build process, edges with ChunkingType::Emitted are collected and reattached to
/// the collecting module. These should not be used manually in a reference.
Collected { namespace: RcStr },
/// Chunk this reference once per entry, like async loaders.
PerEntry,
/// Create a new chunk group in a separate context, merging references with the same tag into a
/// single chunk group. It provides available modules to the current chunk group. It's assumed
/// to be loaded before the current chunk group.
......@@ -393,6 +405,7 @@ impl Display for ChunkingType {
)
}
ChunkingType::Async => write!(f, "Async"),
ChunkingType::PerEntry => write!(f, "PerEntry"),
ChunkingType::Isolated {
_ty,
merge_tag: Some(merge_tag),
......@@ -405,6 +418,18 @@ impl Display for ChunkingType {
} => {
write!(f, "Isolated")
}
ChunkingType::Emitted {
namespace,
emit_to_all_entries,
} => {
write!(
f,
"Emitted(namespace: {namespace}, emit_to_all_entries: {emit_to_all_entries})"
)
}
ChunkingType::Collected { namespace } => {
write!(f, "Collected(namespace: {namespace})")
}
ChunkingType::Shared {
inherit_async,
merge_tag: Some(merge_tag),
......@@ -467,10 +492,21 @@ impl ChunkingType {
inherit_async: false,
},
ChunkingType::Async => ChunkingType::Async,
ChunkingType::PerEntry => ChunkingType::PerEntry,
ChunkingType::Isolated { _ty, merge_tag } => ChunkingType::Isolated {
_ty: *_ty,
merge_tag: merge_tag.clone(),
},
ChunkingType::Emitted {
namespace,
emit_to_all_entries,
} => ChunkingType::Emitted {
namespace: namespace.clone(),
emit_to_all_entries: *emit_to_all_entries,
},
ChunkingType::Collected { namespace } => ChunkingType::Collected {
namespace: namespace.clone(),
},
ChunkingType::Shared {
inherit_async: _,
merge_tag,
......@@ -483,12 +519,19 @@ impl ChunkingType {
}
}
/// The modules (soon to be chunk items) that were discovered after traversing a given chunk group.
#[turbo_tasks::value(cell = "new")]
pub struct ChunkGroupContentInner {
/// Regular chunkable modules/module batches
pub chunkable_items: Vec<ChunkableModuleOrBatch>,
/// As an optimization, we also keep track of the batch groups that were discovered.
pub batch_groups: Vec<ResolvedVc<ModuleBatchGroup>>,
/// The modules that were imported with ChunkingType::Async
#[bincode(with = "turbo_bincode::indexset")]
pub async_modules: FxIndexSet<ResolvedVc<Box<dyn ChunkableModule>>>,
/// All modules that implement CollectingModule
#[bincode(with = "turbo_bincode::indexset")]
pub collecting_modules: FxIndexSet<ResolvedVc<Box<dyn CollectingModule>>>,
pub available_modules: ResolvedVc<AvailableModulesSet>,
}
......@@ -579,7 +622,7 @@ impl AsyncModuleInfo {
pub struct ChunkItemWithAsyncModuleInfo {
pub chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
pub chunk_type: ResolvedVc<Box<dyn ChunkType>>,
pub module: Option<ResolvedVc<Box<dyn ChunkableModule>>>,
pub module: Option<ResolvedVc<Box<dyn Module>>>,
pub async_info: Option<ResolvedVc<AsyncModuleInfo>>,
}
......
use std::fmt::Display;
use anyhow::Result;
use bincode::{Decode, Encode};
use indexmap::Equivalent;
......@@ -105,7 +107,8 @@ macro_rules! free_var_references {
// TODO: replace with just a `serde_json::Value`
// https://linear.app/vercel/issue/WEB-1641/compiletimedefinevalue-should-just-use-serde-jsonvalue
#[derive(Debug, Clone, TraceRawVcs, NonLocalValue, Encode, Decode, PartialEq, Eq, Hash)]
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone, Hash)]
pub enum CompileTimeDefineValue {
Null,
Bool(bool),
......@@ -166,6 +169,59 @@ impl From<serde_json::Value> for CompileTimeDefineValue {
}
}
impl CompileTimeDefineValue {
pub fn display_ecmascript(&self) -> impl Display + '_ {
CompileTimeDefineValueDisplay { value: self }
}
}
struct CompileTimeDefineValueDisplay<'a> {
value: &'a CompileTimeDefineValue,
}
impl Display for CompileTimeDefineValueDisplay<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.value {
CompileTimeDefineValue::Null => write!(f, "null"),
CompileTimeDefineValue::Bool(false) => write!(f, "false"),
CompileTimeDefineValue::Bool(true) => write!(f, "true"),
CompileTimeDefineValue::Number(v) => write!(f, "{}", serde_json::to_string(v).unwrap()),
CompileTimeDefineValue::String(v) => write!(f, "{}", serde_json::to_string(v).unwrap()),
CompileTimeDefineValue::BigInt(b) => write!(f, "{}n", b),
CompileTimeDefineValue::Array(a) => {
write!(f, "[")?;
for (i, v) in a.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", v.display_ecmascript())?;
}
write!(f, "]")?;
Ok(())
}
CompileTimeDefineValue::Object(o) => {
write!(f, "{{")?;
for (i, (k, v)) in o.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(
f,
"{}: {}",
serde_json::to_string(k).unwrap(),
v.display_ecmascript()
)?;
}
write!(f, "}}")?;
Ok(())
}
CompileTimeDefineValue::Undefined => write!(f, "undefined"),
CompileTimeDefineValue::Evaluate(e) => write!(f, "{}", e),
CompileTimeDefineValue::Regex(regex, flags) => write!(f, "/{}/{}", regex, flags),
}
}
}
#[turbo_tasks::value]
#[derive(Debug, Clone, PartialOrd, Ord)]
pub enum DefinableNameSegment {
......@@ -532,8 +588,8 @@ mod test {
use turbo_tasks::FxIndexMap;
use crate::compile_time_info::{
DefinableNameSegment, DefinableNameSegmentRef, DefinableNameSegmentRefs, FreeVarReference,
FreeVarReferences,
CompileTimeDefineValue, DefinableNameSegment, DefinableNameSegmentRef,
DefinableNameSegmentRefs, FreeVarReference, FreeVarReferences,
};
fn hash_value<T: Hash>(value: &T) -> u64 {
......@@ -791,4 +847,69 @@ mod test {
"FxHashSet<RcStr> lookup with &str should return false for nonexistent keys"
);
}
#[test]
fn compile_time_define_value_display_ecmascript() {
fn t(v: CompileTimeDefineValue) -> String {
v.display_ecmascript().to_string()
}
use serde_json::Number;
assert_eq!(t(CompileTimeDefineValue::Null), "null");
assert_eq!(t(CompileTimeDefineValue::Bool(false)), "false");
assert_eq!(t(CompileTimeDefineValue::Bool(true)), "true");
assert_eq!(
t(CompileTimeDefineValue::Number(
Number::from_f64(42.1).unwrap()
)),
"42.1"
);
assert_eq!(
t(CompileTimeDefineValue::String(rcstr!(r#"a"b"#))),
r#""a\"b""#
);
assert_eq!(
t(CompileTimeDefineValue::String(rcstr!(r#"a'b"#))),
r#""a'b""#
);
assert_eq!(
t(CompileTimeDefineValue::BigInt(Box::new(42.into()))),
"42n"
);
assert_eq!(t(CompileTimeDefineValue::Undefined), "undefined");
assert_eq!(
t(CompileTimeDefineValue::Evaluate(rcstr!("someExpression"))),
"someExpression"
);
assert_eq!(
t(CompileTimeDefineValue::Regex(
rcstr!("pattern"),
rcstr!("flags")
)),
"/pattern/flags"
);
assert_eq!(
t(CompileTimeDefineValue::Array(vec![
CompileTimeDefineValue::Bool(true),
CompileTimeDefineValue::Number(Number::from(42)),
CompileTimeDefineValue::String(rcstr!(r#"a"b"#)),
])),
r#"[true, 42, "a\"b"]"#
);
assert_eq!(
t(CompileTimeDefineValue::Object(vec![
(rcstr!("foo"), CompileTimeDefineValue::Bool(true)),
(
rcstr!("bar"),
CompileTimeDefineValue::Number(Number::from(42))
),
(
rcstr!(r#"a"b"#),
CompileTimeDefineValue::String(rcstr!(r#"c"d"#),)
),
])),
r#"{"foo": true, "bar": 42, "a\"b": "c\"d"}"#
);
}
}
use turbo_rcstr::RcStr;
use turbo_tasks::{ValueToString, Vc};
use crate::{
chunk::{ChunkItem, ChunkingContext},
compile_time_info::CompileTimeDefineValue,
module::{Module, Modules},
module_graph::ModuleGraph,
reference::ModuleReference,
};
/// A module that can collect other emitted modules during the collect phase.
#[turbo_tasks::value_trait]
pub trait CollectingModule: Module {
/// The namespace that this module is interested in
#[turbo_tasks::function]
fn namespace(self: Vc<Self>) -> Vc<RcStr>;
#[turbo_tasks::function]
fn as_chunk_item(
self: Vc<Self>,
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
entry_chunk_group: Vc<Modules>,
) -> Vc<Box<dyn ChunkItem>>;
}
#[turbo_tasks::value_trait]
pub trait EmittedModuleReference: ModuleReference + ValueToString {
#[turbo_tasks::function]
fn data(self: Vc<Self>) -> Vc<CompileTimeDefineValue>;
}
......@@ -41,6 +41,18 @@ fn traced_reference_ty() -> RcStr {
rcstr!("traced reference")
}
fn per_entry_reference_ty() -> RcStr {
rcstr!("per entry reference")
}
fn emitted_reference_ty() -> RcStr {
rcstr!("emitted reference")
}
fn collected_reference_ty() -> RcStr {
rcstr!("collected reference")
}
#[turbo_tasks::function]
pub async fn content_to_details(content: Vc<AssetContent>) -> Result<Vc<RcStr>> {
Ok(match &*content.await? {
......@@ -80,6 +92,9 @@ pub async fn children_from_module_references(
Some(ChunkingType::Isolated { .. }) => isolated_reference_ty(),
Some(ChunkingType::Shared { .. }) => shared_reference_ty(),
Some(ChunkingType::Traced { .. }) => traced_reference_ty(),
Some(ChunkingType::Emitted { .. }) => emitted_reference_ty(),
Some(ChunkingType::Collected { .. }) => collected_reference_ty(),
Some(ChunkingType::PerEntry) => per_entry_reference_ty(),
};
for &module in reference
......
......@@ -16,6 +16,7 @@ pub mod condition;
pub mod context;
pub mod data_uri_source;
pub mod debug_id;
pub mod emit_collect;
pub mod environment;
pub mod file_source;
pub mod generated_code_source;
......
......@@ -150,7 +150,7 @@ pub async fn compute_binding_usage_info(
let visit_count = graph_ref.traverse_edges_fixed_point_with_priority(
entries.map(|m| (m, 0)),
&mut (),
|parent, target, _| {
|parent, target, _, _| {
// Entries are always used
let Some((parent, ref_data, edge)) = parent else {
used_exports.insert(target, ModuleExportUsageInfo::All);
......
......@@ -248,6 +248,8 @@ pub enum ChunkGroup {
merge_tag: RcStr,
entries: Vec<ResolvedVc<Box<dyn Module>>>,
},
/// a module with an incoming collected edge
Collected(ResolvedVc<Box<dyn Module>>),
}
impl ChunkGroup {
......@@ -266,9 +268,10 @@ impl ChunkGroup {
/// unspecified.
pub fn entries(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + Clone + '_ {
match self {
ChunkGroup::Async(e) | ChunkGroup::Isolated(e) | ChunkGroup::Shared(e) => {
Either::Left(std::iter::once(*e))
}
ChunkGroup::Async(e)
| ChunkGroup::Isolated(e)
| ChunkGroup::Shared(e)
| ChunkGroup::Collected(e) => Either::Left(std::iter::once(*e)),
ChunkGroup::Entry(entries)
| ChunkGroup::IsolatedMerged { entries, .. }
| ChunkGroup::SharedMultiple(entries)
......@@ -278,7 +281,10 @@ impl ChunkGroup {
pub fn entries_count(&self) -> usize {
match self {
ChunkGroup::Async(_) | ChunkGroup::Isolated(_) | ChunkGroup::Shared(_) => 1,
ChunkGroup::Async(_)
| ChunkGroup::Isolated(_)
| ChunkGroup::Shared(_)
| ChunkGroup::Collected(_) => 1,
ChunkGroup::Entry(entries)
| ChunkGroup::IsolatedMerged { entries, .. }
| ChunkGroup::SharedMultiple(entries)
......@@ -299,6 +305,9 @@ impl ChunkGroup {
ChunkGroup::Async(entry) => turbofmt!("ChunkGroup::Async({:?})", entry.ident())
.await?
.to_string(),
ChunkGroup::Collected(entry) => turbofmt!("ChunkGroup::Collected({:?})", entry.ident())
.await?
.to_string(),
ChunkGroup::Isolated(entry) => turbofmt!("ChunkGroup::Isolated({:?})", entry.ident())
.await?
.to_string(),
......@@ -367,6 +376,8 @@ pub enum ChunkGroupKey {
parent: ChunkGroupId,
merge_tag: RcStr,
},
/// a module with an incoming collected edge
Collected(ResolvedVc<Box<dyn Module>>),
}
impl ChunkGroupKey {
......@@ -386,6 +397,9 @@ impl ChunkGroupKey {
ChunkGroupKey::Async(module) => {
turbofmt!("Async({:?})", module.ident()).await?.to_string()
}
ChunkGroupKey::Collected(module) => turbofmt!("Collected({:?})", module.ident())
.await?
.to_string(),
ChunkGroupKey::Isolated(module) => turbofmt!("Isolated({:?})", module.ident())
.await?
.to_string(),
......@@ -435,15 +449,16 @@ impl Deref for ChunkGroupId {
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct TraversalPriority {
depth: usize,
chunk_group_len: u64,
pub(crate) struct TraversalPriority {
pub depth: usize,
pub chunk_group_len: u64,
}
impl PartialOrd for TraversalPriority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
// TODO automatically derive this using Reverse<_>
impl Ord for TraversalPriority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// BinaryHeap prioritizes high values
......@@ -487,7 +502,8 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
// use all entries from all graphs
let entries = graph.all_chunk_group_entries().collect::<Vec<_>>();
// First, compute the depth for each module in the graph
// First, compute the depth for each module in the graph and initialize
// `module_chunk_groups` with empty bitmaps.
let module_depth: FxHashMap<ResolvedVc<Box<dyn Module>>, usize> = {
let mut module_depth =
FxHashMap::with_capacity_and_hasher(module_count, Default::default());
......@@ -590,6 +606,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
&mut module_chunk_groups,
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, _)>,
node: ResolvedVc<Box<dyn Module>>,
_,
module_chunk_groups: &mut FxHashMap<
ResolvedVc<Box<dyn Module>>,
RoaringBitmapWrapper,
......@@ -651,6 +668,28 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
// Traced modules are not placed in chunk groups
return Ok(GraphTraversalAction::Skip);
}
ChunkingType::Emitted {
namespace: _,
emit_to_all_entries: _,
} => {
// TODO ideally this would get the chunk group bitset of the parent
// ChunkGroup::Entry
ChunkGroupInheritance::ChunkGroup(Either::Left(std::iter::once(
ChunkGroupKey::Collected(node),
)))
}
ChunkingType::Collected { .. } => {
// These only exist in the module_batches graph.
unreachable!();
}
ChunkingType::PerEntry => {
// A collecting module belongs wherever its importer belongs. The
// per-entry behavior is carried by the `chunk_group` argument of
// `CollectingModule::as_chunk_item`, not by chunk group membership.
// This matches `collect.rs`, which inherits the parent's entry
// membership across this edge.
ChunkGroupInheritance::Inherit(parent)
}
}
} else {
ChunkGroupInheritance::ChunkGroup(Either::Left(std::iter::once(
......@@ -893,6 +932,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
.map(|(k, merged_entries)| match k {
ChunkGroupKey::Entry(entries) => ChunkGroup::Entry(entries),
ChunkGroupKey::Async(module) => ChunkGroup::Async(module),
ChunkGroupKey::Collected(module) => ChunkGroup::Collected(module),
ChunkGroupKey::Isolated(module) => ChunkGroup::Isolated(module),
ChunkGroupKey::IsolatedMerged { parent, merge_tag } => {
ChunkGroup::IsolatedMerged {
......
This diff is collapsed.
......@@ -171,6 +171,7 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
&mut (),
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, _)>,
node: ResolvedVc<Box<dyn Module>>,
_,
_|
-> Result<GraphTraversalAction> {
// On the down traversal, establish which edges are mergeable and set the list
......
......@@ -33,6 +33,7 @@ use crate::{
async_module_info::{AsyncModulesInfo, compute_async_module_info},
binding_usage_info::BindingUsageInfo,
chunk_group_info::{ChunkGroupEntry, ChunkGroupInfo, compute_chunk_group_info},
collect::{CollectedModules, collect_graph},
merged_modules::{MergedModuleInfo, compute_merged_modules},
module_batches::{ModuleBatchesGraph, compute_module_batches},
style_groups::{StyleGroups, StyleGroupsAlgorithm, StyleGroupsConfig},
......@@ -50,6 +51,7 @@ use crate::{
pub mod async_module_info;
pub mod binding_usage_info;
pub mod chunk_group_info;
pub mod collect;
pub mod merged_modules;
pub mod module_batch;
pub(crate) mod module_batches;
......@@ -322,6 +324,8 @@ pub struct SingleModuleGraph {
PartialEq,
ValueDebugFormat,
NonLocalValue,
Encode,
Decode,
)]
pub struct RefData {
pub chunking_type: ChunkingType,
......@@ -791,6 +795,7 @@ impl ModuleGraph {
let graph = Self::from_graphs_inner(graphs, binding_usage)
.read_strongly_consistent()
.await?;
Ok(ReadRef::cell(graph))
}
......@@ -816,6 +821,11 @@ impl ModuleGraph {
.cell())
}
#[turbo_tasks::function]
pub async fn collected_modules(self: Vc<Self>) -> Result<Vc<CollectedModules>> {
collect_graph(self).await
}
#[turbo_tasks::function]
pub async fn chunk_group_info(self: Vc<Self>) -> Result<Vc<ChunkGroupInfo>> {
compute_chunk_group_info(&*self.await?).await
......@@ -1469,13 +1479,14 @@ impl ModuleGraphSnapshot {
///
/// Returns the number of node visits (i.e. higher than the node count if there are
/// retraversals).
pub fn traverse_edges_fixed_point_with_priority<S, P: Ord>(
&self,
pub fn traverse_edges_fixed_point_with_priority<'graph, S, P: Ord>(
&'graph self,
entries: impl IntoIterator<Item = (ResolvedVc<Box<dyn Module>>, P)>,
state: &mut S,
mut visit: impl FnMut(
Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, GraphEdgeIndex)>,
Option<(ResolvedVc<Box<dyn Module>>, &'graph RefData, GraphEdgeIndex)>,
ResolvedVc<Box<dyn Module>>,
GraphNodeIndex,
&mut S,
) -> Result<GraphTraversalAction>,
priority: impl Fn(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<P>,
......@@ -1530,7 +1541,12 @@ impl ModuleGraphSnapshot {
);
for entry_node in &queue {
visit(None, self.get_node(entry_node.node)?.module(), state)?;
visit(
None,
self.get_node(entry_node.node)?.module(),
entry_node.node,
state,
)?;
}
let mut visit_count = 0usize;
......@@ -1547,6 +1563,7 @@ impl ModuleGraphSnapshot {
let action = visit(
Some((node_weight.module(), self.get_edge(edge)?, edge)),
succ_weight.module(),
succ,
state,
)?;
......@@ -1930,6 +1947,19 @@ impl Visit<SingleModuleGraphBuilderNode, RefData> for SingleModuleGraphBuilder<'
let _span = span.entered();
span = tracing::info_span!("async reference");
}
ChunkingType::PerEntry => {
let _span = span.entered();
span = tracing::info_span!("per-entry reference");
}
ChunkingType::Emitted { namespace, .. } => {
let _span = span.entered();
span = tracing::info_span!("emitted reference", namespace = debug(&namespace));
}
ChunkingType::Collected { namespace, .. } => {
let _span = span.entered();
span =
tracing::info_span!("collected reference", namespace = debug(&namespace));
}
ChunkingType::Isolated { _ty: ty, merge_tag } => {
let _span = span.entered();
span = tracing::info_span!(
......@@ -2110,7 +2140,7 @@ pub mod tests {
graph.traverse_edges_fixed_point_with_priority(
entry_modules.into_iter().map(|m| (m, 0)),
&mut (),
|parent, target, _| {
|parent, target, _, _| {
visits.push((
parent.map(|(node, _, _)| module_to_name.get(&node).unwrap().clone()),
module_to_name.get(&target).unwrap().clone(),
......@@ -2167,7 +2197,7 @@ pub mod tests {
graph.traverse_edges_fixed_point_with_priority(
entry_modules.into_iter().map(|m| (m, 0)),
&mut (),
|parent, target, _| {
|parent, target, _, _| {
visits.push((
parent.map(|(node, _, _)| module_to_name.get(&node).unwrap().clone()),
module_to_name.get(&target).unwrap().clone(),
......
......@@ -373,6 +373,8 @@ async fn collect_chunk_groups(
let mut items_in_postorder = FxIndexSet::default();
batches_graph.traverse_edges_from_entries_dfs(
entries.iter().copied(),
// TODO this would be wrong with emitted CSS modules
None,
&mut (),
|parent_info, module, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
......
......@@ -90,6 +90,8 @@ async fn collect_style_modules_per_chunk_group(
let mut items_in_postorder = FxIndexSet::default();
batches_graph.traverse_edges_from_entries_dfs(
entries.iter().copied(),
// TODO this would be wrong with emitted CSS modules
None,
&mut (),
|parent_info, module, _| {
if let Some((_, ModuleBatchesGraphEdge { ty, .. })) = parent_info
......
......@@ -61,6 +61,7 @@ pub enum EcmaScriptModulesReferenceSubType {
module_type: Option<RcStr>,
},
DynamicImport,
Emit,
Custom(u8),
#[default]
Undefined,
......
......@@ -5,7 +5,7 @@ use std::{
sync::Arc,
};
use anyhow::Result;
use anyhow::{Context, Result, bail};
use bumpalo::boxed::Box as BumpBox;
use num_bigint::BigInt;
use smallvec::SmallVec;
......@@ -612,6 +612,42 @@ impl TryFrom<&ConstantValue> for CompileTimeDefineValue {
}
}
impl TryFrom<&'_ JsValue<'_>> for CompileTimeDefineValue {
type Error = anyhow::Error;
fn try_from(value: &JsValue) -> Result<Self> {
Ok(match value {
JsValue::Constant(v) => return Self::try_from(v),
JsValue::Array { items, .. } => {
let mut arr = Vec::with_capacity(items.len());
for item in items.iter() {
arr.push(Self::try_from(item)?);
}
CompileTimeDefineValue::Array(arr)
}
JsValue::Object { parts, .. } => {
let mut obj = Vec::with_capacity(parts.len());
for part in parts.iter() {
if let ObjectPart::KeyValue(key, value) = part {
obj.push((
key.as_str()
.context("JsValue object key is not a string")?
.into(),
Self::try_from(value)?,
));
} else {
bail!("JsValue object contains non-key-value part");
}
}
CompileTimeDefineValue::Object(obj)
}
_ => bail!(
"JsValue is not constant and could not be converted to CompileTimeDefineValue"
),
})
}
}
impl<'a> JsValue<'a> {
/// Build a [`JsValue`] from a [`FreeVarReference`], allocating any nested structure in `arena`.
/// (Cannot be a `TryFrom` impl because the conversion needs the arena.)
......
......@@ -216,6 +216,10 @@ pub enum WellKnownFunctionKind<'a> {
ModuleHotDecline,
/// `import.meta.glob(patterns, options?)` — Vite-compatible glob import.
ImportMetaGlob,
/// `__turbopack_emit__` — Emit data to the bundler.
TurbopackEmit,
/// `__turbopack_collect__` — Collect emitted data from the bundler.
TurbopackCollect,
}
impl WellKnownFunctionKind<'_> {
......@@ -400,6 +404,14 @@ impl WellKnownFunctionKind<'_> {
"import.meta.glob".to_string(),
"The import.meta.glob() function from Vite: https://vite.dev/guide/features.html#glob-import",
),
Self::TurbopackEmit => (
"__turbopack_emit__".to_string(),
"The __turbopack_emit__ function for emitting data to the bundler"
),
Self::TurbopackCollect => (
"__turbopack_collect__".to_string(),
"The __turbopack_collect__ function for collecting emitted data from the bundler"
)
}
}
}
......@@ -27,6 +27,7 @@ use crate::{
constant_condition::ConstantConditionCodeGen,
constant_value::ConstantValueCodeGen,
dynamic_expression::DynamicExpression,
emit_collect::CollectReferenceCodeGen,
esm::{
EsmBinding, EsmModuleItem, ImportMetaBinding, ImportMetaRef,
dynamic::EsmAsyncAssetReferenceCodeGen, module_id::EsmModuleIdAssetReferenceCodeGen,
......@@ -182,6 +183,7 @@ impl_modify!(visit_mut_program, Program);
pub enum CodeGen {
// AMD occurs very rarely and makes the enum much bigger
AmdDefineWithDependenciesCodeGen(Box<AmdDefineWithDependenciesCodeGen>),
CollectReferenceCodeGen(CollectReferenceCodeGen),
CjsRequireCacheAccess(CjsRequireCacheAccess),
ConstantConditionCodeGen(ConstantConditionCodeGen),
ConstantValueCodeGen(ConstantValueCodeGen),
......@@ -221,6 +223,7 @@ impl CodeGen {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await,
Self::CjsRequireCacheAccess(v) => v.code_generation(ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(ctx).await,
Self::CollectReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(ctx).await,
Self::DynamicExpression(v) => v.code_generation(ctx).await,
Self::EsmBinding(v) => v.code_generation(ctx, scope_hoisting_context).await,
......
use std::io::Write;
use anyhow::{Context, Result, bail};
use rustc_hash::FxHashSet;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::rope::RopeBuilder;
use turbopack_core::{
self,
chunk::{AsyncModuleInfo, ChunkItem, ChunkableModule, ChunkingContext},
context::AssetContext,
emit_collect::{CollectingModule, EmittedModuleReference},
ident::AssetIdent,
module::{Module, ModuleSideEffects, Modules},
module_graph::ModuleGraph,
reference::ModuleReferences,
source::OptionSource,
};
use crate::{
chunk::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item,
},
references::esm::{EsmExport, EsmExports, Liveness},
runtime_functions::{TURBOPACK_ESM, TURBOPACK_IMPORT},
utils::StringifyJs,
};
#[turbo_tasks::value]
pub struct EcmascriptCollectModule {
parent_module: ResolvedVc<Box<dyn Module>>,
namespace: RcStr,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
}
#[turbo_tasks::value_impl]
impl EcmascriptCollectModule {
#[turbo_tasks::function]
pub fn new(
parent_module: ResolvedVc<Box<dyn Module>>,
namespace: RcStr,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
) -> Vc<Self> {
EcmascriptCollectModule {
parent_module,
namespace,
asset_context,
}
.cell()
}
}
#[turbo_tasks::value_impl]
impl Module for EcmascriptCollectModule {
#[turbo_tasks::function]
async fn ident(&self) -> Result<Vc<AssetIdent>> {
Ok(self
.parent_module
.ident()
.owned()
.await?
.with_modifier(rcstr!("collect"))
.with_modifier(self.namespace.clone())
.with_layer(self.asset_context.into_trait_ref().await?.layer())
.into_vc())
}
#[turbo_tasks::function]
fn source(&self) -> Vc<OptionSource> {
Vc::cell(None)
}
#[turbo_tasks::function]
fn references(&self) -> Vc<ModuleReferences> {
ModuleReferences::empty()
}
#[turbo_tasks::function]
fn side_effects(self: Vc<Self>) -> Vc<ModuleSideEffects> {
ModuleSideEffects::ModuleEvaluationIsSideEffectFree.cell()
}
}
#[turbo_tasks::value_impl]
impl CollectingModule for EcmascriptCollectModule {
#[turbo_tasks::function]
fn namespace(&self) -> Vc<RcStr> {
Vc::cell(self.namespace.clone())
}
#[turbo_tasks::function]
fn as_chunk_item(
self: ResolvedVc<Self>,
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
entry_chunk_group: ResolvedVc<Modules>,
) -> Vc<Box<dyn ChunkItem>> {
EcmascriptCollectModuleWithChunkGroup {
module: self,
entry_chunk_group,
}
.cell()
.as_chunk_item(module_graph, chunking_context)
}
}
#[turbo_tasks::value_impl]
impl ChunkableModule for EcmascriptCollectModule {
#[turbo_tasks::function]
fn as_chunk_item(
self: Vc<Self>,
_module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<Box<dyn ChunkItem>>> {
bail!("shouldn't be called, but needed for chunkable.chunk_item_id");
}
}
#[turbo_tasks::value]
struct EcmascriptCollectModuleWithChunkGroup {
module: ResolvedVc<EcmascriptCollectModule>,
entry_chunk_group: ResolvedVc<Modules>,
}
#[turbo_tasks::value_impl]
impl Module for EcmascriptCollectModuleWithChunkGroup {
#[turbo_tasks::function]
fn ident(&self) -> Vc<AssetIdent> {
self.module.ident()
}
#[turbo_tasks::function]
fn source(&self) -> Vc<OptionSource> {
self.module.source()
}
#[turbo_tasks::function]
fn references(&self) -> Vc<ModuleReferences> {
self.module.references()
}
#[turbo_tasks::function]
fn side_effects(&self) -> Vc<ModuleSideEffects> {
self.module.side_effects()
}
}
#[turbo_tasks::value_impl]
impl ChunkableModule for EcmascriptCollectModuleWithChunkGroup {
#[turbo_tasks::function]
fn as_chunk_item(
self: ResolvedVc<Self>,
module_graph: ResolvedVc<ModuleGraph>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
) -> Vc<Box<dyn ChunkItem>> {
ecmascript_chunk_item(ResolvedVc::upcast(self), module_graph, chunking_context)
}
}
#[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup {
#[turbo_tasks::function]
fn get_exports(&self) -> Vc<EcmascriptExports> {
EcmascriptExports::EsmExports(
EsmExports {
exports: [(
"getList".into(),
EsmExport::LocalBinding(rcstr!("getList"), Liveness::Constant),
)]
.into(),
star_exports: vec![],
}
.resolved_cell(),
)
.cell()
}
#[turbo_tasks::function]
async fn chunk_item_content_ident(
self: Vc<Self>,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
_module_graph: Vc<ModuleGraph>,
) -> Result<Vc<AssetIdent>> {
Ok(self
.ident()
.owned()
.await?
.with_modifier(
format!(
"from {:?}",
self.await?
.entry_chunk_group
.await?
.iter()
.map(|m| m.ident_string())
.try_join()
.await?
)
.into(),
)
.into_vc())
}
#[turbo_tasks::function]
async fn chunk_item_content(
&self,
chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>,
_async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> {
let chunk_item_id_strategy = chunking_context.chunk_item_id_strategy().await?;
let entries = self
.entry_chunk_group
.await?
.into_iter()
.collect::<FxHashSet<_>>();
let collected_modules = module_graph.collected_modules();
let items = collected_modules
.get(&ResolvedVc::upcast(self.module))
.await?;
let items = items
.iter()
.flat_map(|v| v.iter())
.filter_map(|(entry_modules, references)| {
if entry_modules.iter().any(|m| entries.contains(m)) {
Some(references.iter())
} else {
None
}
})
.flatten()
.map(async |(data, module)| {
Ok((
chunk_item_id_strategy.get_id_from_module(**module).await?,
ResolvedVc::try_sidecast::<Box<dyn EmittedModuleReference>>(data.reference)
.context("Expected collected reference to be a EmittedModuleReference")?
.data()
.await?,
))
})
.try_join()
.await?
.into_iter()
.collect::<Vec<_>>();
let mut code = RopeBuilder::default();
code += "const data = ([\n";
for (id, data) in items {
writeln!(
code,
"{{id: {}, data: {}, import: () => {TURBOPACK_IMPORT}({})}},",
StringifyJs(&id),
data.display_ecmascript(),
StringifyJs(&id),
)?;
}
code += "]);";
code += "function getList() { return data; }";
writeln!(
code,
"{TURBOPACK_ESM}([
'getList', ()=>getList
]);"
)?;
Ok(EcmascriptChunkItemContent {
inner_code: code.build(),
..Default::default()
}
.cell())
}
}
......@@ -21,5 +21,7 @@ pub mod failed_to_analyze {
pub const MODULE_HOT_ACCEPT: &str = "TP1204";
pub const MODULE_HOT_DECLINE: &str = "TP1205";
pub const CHUNKING_TYPE: &str = "TP1206";
pub const TURBOPACK_EMIT: &str = "TP1207";
pub const TURBOPACK_COLLECT: &str = "TP1208";
}
}
......@@ -14,6 +14,7 @@ pub mod bytes_source_transform;
pub mod chunk;
pub mod chunk_list;
pub mod code_gen;
mod collect_module;
mod directive;
pub mod embed_js;
mod errors;
......
use anyhow::{Result, bail};
use bincode::{Decode, Encode};
use swc_core::{
ecma::ast::{Expr, Invalid},
quote,
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
};
use turbopack_core::{
chunk::{ChunkingContext, ChunkingType},
compile_time_info::CompileTimeDefineValue,
emit_collect::EmittedModuleReference,
issue::IssueSource,
module::Module,
reference::ModuleReference,
reference_type::EcmaScriptModulesReferenceSubType,
resolve::{
BindingUsage, ExportUsage, ModuleResolveResult, ResolveErrorMode,
options::ResolveOptions,
origin::{ResolveOrigin, ResolveOriginExt},
parse::Request,
},
};
use turbopack_resolve::ecmascript::esm_resolve;
use crate::{
analyzer::imports::ImportAnnotations,
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
collect_module::EcmascriptCollectModule,
create_visitor,
references::{
AstPath,
pattern_mapping::{PatternMapping, ResolveType},
removal::RemovalCodeGen,
},
utils::AstPathRange,
};
#[turbo_tasks::value]
#[derive(Hash, Debug, ValueToString)]
#[value_to_string("emit {request} {namespace}")]
pub struct EmitReference {
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: ResolvedVc<Request>,
annotations: ImportAnnotations,
issue_source: IssueSource,
error_mode: ResolveErrorMode,
export_usage: ExportUsage,
namespace: RcStr,
data: Option<CompileTimeDefineValue>,
emit_to_all_entries: bool,
}
impl EmitReference {
pub fn new(
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: ResolvedVc<Request>,
issue_source: IssueSource,
annotations: ImportAnnotations,
error_mode: ResolveErrorMode,
export_usage: ExportUsage,
namespace: RcStr,
data: Option<CompileTimeDefineValue>,
emit_to_all_entries: bool,
) -> Self {
EmitReference {
origin,
request,
issue_source,
annotations,
error_mode,
export_usage,
namespace,
data,
emit_to_all_entries,
}
}
}
#[turbo_tasks::value_impl]
impl ModuleReference for EmitReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let origin = if let Some(transition) = self.annotations.transition() {
self.origin
.with_transition(transition.into())
.await?
.to_resolved()
.await?
} else {
self.origin
};
if self.annotations.turbopack_loader().is_some()
|| self.annotations.turbopack_rename_as().is_some()
|| self.annotations.turbopack_module_type().is_some()
{
// TODO implement
bail!(
"turbopack_loader, turbopack_rename_as, and turbopack_module_type annotations are \
not yet supported for emit references"
);
}
esm_resolve(
*origin,
*self.request,
EcmaScriptModulesReferenceSubType::Emit,
self.error_mode,
Some(self.issue_source),
)
.await
}
fn chunking_type(&self) -> Option<ChunkingType> {
Some(ChunkingType::Emitted {
namespace: self.namespace.clone(),
emit_to_all_entries: self.emit_to_all_entries,
})
}
fn binding_usage(&self) -> BindingUsage {
BindingUsage {
import: Default::default(),
export: self.export_usage.clone(),
}
}
}
#[turbo_tasks::value_impl]
impl EmittedModuleReference for EmitReference {
#[turbo_tasks::function]
fn data(&self) -> Vc<CompileTimeDefineValue> {
self.data
.clone()
.unwrap_or(CompileTimeDefineValue::Undefined)
.cell()
}
}
impl IntoCodeGenReference for EmitReference {
fn into_code_gen_reference(
self,
mut path: AstPath,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell();
path.0.pop();
(
ResolvedVc::upcast(reference),
CodeGen::RemovalCodeGen(RemovalCodeGen::new(
rcstr!("TURBOPACK collect"),
AstPathRange::Exact(path.0),
)),
)
}
}
#[turbo_tasks::value]
#[derive(Hash, Debug, ValueToString)]
#[value_to_string("collect {namespace}")]
pub struct CollectReference {
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
parent_module: ResolvedVc<Box<dyn Module>>,
namespace: RcStr,
}
impl CollectReference {
pub fn new(
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
parent_module: ResolvedVc<Box<dyn Module>>,
namespace: RcStr,
) -> Self {
CollectReference {
origin,
parent_module,
namespace,
}
}
}
fn collect_request() -> Vc<Request> {
Request::parse_string(rcstr!("data:text/javascript,"))
}
#[turbo_tasks::function]
async fn with_data_uri(options: Vc<ResolveOptions>) -> Result<Vc<ResolveOptions>> {
let mut options: ResolveOptions = options.owned().await?;
options.parse_data_uris = true;
Ok(options.cell())
}
#[turbo_tasks::value_impl]
impl ModuleReference for CollectReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let origin = self.origin.into_trait_ref().await?;
// TODO eventually, you might want to be able to use multiple different collect modules here
Ok(*ModuleResolveResult::module(ResolvedVc::upcast(
EcmascriptCollectModule::new(
*self.parent_module,
self.namespace.clone(),
*origin.asset_context(),
)
.to_resolved()
.await?,
)))
}
fn chunking_type(&self) -> Option<ChunkingType> {
Some(ChunkingType::PerEntry)
}
}
impl IntoCodeGenReference for CollectReference {
fn into_code_gen_reference(
self,
mut path: AstPath,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell();
path.0.pop();
(
ResolvedVc::upcast(reference),
CodeGen::CollectReferenceCodeGen(CollectReferenceCodeGen { reference, path }),
)
}
}
#[derive(
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)]
pub struct CollectReferenceCodeGen {
reference: ResolvedVc<CollectReference>,
path: AstPath,
}
impl CollectReferenceCodeGen {
pub async fn code_generation(
&self,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let reference = self.reference.await?;
let pm = PatternMapping::resolve_request(
collect_request(),
*reference.origin,
chunking_context,
self.reference.resolve_reference(),
ResolveType::ChunkItem,
Some(Vc::upcast(*self.reference)),
)
.await?;
let mut visitors = Vec::new();
visitors.push(create_visitor!(
self.path,
visit_mut_expr,
|expr: &mut Expr| {
*expr = quote!(
"$v.getList" as Expr,
v: Expr = pm.create_require(Expr::Invalid(Invalid::default()))
);
}
));
Ok(CodeGeneration::visitors(visitors))
}
}
......@@ -29,7 +29,7 @@ use turbopack_core::{
};
use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule,
chunk::EcmascriptChunk,
chunk::{EcmascriptChunk, EcmascriptChunkPlaceable},
manifest::{chunk_asset::ManifestAsyncModule, loader_module::ManifestLoaderModule},
};
use turbopack_ecmascript_runtime::RuntimeType;
......@@ -641,16 +641,24 @@ impl ChunkingContext for NodeJsChunkingContext {
.await?;
other_chunks.extend(extra_chunks.iter().copied());
let Some(module) = ResolvedVc::try_sidecast(chunk_group.entries().last().unwrap())
let module = chunk_group.entries().last().unwrap();
let Some(module) =
ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(module)
else {
bail!("module must be placeable in an ecmascript chunk");
bail!("last entry must be EcmascriptChunkPlaceable {:?}", module);
};
let evaluatable_assets = chunk_group
.entries()
.map(|entry| {
ResolvedVc::try_sidecast::<Box<dyn EvaluatableAsset>>(entry)
.context("entry_chunk_group entries must be evaluatable")
ResolvedVc::try_sidecast::<Box<dyn EvaluatableAsset>>(entry).with_context(
|| {
format!(
"entry_chunk_group entries must be EvaluatableAssets {:?}",
entry
)
},
)
})
.collect::<Result<Vec<_>>>()?;
......
......@@ -276,6 +276,8 @@ struct TestOptions {
remove_unused_exports: bool,
#[serde(default = "default_true")]
scope_hoisting: bool,
#[serde(default = "default_true")]
infer_module_side_effects: bool,
#[serde(default)]
cjs_tree_shaking: bool,
#[serde(default = "default_true")]
......@@ -307,6 +309,7 @@ impl Default for TestOptions {
cjs_tree_shaking: false,
cjs_scope_hoisting: false,
cross_module_constants: true,
infer_module_side_effects: default_true(),
minify: false,
production_chunking: false,
side_effect_free_packages: Vec::new(),
......@@ -469,10 +472,10 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
enable_import_as_bytes: true,
import_externals: true,
enable_exports_info_inlining: true,
infer_module_side_effects: true,
cjs_tree_shaking: options.cjs_tree_shaking,
cjs_scope_hoisting: options.cjs_scope_hoisting,
cross_module_constants: options.cross_module_constants,
infer_module_side_effects: options.infer_module_side_effects,
..Default::default()
},
environment: Some(env),
......
__turbopack_emit__('./b.js', {
namespace: 'my-test',
data: 'data-for-b',
})
export function unusedHelper() {
return 'this is unused helper'
}
import { unusedHelper } from './c-unused'
export function c() {
return 'this is c.js'
}
export function unused() {
return unusedHelper()
}
import './lib'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
it('should work', async () => {
const list = getList()
expect(list).toEqual([
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/basic/input/b.js [test] (ecmascript)',
data: 'more-data-for-b',
}),
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/basic/input/c.js [test] (ecmascript)',
data: 'data-for-c',
}),
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/basic/input/a.js [test] (ecmascript)',
data: 'data-for-a',
}),
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/basic/input/b.js [test] (ecmascript)',
data: 'data-for-b',
}),
])
const [b2, c, a, b1] = list
expect((await a.import()).a()).toEqual('this is a.js')
expect((await b1.import()).b()).toEqual('this is b.js')
expect((await c.import()).c()).toEqual('this is c.js')
expect(await b1.import()).toBe(await b2.import())
const modules = Array.from(__turbopack_modules__.keys())
expect(modules).not.toContainEqual(expect.stringMatching(/input\/c-unused/))
})
__turbopack_emit__('./a.js', {
namespace: 'my-test',
data: 'data-for-a',
})
__turbopack_emit__('./c.js', {
namespace: 'my-test',
data: 'data-for-c',
exports: ['c'],
})
export default function () {
import('./async')
}
__turbopack_emit__('./b.js', {
namespace: 'my-test',
data: 'more-data-for-b',
})
import './lib'
const getList = __turbopack_collect__({
namespace: 'my-test',
})
it('should work', async () => {
const list = [...getList()]
list.sort((a, b) => String(a.data).localeCompare(String(b.data)))
expect(list).toEqual([
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/data/input/a.js [test] (ecmascript)',
data: { foo: 1, bar: 'baz' },
}),
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/data/input/a.js [test] (ecmascript)',
data: 'data-for-a',
}),
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/data/input/a.js [test] (ecmascript)',
data: ['foo', 123, true, null],
}),
expect.objectContaining({
id: '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/collect/data/input/a.js [test] (ecmascript)',
data: undefined,
}),
])
for (const item of list) {
expect((await item.import()).a()).toEqual('this is a.js')
}
})
__turbopack_emit__('./a.js', {
namespace: 'my-test',
})
__turbopack_emit__('./a.js', {
namespace: 'my-test',
data: 'data-for-a',
})
__turbopack_emit__('./a.js', {
namespace: 'my-test',
data: ['foo', 123, true, null],
})
__turbopack_emit__('./a.js', {
namespace: 'my-test',
data: { foo: 1, bar: 'baz' },
})
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