Skip to main content

turbopack_css/chunk/
mod.rs

1pub(crate) mod single_item_chunk;
2pub mod source_map;
3
4use std::fmt::Write;
5
6use anyhow::{Result, bail};
7use turbo_rcstr::{RcStr, rcstr};
8use turbo_tasks::{FxIndexSet, ResolvedVc, TryJoinIterExt, ValueDefault, ValueToString, Vc};
9use turbo_tasks_fs::{
10    File, FileContent, FileSystem, FileSystemPath,
11    rope::{Rope, RopeBuilder},
12};
13use turbopack_core::{
14    asset::{Asset, AssetContent},
15    chunk::{
16        AsyncModuleInfo, Chunk, ChunkItem, ChunkItemBatchGroup, ChunkItemExt,
17        ChunkItemOrBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
18        ChunkableModule, ChunkingContext, ChunkingContextExt, MinifyType, OutputChunk,
19        OutputChunkRuntimeInfo, SourceMapSourceType, round_chunk_item_size,
20    },
21    code_builder::{Code, CodeBuilder},
22    ident::AssetIdent,
23    introspect::{
24        Introspectable, IntrospectableChildren,
25        module::IntrospectableModule,
26        utils::{children_from_output_assets, content_to_details},
27    },
28    module::Module,
29    output::{OutputAsset, OutputAssetsReference, OutputAssetsWithReferenced},
30    reference_type::ImportContext,
31    server_fs::ServerFileSystem,
32    source_map::{
33        GenerateSourceMap,
34        utils::{absolute_fileify_source_map, relative_fileify_source_map},
35    },
36};
37
38use self::{single_item_chunk::chunk::SingleItemCssChunk, source_map::CssChunkSourceMapAsset};
39use crate::ImportAssetReference;
40
41#[turbo_tasks::value]
42pub struct CssChunk {
43    pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
44    pub content: ResolvedVc<CssChunkContent>,
45}
46
47#[turbo_tasks::value_impl]
48impl CssChunk {
49    #[turbo_tasks::function]
50    pub fn new(
51        chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
52        content: ResolvedVc<CssChunkContent>,
53    ) -> Vc<Self> {
54        CssChunk {
55            chunking_context,
56            content,
57        }
58        .cell()
59    }
60
61    #[turbo_tasks::function]
62    fn chunk_content(&self) -> Vc<CssChunkContent> {
63        *self.content
64    }
65
66    #[turbo_tasks::function]
67    async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
68        use std::io::Write;
69
70        let this = self.await?;
71
72        let source_maps = *this
73            .chunking_context
74            .reference_chunk_source_maps(Vc::upcast(self))
75            .await?;
76
77        // CSS chunks never have debug IDs
78        let mut code = CodeBuilder::new(source_maps, false);
79        let mut body = CodeBuilder::new(source_maps, false);
80        let mut external_imports = FxIndexSet::default();
81        for css_item in &this.content.await?.chunk_items {
82            let content = &css_item.content().await?;
83            for import in &content.imports {
84                if let CssImport::External(external_import) = import {
85                    external_imports.insert((*external_import.await?).to_string());
86                }
87            }
88
89            if matches!(
90                &*this.chunking_context.minify_type().await?,
91                MinifyType::NoMinify
92            ) {
93                let id = css_item.asset_ident().to_string().await?;
94                writeln!(body, "/* {id} */")?;
95            }
96
97            let close = write_import_context(&mut body, content.import_context).await?;
98
99            let chunking_context = self.chunking_context();
100            let source_map = content.source_map.await?;
101            let source_map = source_map.as_content().map(|f| f.content());
102            let source_map = match *chunking_context.source_map_source_type().await? {
103                SourceMapSourceType::AbsoluteFileUri => {
104                    absolute_fileify_source_map(
105                        source_map,
106                        chunking_context.root_path().owned().await?,
107                    )
108                    .await?
109                }
110                SourceMapSourceType::RelativeUri => {
111                    relative_fileify_source_map(
112                        source_map,
113                        chunking_context.root_path().owned().await?,
114                        chunking_context
115                            .relative_path_from_chunk_root_to_project_root()
116                            .owned()
117                            .await?,
118                    )
119                    .await?
120                }
121                SourceMapSourceType::TurbopackUri => source_map.cloned(),
122            };
123
124            body.push_source(&content.inner_code, source_map);
125
126            if !close.is_empty() {
127                writeln!(body, "{close}")?;
128            }
129            writeln!(body)?;
130        }
131
132        for external_import in external_imports {
133            writeln!(code, "{}", external_import)?;
134        }
135
136        let built = &body.build();
137        code.push_code(built);
138
139        let c = code.build().cell();
140        Ok(c)
141    }
142
143    #[turbo_tasks::function]
144    async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
145        let code = self.code().await?;
146
147        let rope = if code.has_source_map() {
148            use std::io::Write;
149            let mut rope_builder = RopeBuilder::default();
150            rope_builder.concat(code.source_code());
151            let source_map_path = CssChunkSourceMapAsset::new(self).path().await?;
152            write!(
153                rope_builder,
154                "/*# sourceMappingURL={}*/",
155                urlencoding::encode(source_map_path.file_name())
156            )?;
157            rope_builder.build()
158        } else {
159            code.source_code().clone()
160        };
161
162        Ok(AssetContent::file(
163            FileContent::Content(File::from(rope)).cell(),
164        ))
165    }
166
167    #[turbo_tasks::function]
168    async fn ident_for_path(&self) -> Result<Vc<AssetIdent>> {
169        let CssChunkContent { chunk_items, .. } = &*self.content.await?;
170        let mut common_path = if let Some(chunk_item) = chunk_items.first() {
171            let path = chunk_item.asset_ident().await?.path.clone();
172            Some(path)
173        } else {
174            None
175        };
176
177        // The included chunk items and the availability info describe the chunk
178        // uniquely
179        for &chunk_item in chunk_items.iter() {
180            if let Some(common_path_ref) = common_path.as_mut() {
181                let path = &chunk_item.asset_ident().await?.path;
182                while !path.is_inside_or_equal_ref(common_path_ref) {
183                    let parent = common_path_ref.parent();
184                    if parent == *common_path_ref {
185                        common_path = None;
186                        break;
187                    }
188                    *common_path_ref = parent;
189                }
190            }
191        }
192        let assets = chunk_items
193            .iter()
194            .map(|chunk_item| async move {
195                Ok((
196                    rcstr!("chunk item"),
197                    chunk_item.content_ident().to_resolved().await?,
198                ))
199            })
200            .try_join()
201            .await?;
202
203        let path = if let Some(common_path) = common_path {
204            common_path
205        } else {
206            ServerFileSystem::new().root().owned().await?
207        };
208        let mut ident = AssetIdent::from_path(path);
209        ident.assets.extend(assets);
210
211        Ok(ident.into_vc())
212    }
213}
214
215pub async fn write_import_context(
216    body: &mut impl std::io::Write,
217    import_context: Option<ResolvedVc<ImportContext>>,
218) -> Result<String> {
219    let mut close = String::new();
220    if let Some(import_context) = import_context {
221        let import_context = &*import_context.await?;
222        if !&import_context.layers.is_empty() {
223            writeln!(body, "@layer {} {{", import_context.layers.join("."))?;
224            close.push_str("\n}");
225        }
226        if !&import_context.media.is_empty() {
227            writeln!(body, "@media {} {{", import_context.media.join(" and "))?;
228            close.push_str("\n}");
229        }
230        if !&import_context.supports.is_empty() {
231            writeln!(
232                body,
233                "@supports {} {{",
234                import_context.supports.join(" and ")
235            )?;
236            close.push_str("\n}");
237        }
238    }
239    Ok(close)
240}
241
242#[turbo_tasks::value]
243pub struct CssChunkContent {
244    pub chunk_items: Vec<ResolvedVc<Box<dyn CssChunkItem>>>,
245}
246
247#[turbo_tasks::value_impl]
248impl OutputAssetsReference for CssChunk {
249    #[turbo_tasks::function]
250    async fn references(self: Vc<Self>) -> Result<Vc<OutputAssetsWithReferenced>> {
251        let this = self.await?;
252        let content = this.content.await?;
253        let should_generate_single_item_chunks = content.chunk_items.len() > 1
254            && *this
255                .chunking_context
256                .is_dynamic_chunk_content_loading_enabled()
257                .await?;
258        let references = content
259            .chunk_items
260            .iter()
261            .map(|item| async {
262                let refs = item.references().await?;
263                let single_css_chunk = if should_generate_single_item_chunks {
264                    Some(ResolvedVc::upcast(
265                        SingleItemCssChunk::new(*this.chunking_context, **item)
266                            .to_resolved()
267                            .await?,
268                    ))
269                } else {
270                    None
271                };
272                Ok((
273                    refs.assets.await?,
274                    single_css_chunk,
275                    refs.referenced_assets.await?,
276                    refs.references.await?,
277                ))
278            })
279            .try_join()
280            .await?;
281        let source_map = if *this
282            .chunking_context
283            .reference_chunk_source_maps(Vc::upcast(self))
284            .await?
285        {
286            Some(ResolvedVc::upcast(
287                CssChunkSourceMapAsset::new(self).to_resolved().await?,
288            ))
289        } else {
290            None
291        };
292
293        Ok(OutputAssetsWithReferenced {
294            assets: ResolvedVc::cell(
295                references
296                    .iter()
297                    .flat_map(|(assets, single_css_chunk, _, _)| {
298                        assets
299                            .iter()
300                            .copied()
301                            .chain(single_css_chunk.iter().copied())
302                    })
303                    .chain(source_map)
304                    .collect(),
305            ),
306            referenced_assets: ResolvedVc::cell(
307                references
308                    .iter()
309                    .flat_map(|(_, _, referenced_assets, _)| referenced_assets.iter().copied())
310                    .collect(),
311            ),
312            references: ResolvedVc::cell(
313                references
314                    .iter()
315                    .flat_map(|(_, _, _, references)| references.iter().copied())
316                    .collect(),
317            ),
318        }
319        .cell())
320    }
321}
322
323#[turbo_tasks::value_impl]
324impl Chunk for CssChunk {
325    #[turbo_tasks::function]
326    async fn ident(self: Vc<Self>) -> Result<Vc<AssetIdent>> {
327        Ok(AssetIdent::from_path(self.path().owned().await?).into_vc())
328    }
329
330    #[turbo_tasks::function]
331    fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
332        *self.chunking_context
333    }
334}
335
336#[turbo_tasks::value_impl]
337impl OutputChunk for CssChunk {
338    #[turbo_tasks::function]
339    async fn runtime_info(&self) -> Result<Vc<OutputChunkRuntimeInfo>> {
340        if !*self
341            .chunking_context
342            .is_dynamic_chunk_content_loading_enabled()
343            .await?
344        {
345            return Ok(OutputChunkRuntimeInfo::empty());
346        }
347
348        let content = self.content.await?;
349        let entries_chunk_items = &content.chunk_items;
350        let included_ids = entries_chunk_items
351            .iter()
352            .map(|chunk_item| chunk_item.id())
353            .try_join()
354            .await?;
355        let imports_chunk_items: Vec<_> = entries_chunk_items
356            .iter()
357            .map(|&css_item| async move {
358                Ok(css_item
359                    .content()
360                    .await?
361                    .imports
362                    .iter()
363                    .filter_map(|import| {
364                        if let CssImport::Internal(_, item) = import {
365                            Some(*item)
366                        } else {
367                            None
368                        }
369                    })
370                    .collect::<Vec<_>>())
371            })
372            .try_join()
373            .await?
374            .into_iter()
375            .flatten()
376            .collect();
377        let module_chunks = if content.chunk_items.len() > 1 {
378            content
379                .chunk_items
380                .iter()
381                .chain(imports_chunk_items.iter())
382                .map(|item| {
383                    Vc::upcast::<Box<dyn OutputAsset>>(SingleItemCssChunk::new(
384                        *self.chunking_context,
385                        **item,
386                    ))
387                    .to_resolved()
388                })
389                .try_join()
390                .await?
391        } else {
392            Vec::new()
393        };
394        Ok(OutputChunkRuntimeInfo {
395            included_ids: Some(ResolvedVc::cell(included_ids)),
396            module_chunks: Some(ResolvedVc::cell(module_chunks)),
397            ..Default::default()
398        }
399        .cell())
400    }
401}
402
403#[turbo_tasks::value_impl]
404impl OutputAsset for CssChunk {
405    #[turbo_tasks::function]
406    async fn path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
407        let ident = self.ident_for_path();
408
409        Ok(self.await?.chunking_context.chunk_path(
410            Some(Vc::upcast(self)),
411            ident,
412            None,
413            rcstr!(".css"),
414        ))
415    }
416}
417
418#[turbo_tasks::value_impl]
419impl Asset for CssChunk {
420    #[turbo_tasks::function]
421    fn content(self: Vc<Self>) -> Vc<AssetContent> {
422        self.content()
423    }
424}
425
426#[turbo_tasks::value_impl]
427impl GenerateSourceMap for CssChunk {
428    #[turbo_tasks::function]
429    fn generate_source_map(self: Vc<Self>) -> Vc<FileContent> {
430        self.code().generate_source_map()
431    }
432}
433
434// TODO: remove
435#[turbo_tasks::value_trait]
436pub trait CssChunkPlaceable: ChunkableModule + Module {}
437
438#[derive(Clone, Debug)]
439#[turbo_tasks::value(shared)]
440pub enum CssImport {
441    External(ResolvedVc<RcStr>),
442    Internal(
443        ResolvedVc<ImportAssetReference>,
444        ResolvedVc<Box<dyn CssChunkItem>>,
445    ),
446    Composes(ResolvedVc<Box<dyn CssChunkItem>>),
447}
448
449#[derive(Debug)]
450#[turbo_tasks::value(shared)]
451pub struct CssChunkItemContent {
452    pub import_context: Option<ResolvedVc<ImportContext>>,
453    pub imports: Vec<CssImport>,
454    pub inner_code: Rope,
455    pub source_map: ResolvedVc<FileContent>,
456}
457
458#[turbo_tasks::value_trait]
459pub trait CssChunkItem: ChunkItem + OutputAssetsReference {
460    #[turbo_tasks::function]
461    fn content(self: Vc<Self>) -> Vc<CssChunkItemContent>;
462}
463
464#[turbo_tasks::value_impl]
465impl Introspectable for CssChunk {
466    #[turbo_tasks::function]
467    fn ty(&self) -> Vc<RcStr> {
468        Vc::cell(rcstr!("css chunk"))
469    }
470
471    #[turbo_tasks::function]
472    fn title(self: Vc<Self>) -> Vc<RcStr> {
473        self.path().to_string()
474    }
475
476    #[turbo_tasks::function]
477    async fn details(self: Vc<Self>) -> Result<Vc<RcStr>> {
478        let content = content_to_details(self.content());
479        let mut details = String::new();
480        let this = self.await?;
481        let chunk_content = this.content.await?;
482        details += "Chunk items:\n\n";
483        for item in chunk_content.chunk_items.iter() {
484            writeln!(details, "- {}", item.asset_ident().to_string().await?)?;
485        }
486        details += "\nContent:\n\n";
487        write!(details, "{}", content.await?)?;
488        Ok(Vc::cell(details.into()))
489    }
490
491    #[turbo_tasks::function]
492    async fn children(self: Vc<Self>) -> Result<Vc<IntrospectableChildren>> {
493        let mut children = children_from_output_assets(OutputAssetsReference::references(self))
494            .owned()
495            .await?;
496        children.extend(
497            self.await?
498                .content
499                .await?
500                .chunk_items
501                .iter()
502                .map(|chunk_item| async move {
503                    Ok((
504                        rcstr!("entry module"),
505                        IntrospectableModule::new(chunk_item.module())
506                            .to_resolved()
507                            .await?,
508                    ))
509                })
510                .try_join()
511                .await?,
512        );
513        Ok(Vc::cell(children))
514    }
515}
516
517#[derive(Default, ValueToString)]
518#[value_to_string("css")]
519#[turbo_tasks::value]
520pub struct CssChunkType {}
521
522#[turbo_tasks::value_impl]
523impl ChunkType for CssChunkType {
524    #[turbo_tasks::function]
525    fn is_style(self: Vc<Self>) -> Vc<bool> {
526        Vc::cell(true)
527    }
528
529    #[turbo_tasks::function]
530    async fn chunk(
531        &self,
532        chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
533        chunk_items_or_batches: Vec<ChunkItemOrBatchWithAsyncModuleInfo>,
534        _batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>,
535    ) -> Result<Vc<Box<dyn Chunk>>> {
536        let mut chunk_items = Vec::new();
537        // TODO operate with batches
538        for item in chunk_items_or_batches {
539            match item {
540                ChunkItemOrBatchWithAsyncModuleInfo::ChunkItem(chunk_item) => {
541                    chunk_items.push(chunk_item);
542                }
543                ChunkItemOrBatchWithAsyncModuleInfo::Batch(batch) => {
544                    let batch = batch.await?;
545                    chunk_items.extend(batch.chunk_items.iter().cloned());
546                }
547            }
548        }
549        let content = CssChunkContent {
550            chunk_items: chunk_items
551                .iter()
552                .map(async |ChunkItemWithAsyncModuleInfo { chunk_item, .. }| {
553                    let Some(chunk_item) =
554                        ResolvedVc::try_downcast::<Box<dyn CssChunkItem>>(*chunk_item)
555                    else {
556                        bail!("Chunk item is not an css chunk item but reporting chunk type css");
557                    };
558                    // CSS doesn't need to care about async_info, so we can discard it
559                    Ok(chunk_item)
560                })
561                .try_join()
562                .await?,
563        }
564        .cell();
565        Ok(Vc::upcast(CssChunk::new(*chunking_context, content)))
566    }
567
568    #[turbo_tasks::function]
569    async fn chunk_item_size(
570        &self,
571        _chunking_context: Vc<Box<dyn ChunkingContext>>,
572        chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
573        _async_module_info: Option<Vc<AsyncModuleInfo>>,
574    ) -> Result<Vc<usize>> {
575        let Some(chunk_item) = ResolvedVc::try_downcast::<Box<dyn CssChunkItem>>(chunk_item) else {
576            bail!("Chunk item is not an css chunk item but reporting chunk type css");
577        };
578        Ok(Vc::cell(chunk_item.content().await.map_or(0, |content| {
579            round_chunk_item_size(content.inner_code.len())
580        })))
581    }
582}
583
584#[turbo_tasks::value_impl]
585impl ValueDefault for CssChunkType {
586    #[turbo_tasks::function]
587    fn value_default() -> Vc<Self> {
588        Self::default().cell()
589    }
590}