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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
pub(crate) mod single_item_chunk;
pub mod source_map;

use std::fmt::Write;

use anyhow::{Result, bail};
use swc_core::common::pass::Either;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
    FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, ValueDefault, ValueToString, Vc,
};
use turbo_tasks_fs::{
    File, FileSystem, FileSystemPath,
    rope::{Rope, RopeBuilder},
};
use turbopack_core::{
    asset::{Asset, AssetContent},
    chunk::{
        AsyncModuleInfo, Chunk, ChunkItem, ChunkItemBatchGroup, ChunkItemExt,
        ChunkItemOrBatchWithAsyncModuleInfo, ChunkItemWithAsyncModuleInfo, ChunkType,
        ChunkableModule, ChunkingContext, MinifyType, OutputChunk, OutputChunkRuntimeInfo,
        round_chunk_item_size,
    },
    code_builder::{Code, CodeBuilder},
    ident::AssetIdent,
    introspect::{
        Introspectable, IntrospectableChildren,
        module::IntrospectableModule,
        utils::{children_from_output_assets, content_to_details},
    },
    module::Module,
    output::{OutputAsset, OutputAssets},
    reference_type::ImportContext,
    server_fs::ServerFileSystem,
    source_map::{GenerateSourceMap, OptionStringifiedSourceMap, utils::fileify_source_map},
};

use self::{single_item_chunk::chunk::SingleItemCssChunk, source_map::CssChunkSourceMapAsset};
use crate::{ImportAssetReference, util::stringify_js};

#[turbo_tasks::value]
pub struct CssChunk {
    pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
    pub content: ResolvedVc<CssChunkContent>,
}

#[turbo_tasks::value_impl]
impl CssChunk {
    #[turbo_tasks::function]
    pub fn new(
        chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
        content: ResolvedVc<CssChunkContent>,
    ) -> Vc<Self> {
        CssChunk {
            chunking_context,
            content,
        }
        .cell()
    }

    #[turbo_tasks::function]
    fn chunk_content(&self) -> Vc<CssChunkContent> {
        *self.content
    }

    #[turbo_tasks::function]
    async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
        use std::io::Write;

        let this = self.await?;

        let source_maps = *this
            .chunking_context
            .reference_chunk_source_maps(Vc::upcast(self))
            .await?;

        let mut code = CodeBuilder::new(source_maps);
        let mut body = CodeBuilder::new(source_maps);
        let mut external_imports = FxIndexSet::default();
        for css_item in &this.content.await?.chunk_items {
            let content = &css_item.content().await?;
            for import in &content.imports {
                if let CssImport::External(external_import) = import {
                    external_imports.insert((*external_import.await?).to_string());
                }
            }

            if matches!(
                &*this.chunking_context.minify_type().await?,
                MinifyType::NoMinify
            ) {
                let id = css_item.asset_ident().to_string().await?;
                writeln!(body, "/* {id} */")?;
            }

            let close = write_import_context(&mut body, content.import_context).await?;

            let source_map = if *self
                .chunking_context()
                .should_use_file_source_map_uris()
                .await?
            {
                fileify_source_map(
                    content.source_map.as_ref(),
                    self.chunking_context().root_path().owned().await?,
                )
                .await?
            } else {
                content.source_map.clone()
            };

            body.push_source(&content.inner_code, source_map);

            if !close.is_empty() {
                writeln!(body, "{close}")?;
            }
            writeln!(body)?;
        }

        for external_import in external_imports {
            writeln!(code, "@import {};", stringify_js(&external_import))?;
        }

        let built = &body.build();
        code.push_code(built);

