Skip to main content

turbopack_node/transforms/
postcss.rs

1use anyhow::{Context, Result, bail};
2use bincode::{Decode, Encode};
3use indoc::formatdoc;
4use serde::Deserialize;
5use turbo_rcstr::{RcStr, rcstr};
6use turbo_tasks::{Completion, Completions, ResolvedVc, TryFlatJoinIterExt, Vc, turbofmt};
7use turbo_tasks_fs::{
8    DiskFileSystem, File, FileContent, FileSystemEntryType, FileSystemPath,
9    json::parse_json_with_source_context, rope::Rope,
10};
11use turbopack_core::{
12    asset::{Asset, AssetContent},
13    changed::any_source_content_changed_of_module,
14    context::{AssetContext, ProcessResult},
15    file_source::FileSource,
16    ident::AssetIdent,
17    module_graph::{ModuleGraph, ModuleGraphOptions, SingleModuleGraph},
18    reference_type::{EntryReferenceSubType, InnerAssets, ReferenceType},
19    resolve::{FindContextFileResult, find_context_file_or_package_key, options::ImportMapping},
20    source::Source,
21    source_map::{GenerateSourceMap, SourceMapType, utils::resolve_source_map_sources},
22    source_transform::SourceTransform,
23    virtual_source::VirtualSource,
24};
25use turbopack_ecmascript::runtime_functions::TURBOPACK_EXTERNAL_IMPORT;
26
27use crate::{
28    embed_js::embed_file_path,
29    evaluate::{EvaluateArg, SourceContentEncoding, get_evaluate_entries},
30    execution_context::ExecutionContext,
31    transforms::{
32        util::{EmittedAsset, emitted_assets_to_virtual_sources},
33        webpack::{WebpackLoaderContext, evaluate_webpack_loader},
34    },
35};
36
37#[derive(Debug, Clone, Deserialize)]
38#[turbo_tasks::value]
39#[serde(rename_all = "camelCase")]
40struct PostCssProcessingResult {
41    css: String,
42    map: Option<String>,
43    assets: Option<Vec<EmittedAsset>>,
44}
45
46#[turbo_tasks::task_input]
47#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug, Encode, Decode)]
48pub enum PostCssConfigLocation {
49    /// Searches for postcss config only starting from the project root directory.
50    /// Used for foreign code (node_modules) where per-directory configs should be ignored.
51    #[default]
52    ProjectPath,
53    /// Searches for postcss config starting from the project root directory first,
54    /// then falls back to searching from the CSS file's parent directory if not found
55    /// at the project root.
56    ProjectPathOrLocalPath,
57    /// Searches for postcss config starting from the CSS file's parent directory first,
58    /// then falls back to the project root if not found locally. This allows per-directory
59    /// postcss.config.js files to override the project root config.
60    LocalPathOrProjectPath,
61}
62
63#[turbo_tasks::value(shared)]
64#[derive(Clone, Default)]
65pub struct PostCssTransformOptions {
66    pub postcss_package: Option<ResolvedVc<ImportMapping>>,
67    pub config_location: PostCssConfigLocation,
68    pub placeholder_for_future_extensions: u8,
69}
70
71#[turbo_tasks::function]
72fn postcss_configs() -> Vc<Vec<RcStr>> {
73    Vc::cell(vec![
74        rcstr!(".postcssrc"),
75        rcstr!(".postcssrc.json"),
76        rcstr!(".postcssrc.yaml"),
77        rcstr!(".postcssrc.yml"),
78        rcstr!(".postcssrc.js"),
79        rcstr!(".postcssrc.mjs"),
80        rcstr!(".postcssrc.cjs"),
81        rcstr!(".postcssrc.ts"),
82        rcstr!(".postcssrc.mts"),
83        rcstr!(".postcssrc.cts"),
84        rcstr!(".config/postcssrc"),
85        rcstr!(".config/postcssrc.json"),
86        rcstr!(".config/postcssrc.yaml"),
87        rcstr!(".config/postcssrc.yml"),
88        rcstr!(".config/postcssrc.js"),
89        rcstr!(".config/postcssrc.mjs"),
90        rcstr!(".config/postcssrc.cjs"),
91        rcstr!(".config/postcssrc.ts"),
92        rcstr!(".config/postcssrc.mts"),
93        rcstr!(".config/postcssrc.cts"),
94        rcstr!("postcss.config.js"),
95        rcstr!("postcss.config.mjs"),
96        rcstr!("postcss.config.cjs"),
97        rcstr!("postcss.config.ts"),
98        rcstr!("postcss.config.mts"),
99        rcstr!("postcss.config.cts"),
100        rcstr!("postcss.config.json"),
101    ])
102}
103
104#[turbo_tasks::value]
105pub struct PostCssTransform {
106    evaluate_context: ResolvedVc<Box<dyn AssetContext>>,
107    config_tracing_context: ResolvedVc<Box<dyn AssetContext>>,
108    execution_context: ResolvedVc<ExecutionContext>,
109    config_location: PostCssConfigLocation,
110    source_maps: bool,
111}
112
113#[turbo_tasks::value_impl]
114impl PostCssTransform {
115    #[turbo_tasks::function]
116    pub fn new(
117        evaluate_context: ResolvedVc<Box<dyn AssetContext>>,
118        config_tracing_context: ResolvedVc<Box<dyn AssetContext>>,
119        execution_context: ResolvedVc<ExecutionContext>,
120        config_location: PostCssConfigLocation,
121        source_maps: bool,
122    ) -> Vc<Self> {
123        PostCssTransform {
124            evaluate_context,
125            config_tracing_context,
126            execution_context,
127            config_location,
128            source_maps,
129        }
130        .cell()
131    }
132}
133
134#[turbo_tasks::value_impl]
135impl SourceTransform for PostCssTransform {
136    #[turbo_tasks::function]
137    fn transform(
138        &self,
139        source: ResolvedVc<Box<dyn Source>>,
140        asset_context: ResolvedVc<Box<dyn AssetContext>>,
141    ) -> Vc<Box<dyn Source>> {
142        Vc::upcast(
143            PostCssTransformedAsset {
144                evaluate_context: self.evaluate_context,
145                config_tracing_context: self.config_tracing_context,
146                execution_context: self.execution_context,
147                config_location: self.config_location,
148                source,
149                asset_context,
150                source_map: self.source_maps,
151            }
152            .cell(),
153        )
154    }
155}
156
157#[turbo_tasks::value]
158struct PostCssTransformedAsset {
159    evaluate_context: ResolvedVc<Box<dyn AssetContext>>,
160    config_tracing_context: ResolvedVc<Box<dyn AssetContext>>,
161    execution_context: ResolvedVc<ExecutionContext>,
162    config_location: PostCssConfigLocation,
163    source: ResolvedVc<Box<dyn Source>>,
164    asset_context: ResolvedVc<Box<dyn AssetContext>>,
165    source_map: bool,
166}
167
168#[turbo_tasks::value_impl]
169impl Source for PostCssTransformedAsset {
170    #[turbo_tasks::function]
171    fn ident(&self) -> Vc<AssetIdent> {
172        self.source.ident()
173    }
174
175    #[turbo_tasks::function]
176    async fn description(&self) -> Result<Vc<RcStr>> {
177        let inner = self.source.description().await?;
178        Ok(Vc::cell(format!("PostCSS transform of {}", inner).into()))
179    }
180}
181
182#[turbo_tasks::value_impl]
183impl Asset for PostCssTransformedAsset {
184    #[turbo_tasks::function]
185    async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
186        Ok(*self.process().await?.content)
187    }
188}
189
190#[turbo_tasks::value]
191struct ProcessPostCssResult {
192    content: ResolvedVc<AssetContent>,
193    source_map: ResolvedVc<FileContent>,
194    assets: Vec<ResolvedVc<VirtualSource>>,
195}
196
197#[turbo_tasks::function]
198async fn config_changed(
199    asset_context: Vc<Box<dyn AssetContext>>,
200    postcss_config_path: FileSystemPath,
201) -> Result<Vc<Completion>> {
202    let config_asset = asset_context
203        .process(
204            Vc::upcast(FileSource::new(postcss_config_path.clone())),
205            ReferenceType::Internal(InnerAssets::empty().to_resolved().await?),
206        )
207        .module();
208
209    Ok(Vc::<Completions>::cell(vec![
210        any_source_content_changed_of_module(config_asset)
211            .to_resolved()
212            .await?,
213        extra_configs_changed(asset_context, postcss_config_path)
214            .to_resolved()
215            .await?,
216    ])
217    .completed())
218}
219
220#[turbo_tasks::function]
221async fn extra_configs_changed(
222    asset_context: Vc<Box<dyn AssetContext>>,
223    postcss_config_path: FileSystemPath,
224) -> Result<Vc<Completion>> {
225    let parent_path = postcss_config_path.parent();
226
227    let config_paths = [
228        parent_path.join("tailwind.config.js")?,
229        parent_path.join("tailwind.config.mjs")?,
230        parent_path.join("tailwind.config.ts")?,
231    ];
232
233    let configs = config_paths
234        .into_iter()
235        .map(async |path| {
236            Ok(
237                if matches!(&*path.get_type().await?, FileSystemEntryType::File) {
238                    match *asset_context
239                        .process(
240                            Vc::upcast(FileSource::new(path)),
241                            ReferenceType::Internal(InnerAssets::empty().to_resolved().await?),
242                        )
243                        .try_into_module()
244                        .await?
245                    {
246                        Some(module) => Some(
247                            any_source_content_changed_of_module(*module)
248                                .to_resolved()
249                                .await?,
250                        ),
251                        None => None,
252                    }
253                } else {
254                    None
255                },
256            )
257        })
258        .try_flat_join()
259        .await?;
260
261    Ok(Vc::<Completions>::cell(configs).completed())
262}
263
264#[turbo_tasks::value]
265struct JsonSource {
266    path: FileSystemPath,
267    key: ResolvedVc<Option<RcStr>>,
268    allow_json5: bool,
269}
270
271#[turbo_tasks::value_impl]
272impl JsonSource {
273    #[turbo_tasks::function]
274    fn new(path: FileSystemPath, key: ResolvedVc<Option<RcStr>>, allow_json5: bool) -> Vc<Self> {
275        JsonSource {
276            path,
277            key,
278            allow_json5,
279        }
280        .cell()
281    }
282}
283
284#[turbo_tasks::value_impl]
285impl Source for JsonSource {
286    #[turbo_tasks::function]
287    fn description(&self) -> Vc<RcStr> {
288        Vc::cell(format!("JSON content of {}", self.path).into())
289    }
290
291    #[turbo_tasks::function]
292    async fn ident(&self) -> Result<Vc<AssetIdent>> {
293        match &*self.key.await? {
294            Some(key) => Ok(AssetIdent::from_path(
295                self.path.append(".")?.append(key)?.append(".json")?,
296            )
297            .into_vc()),
298            None => Ok(AssetIdent::from_path(self.path.append(".json")?).into_vc()),
299        }
300    }
301}
302
303#[turbo_tasks::value_impl]
304impl Asset for JsonSource {
305    #[turbo_tasks::function]
306    async fn content(&self) -> Result<Vc<AssetContent>> {
307        let file_type = &*self.path.get_type().await?;
308        match file_type {
309            FileSystemEntryType::File => {
310                let json = if self.allow_json5 {
311                    self.path.read_json5().content().await?
312                } else {
313                    self.path.read_json().content().await?
314                };
315                let value = match &*self.key.await? {
316                    Some(key) => {
317                        let Some(value) = json.get(&**key) else {
318                            anyhow::bail!("Invalid file type {:?}", file_type)
319                        };
320                        value
321                    }
322                    None => &*json,
323                };
324                Ok(AssetContent::file(
325                    FileContent::Content(File::from(value.to_string())).cell(),
326                ))
327            }
328            FileSystemEntryType::NotFound => {
329                Ok(AssetContent::File(FileContent::NotFound.resolved_cell()).cell())
330            }
331            _ => bail!("Invalid file type {:?}", file_type),
332        }
333    }
334}
335
336#[turbo_tasks::function]
337async fn config_loader_source(
338    project_path: FileSystemPath,
339    postcss_config_path: FileSystemPath,
340) -> Result<Vc<Box<dyn Source>>> {
341    let postcss_config_path_filename = postcss_config_path.file_name();
342
343    if postcss_config_path_filename == "package.json" {
344        return Ok(Vc::upcast(JsonSource::new(
345            postcss_config_path,
346            Vc::cell(Some(rcstr!("postcss"))),
347            false,
348        )));
349    }
350
351    if postcss_config_path.path.ends_with(".json") || postcss_config_path_filename == ".postcssrc" {
352        return Ok(Vc::upcast(JsonSource::new(
353            postcss_config_path,
354            Vc::cell(None),
355            true,
356        )));
357    }
358
359    // We can only load js files with `import()`.
360    if !postcss_config_path.path.ends_with(".js") {
361        return Ok(Vc::upcast(FileSource::new(postcss_config_path)));
362    }
363
364    let Some(config_path) = project_path.get_relative_path_to(&postcss_config_path) else {
365        bail!("Unable to get relative path to postcss config");
366    };
367
368    // We don't want to bundle the config file, so we load it with `import()`.
369    // Bundling would break the ability to use `require.resolve` in the config file.
370    let code = formatdoc! {
371        r#"
372            import {{ pathToFileURL }} from 'node:url';
373            import path from 'node:path';
374
375            const configPath = path.join(process.cwd(), {config_path});
376            // Absolute paths don't work with ESM imports on Windows:
377            // https://github.com/nodejs/node/issues/31710
378            // convert it to a file:// URL, which works on all platforms
379            const configUrl = pathToFileURL(configPath).toString();
380            const mod = await {TURBOPACK_EXTERNAL_IMPORT}(configUrl);
381
382            export default mod.default ?? mod;
383        "#,
384        config_path = serde_json::to_string(&config_path).expect("a string should be serializable"),
385    };
386
387    Ok(Vc::upcast(VirtualSource::new(
388        postcss_config_path.append("_.loader.mjs")?,
389        AssetContent::file(FileContent::Content(File::from(code)).cell()),
390    )))
391}
392
393#[turbo_tasks::function]
394async fn postcss_executor(
395    asset_context: Vc<Box<dyn AssetContext>>,
396    project_path: FileSystemPath,
397    postcss_config_path: FileSystemPath,
398) -> Result<Vc<ProcessResult>> {
399    let config_asset = asset_context
400        .process(
401            config_loader_source(project_path, postcss_config_path.clone()),
402            ReferenceType::Entry(EntryReferenceSubType::default()),
403        )
404        .module()
405        .to_resolved()
406        .await?;
407
408    Ok(asset_context.process(
409        Vc::upcast(FileSource::new_with_query(
410            embed_file_path(rcstr!("transforms/postcss.ts"))
411                .owned()
412                .await?,
413            turbofmt!("?config={postcss_config_path}").await?,
414        )),
415        ReferenceType::Internal(ResolvedVc::cell([(rcstr!("CONFIG"), config_asset)].into())),
416    ))
417}
418
419async fn find_config_in_location(
420    project_path: FileSystemPath,
421    location: PostCssConfigLocation,
422    source: Vc<Box<dyn Source>>,
423) -> Result<Option<FileSystemPath>> {
424    // Build an ordered list of directories to search based on the location strategy.
425    let search_paths = match location {
426        // Only check project root (used for foreign/node_modules code).
427        PostCssConfigLocation::ProjectPath => {
428            vec![project_path]
429        }
430        // Check project root first, fall back to the CSS file's directory.
431        PostCssConfigLocation::ProjectPathOrLocalPath => {
432            vec![project_path, source.ident().await?.path.parent()]
433        }
434        // Check the CSS file's directory first, fall back to the project root.
435        PostCssConfigLocation::LocalPathOrProjectPath => {
436            vec![source.ident().await?.path.parent(), project_path]
437        }
438    };
439
440    for path in search_paths {
441        if let FindContextFileResult::Found(config_path, _) =
442            &*find_context_file_or_package_key(path, postcss_configs(), rcstr!("postcss")).await?
443        {
444            return Ok(Some(config_path.clone()));
445        }
446    }
447
448    Ok(None)
449}
450
451#[turbo_tasks::value_impl]
452impl GenerateSourceMap for PostCssTransformedAsset {
453    #[turbo_tasks::function]
454    async fn generate_source_map(self: Vc<Self>, _ty: SourceMapType) -> Result<Vc<FileContent>> {
455        Ok(*self.process().await?.source_map)
456    }
457}
458
459#[turbo_tasks::value_impl]
460impl PostCssTransformedAsset {
461    #[turbo_tasks::function]
462    async fn process(&self) -> Result<Vc<ProcessPostCssResult>> {
463        let source_map = if let Some(generator) =
464            ResolvedVc::try_sidecast::<Box<dyn GenerateSourceMap>>(self.source)
465        {
466            generator
467                .generate_source_map(SourceMapType::Full)
468                .to_resolved()
469                .await?
470        } else {
471            FileContent::NotFound.resolved_cell()
472        };
473        let ExecutionContext {
474            project_path,
475            chunking_context,
476            env,
477            node_backend,
478        } = &*self.execution_context.await?;
479
480        // For this postcss transform, there is no guarantee that looking up for the
481        // source path will arrives specific project config for the postcss.
482        // i.e, this is possible
483        // - root
484        //  - node_modules
485        //     - somepkg/(some.module.css, postcss.config.js) // this could be symlinked local, or
486        //       actual remote pkg or anything
487        //  - packages // root of workspace pkgs
488        //     - pkg1/(postcss.config.js) // The actual config we're looking for
489        //
490        // We look for the config in the project path first, then the source path
491        let Some(config_path) =
492            find_config_in_location(project_path.clone(), self.config_location, *self.source)
493                .await?
494        else {
495            return Ok(ProcessPostCssResult {
496                content: self.source.content().to_resolved().await?,
497                source_map,
498                assets: Vec::new(),
499            }
500            .cell());
501        };
502
503        let input_source_map = match &*source_map.await? {
504            FileContent::Content(file) => serde_json::from_str(&file.content().to_str()?)?,
505            FileContent::NotFound => serde_json::Value::Null,
506        };
507        let evaluate_context = self.evaluate_context;
508        let source_map = self.source_map;
509
510        // This invalidates the transform when the config changes.
511        let config_changed = config_changed(*self.config_tracing_context, config_path.clone())
512            .to_resolved()
513            .await?;
514
515        let postcss_executor =
516            postcss_executor(*evaluate_context, project_path.clone(), config_path).module();
517
518        let entries =
519            get_evaluate_entries(postcss_executor, *evaluate_context, **node_backend, None)
520                .to_resolved()
521                .await?;
522
523        let module_graph = ModuleGraph::from_graphs(
524            vec![SingleModuleGraph::new_with_entries(
525                entries.graph_entries().to_resolved().await?,
526                ModuleGraphOptions::default(),
527            )],
528            None,
529        )
530        .connect()
531        .to_resolved()
532        .await?;
533
534        let source_ident = self.source.ident().await?;
535
536        let css_path =
537            if ResolvedVc::try_downcast_type::<DiskFileSystem>(source_ident.path.fs).is_some() {
538                EvaluateArg::Path(source_ident.path.clone())
539            } else {
540                // This shouldn't be an error since it can happen on virtual assets
541                EvaluateArg::Vc(ResolvedVc::cell(serde_json::Value::from("")))
542            };
543
544        let config_value = evaluate_webpack_loader(WebpackLoaderContext {
545            entries,
546            cwd: project_path.clone(),
547            env: *env,
548            node_backend: *node_backend,
549            context_source_for_issue: self.source,
550            chunking_context: *chunking_context,
551            evaluate_context: self.evaluate_context,
552            module_graph,
553            resolve_options_context: None,
554            asset_context: self.asset_context,
555            args: vec![
556                EvaluateArg::SourceContent {
557                    source: self.source,
558                    encoding: SourceContentEncoding::Text,
559                },
560                css_path,
561                EvaluateArg::Vc(ResolvedVc::cell(source_map.into())),
562                EvaluateArg::Vc(ResolvedVc::cell(input_source_map)),
563            ],
564            additional_invalidation: config_changed,
565            loader_names: vec![turbo_rcstr::rcstr!("postcss")],
566        })
567        .await?;
568
569        let Some(val) = &*config_value else {
570            // An error happened, which has already been converted into an issue.
571            return Ok(ProcessPostCssResult {
572                content: AssetContent::File(FileContent::NotFound.resolved_cell()).resolved_cell(),
573                source_map: FileContent::NotFound.resolved_cell(),
574                assets: Vec::new(),
575            }
576            .cell());
577        };
578        let processed_css: PostCssProcessingResult = parse_json_with_source_context(val)
579            .context("Unable to deserializate response from PostCSS transform operation")?;
580
581        let source_map = processed_css.map.map(Rope::from);
582        let source_map =
583            resolve_source_map_sources(source_map.as_ref(), &source_ident.path).await?;
584        let source_map = match source_map {
585            Some(map) => FileContent::Content(File::from(map)).resolved_cell(),
586            None => FileContent::NotFound.resolved_cell(),
587        };
588        let file = File::from(processed_css.css);
589        let assets = emitted_assets_to_virtual_sources(processed_css.assets).await?;
590        let content =
591            AssetContent::File(FileContent::Content(file).resolved_cell()).resolved_cell();
592        Ok(ProcessPostCssResult {
593            content,
594            source_map,
595            assets,
596        }
597        .cell())
598    }
599}