        let c = code.build().cell();
        Ok(c)
    }

    #[turbo_tasks::function]
    async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
        let code = self.code().await?;

        let rope = if code.has_source_map() {
            use std::io::Write;
            let mut rope_builder = RopeBuilder::default();
            rope_builder.concat(code.source_code());
            let source_map_path = CssChunkSourceMapAsset::new(self).path().await?;
            write!(
                rope_builder,
                "/*# sourceMappingURL={}*/",
                urlencoding::encode(source_map_path.file_name())
            )?;
            rope_builder.build()
        } else {
            code.source_code().clone()
        };

        Ok(AssetContent::file(File::from(rope).into()))
    }

    #[turbo_tasks::function]
    async fn ident_for_path(&self) -> Result<Vc<AssetIdent>> {
        let CssChunkContent { chunk_items, .. } = &*self.content.await?;
        let mut common_path = if let Some(chunk_item) = chunk_items.first() {
            let path = chunk_item.asset_ident().path().owned().await?;
            Some((path.clone(), path))
        } else {
            None
        };

        // The included chunk items and the availability info describe the chunk
        // uniquely
        for &chunk_item in chunk_items.iter() {
            if let Some((common_path_vc, common_path_ref)) = common_path.as_mut() {
                let path = chunk_item.asset_ident().path().await?;
                while !path.is_inside_or_equal_ref(common_path_ref) {
                    let parent = common_path_vc.parent();
                    if parent == *common_path_vc {
                        common_path = None;
                        break;
                    }
                    *common_path_vc = parent;
                    *common_path_ref = common_path_vc.clone();
                }
            }
        }
        let assets = chunk_items
            .iter()
            .map(|chunk_item| async move {
                Ok((
                    rcstr!("chunk item"),
                    chunk_item.content_ident().to_resolved().await?,
                ))
            })
            .try_join()
            .await?;

        let ident = AssetIdent {
            path: if let Some((common_path, _)) = common_path {
                common_path
            } else {
                ServerFileSystem::new().root().owned().await?
            },
            query: RcStr::default(),
            fragment: RcStr::default(),
            assets,
            modifiers: Vec::new(),
            parts: Vec::new(),
            layer: None,
            content_type: None,
        };

        Ok(AssetIdent::new(ident))
    }
}

pub async fn write_import_context(
    body: &mut impl std::io::Write,
    import_context: Option<ResolvedVc<ImportContext>>,
) -> Result<String> {
    let mut close = String::new();
    if let Some(import_context) = import_context {
        let import_context = &*import_context.await?;
        if !&import_context.layers.is_empty() {
            writeln!(body, "@layer {} {{", import_context.layers.join("."))?;
            close.push_str("\n}");
        }
        if !&import_context.media.is_empty() {
            writeln!(body, "@media {} {{", import_context.media.join(" and "))?;
            close.push_str("\n}");
        }
        if !&import_context.supports.is_empty() {
            writeln!(
                body,
                "@supports {} {{",
                import_context.supports.join(" and ")
            )?;
            close.push_str("\n}");
        }
    }
    Ok(close)
}

#[turbo_tasks::value]
pub struct CssChunkContent {
    pub chunk_items: Vec<ResolvedVc<Box<dyn CssChunkItem>>>,
    pub referenced_output_assets: ResolvedVc<OutputAssets>,
}

#[turbo_tasks::value_impl]
impl Chunk for CssChunk {
    #[turbo_tasks::function]
    async fn ident(self: Vc<Self>) -> Result<Vc<AssetIdent>> {
        Ok(AssetIdent::from_path(self.path().owned().await?))
    }

    #[turbo_tasks::function]
    fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
        *self.chunking_context
    }
}

#[turbo_tasks::value_impl]
impl OutputChunk for CssChunk {
    #[turbo_tasks::function]
    async fn runtime_info(&self) -> Result<Vc<OutputChunkRuntimeInfo>> {
        if !*self
            .chunking_context
            .is_dynamic_chunk_content_loading_enabled()
            .await?
        {
            return Ok(OutputChunkRuntimeInfo::empty());
        }

        let content = self.content.await?;
        let entries_chunk_items = &content.chunk_items;
        let included_ids = entries_chunk_items
            .iter()
            .map(|chunk_item| chunk_item.id().to_resolved())
            .try_join()
            .await?;
        let imports_chunk_items: Vec<_> = entries_chunk_items
            .iter()
            .map(|&chunk_item| async move {
                let Some(css_item) = ResolvedVc::try_downcast::<Box<dyn CssChunkItem>>(chunk_item)
                else {
                    return Ok(vec![]);
                };
                Ok(css_item
                    .content()
                    .await?
                    .imports
                    .iter()
                    .filter_map(|import| {
                        if let CssImport::Internal(_, item) = import {
                            Some(*item)
                        } else {
                            None
                        }
                    })
                    .collect())
            })
            .try_join()
            .await?
            .into_iter()
            .flatten()
            .collect();
        let module_chunks = if content.chunk_items.len() > 1 {
            content
                .chunk_items
                .iter()
                .chain(imports_chunk_items.iter())
                .map(|item| {
                    Vc::upcast::<Box<dyn OutputAsset>>(SingleItemCssChunk::new(
                        *self.chunking_context,
                        **item,
                    ))
                    .to_resolved()
                })
                .try_join()
                .await?
        } else {
            Vec::new()
        };
        Ok(OutputChunkRuntimeInfo {
            included_ids: Some(ResolvedVc::cell(included_ids)),
            module_chunks: Some(ResolvedVc::cell(module_chunks)),
            ..Default::default()
        }
        .cell())
    }
}

#[turbo_tasks::value_impl]
impl OutputAsset for CssChunk {
    #[turbo_tasks::function]
    async fn path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
        let ident = self.ident_for_path();

        Ok(self.await?.chunking_context.chunk_path(
            Some(Vc::upcast(self)),
            ident,
            None,
            rcstr!(".css"),
        ))
    }

    #[turbo_tasks::function]
    async fn references(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
        let this = self.await?;
        let content = this.content.await?;
        let mut references = content.referenced_output_assets.owned().await?;
        let should_generate_single_item_chunks = content.chunk_items.len() > 1
            && *this
                .chunking_context
                .is_dynamic_chunk_content_loading_enabled()
                .await?;
        references.extend(
            content
                .chunk_items
                .iter()
                .map(|item| async {
                    let references = item.references().await?.into_iter().copied();
                    Ok(if should_generate_single_item_chunks {
                        Either::Left(
                            references.chain(std::iter::once(ResolvedVc::upcast(
                                SingleItemCssChunk::new(*this.chunking_context, **item)
                                    .to_resolved()
                                    .await?,
                            ))),
                        )
                    } else {
                        Either::Right(references)
                    })
                })
                .try_flat_join()
                .await?,
        );
        if *this
            .chunking_context
            .reference_chunk_source_maps(Vc::upcast(self))
            .await?
        {
            references.push(ResolvedVc::upcast(
                CssChunkSourceMapAsset::new(self).to_resolved().await?,
            ));
        }
        Ok(Vc::cell(references))
    }
}

#[turbo_tasks::value_impl]
impl Asset for CssChunk {
    #[turbo_tasks::function]
    fn content(self: Vc<Self>) -> Vc<AssetContent> {
        self.content()
    }
}

#[turbo_tasks::value_impl]
impl GenerateSourceMap for CssChunk {
    #[turbo_tasks::function]
    fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
        self.code().generate_source_map()
    }
}

// TODO: remove
#[turbo_tasks::value_trait]
pub trait CssChunkPlaceable: ChunkableModule + Module + Asset {}

#[derive(Clone, Debug)]
#[turbo_tasks::value(shared)]
pub enum CssImport {
    External(ResolvedVc<RcStr>),
    Internal(
        ResolvedVc<ImportAssetReference>,
        ResolvedVc<Box<dyn CssChunkItem>>,
    ),
    Composes(ResolvedVc<Box<dyn CssChunkItem>>),
}

#[derive(Debug)]
#[turbo_tasks::value(shared)]
pub struct CssChunkItemContent {
    pub import_context: Option<ResolvedVc<ImportContext>>,
    pub imports: Vec<CssImport>,
    pub inner_code: Rope,
    pub source_map: Option<Rope>,
}

#[turbo_tasks::value_trait]
pub trait CssChunkItem: ChunkItem {
    #[turbo_tasks::function]
    fn content(self: Vc<Self>) -> Vc<CssChunkItemContent>;
}

#[turbo_tasks::value_impl]
impl Introspectable for CssChunk {
    #[turbo_tasks::function]
    fn ty(&self) -> Vc<RcStr> {
        Vc::cell(rcstr!("css chunk"))
    }

    #[turbo_tasks::function]
    fn title(self: Vc<Self>) -> Vc<RcStr> {
        self.path().to_string()
    }

    #[turbo_tasks::function]
    async fn details(self: Vc<Self>) -> Result<Vc<RcStr>> {
        let content = content_to_details(self.content());
        let mut details = String::new();
        let this = self.await?;
        let chunk_content = this.content.await?;
        details += "Chunk items:\n\n";
        for item in chunk_content.chunk_items.iter() {
            writeln!(details, "- {}", item.asset_ident().to_string().await?)?;
        }
        details += "\nContent:\n\n";
        write!(details, "{}", content.await?)?;
        Ok(Vc::cell(details.into()))
    }

    #[turbo_tasks::function]
    async fn children(self: Vc<Self>) -> Result<Vc<IntrospectableChildren>> {
        let mut children = children_from_output_assets(OutputAsset::references(self))
            .owned()
            .await?;
        children.extend(
            self.await?
                .content
                .await?
                .chunk_items
                .iter()
                .map(|chunk_item| async move {
                    Ok((
                        rcstr!("entry module"),
                        IntrospectableModule::new(chunk_item.module())
                            .to_resolved()
                            .await?,
                    ))
                })
                .try_join()
                .await?,
        );
        Ok(Vc::cell(children))
    }
}

#[derive(Default)]
#[turbo_tasks::value]
pub struct CssChunkType {}

#[turbo_tasks::value_impl]
impl ValueToString for CssChunkType {
    #[turbo_tasks::function]
    fn to_string(&self) -> Vc<RcStr> {
        Vc::cell(rcstr!("css"))
    }
}

#[turbo_tasks::value_impl]
impl ChunkType for CssChunkType {
    #[turbo_tasks::function]
    fn is_style(self: Vc<Self>) -> Vc<bool> {
        Vc::cell(true)
    }

    #[turbo_tasks::function]
    async fn chunk(
        &self,
        chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
        chunk_items_or_batches: Vec<ChunkItemOrBatchWithAsyncModuleInfo>,
        _batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>,
        referenced_output_assets: ResolvedVc<OutputAssets>,
    ) -> Result<Vc<Box<dyn Chunk>>> {
        let mut chunk_items = Vec::new();
        // TODO operate with batches
        for item in chunk_items_or_batches {
            match item {
                ChunkItemOrBatchWithAsyncModuleInfo::ChunkItem(chunk_item) => {
                    chunk_items.push(chunk_item);
                }
                ChunkItemOrBatchWithAsyncModuleInfo::Batch(batch) => {
                    let batch = batch.await?;
                    chunk_items.extend(batch.chunk_items.iter().cloned());
                }
            }
        }
        let content = CssChunkContent {
            chunk_items: chunk_items
                .iter()
                .map(async |ChunkItemWithAsyncModuleInfo { chunk_item, .. }| {
                    let Some(chunk_item) =
                        ResolvedVc::try_downcast::<Box<dyn CssChunkItem>>(*chunk_item)
                    else {
                        bail!("Chunk item is not an css chunk item but reporting chunk type css");
                    };
                    // CSS doesn't need to care about async_info, so we can discard it
                    Ok(chunk_item)
                })
                .try_join()
                .await?,
            referenced_output_assets,
        }
        .cell();
        Ok(Vc::upcast(CssChunk::new(*chunking_context, content)))
    }

    #[turbo_tasks::function]
    async fn chunk_item_size(
        &self,
        _chunking_context: Vc<Box<dyn ChunkingContext>>,
        chunk_item: Vc<Box<dyn ChunkItem>>,
        _async_module_info: Option<Vc<AsyncModuleInfo>>,
    ) -> Result<Vc<usize>> {
        let Some(chunk_item) =
            Vc::try_resolve_downcast::<Box<dyn CssChunkItem>>(chunk_item).await?
        else {
            bail!("Chunk item is not an css chunk item but reporting chunk type css");
        };
        Ok(Vc::cell(chunk_item.content().await.map_or(0, |content| {
            round_chunk_item_size(content.inner_code.len())
        })))
    }
}

#[turbo_tasks::value_impl]
impl ValueDefault for CssChunkType {
    #[turbo_tasks::function]
    fn value_default() -> Vc<Self> {
        Self::default().cell()
    }
}