-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
postcss.rs
445 lines (400 loc) · 13.9 KB
/
postcss.rs
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
use anyhow::{bail, Context, Result};
use indexmap::indexmap;
use indoc::formatdoc;
use serde::{Deserialize, Serialize};
use turbo_tasks::{
trace::TraceRawVcs, Completion, Completions, TaskInput, TryFlatJoinIterExt, Value, Vc,
};
use turbo_tasks_bytes::stream::SingleValue;
use turbo_tasks_fs::{
json::parse_json_with_source_context, File, FileContent, FileSystemEntryType, FileSystemPath,
};
use turbopack_core::{
asset::{Asset, AssetContent},
changed::any_content_changed_of_module,
context::{AssetContext, ProcessResult},
file_source::FileSource,
ident::AssetIdent,
issue::{
Issue, IssueDescriptionExt, IssueSeverity, IssueStage, OptionStyledString, StyledString,
},
reference_type::{EntryReferenceSubType, InnerAssets, ReferenceType},
resolve::{find_context_file, options::ImportMapping, FindContextFileResult},
source::Source,
source_transform::SourceTransform,
virtual_source::VirtualSource,
};
use super::{
util::{emitted_assets_to_virtual_sources, EmittedAsset},
webpack::WebpackLoaderContext,
};
use crate::{
embed_js::embed_file, execution_context::ExecutionContext,
transforms::webpack::evaluate_webpack_loader,
};
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[turbo_tasks::value(transparent, serialization = "custom")]
struct PostCssProcessingResult {
css: String,
map: Option<String>,
#[turbo_tasks(trace_ignore)]
assets: Option<Vec<EmittedAsset>>,
}
#[derive(
Default, Copy, Clone, PartialEq, Eq, Debug, TraceRawVcs, Serialize, Deserialize, TaskInput,
)]
pub enum PostCssConfigLocation {
#[default]
ProjectPath,
ProjectPathOrLocalPath,
}
#[turbo_tasks::value(shared)]
#[derive(Clone, Default)]
pub struct PostCssTransformOptions {
pub postcss_package: Option<Vc<ImportMapping>>,
pub config_location: PostCssConfigLocation,
pub placeholder_for_future_extensions: u8,
}
#[turbo_tasks::function]
fn postcss_configs() -> Vc<Vec<String>> {
Vc::cell(
[
".postcssrc",
".postcssrc.json",
".postcssrc.yaml",
".postcssrc.yml",
".postcssrc.js",
".postcssrc.mjs",
".postcssrc.cjs",
".config/postcssrc",
".config/postcssrc.json",
".config/postcssrc.yaml",
".config/postcssrc.yml",
".config/postcssrc.js",
".config/postcssrc.mjs",
".config/postcssrc.cjs",
"postcss.config.js",
"postcss.config.mjs",
"postcss.config.cjs",
"postcss.config.json",
]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
)
}
#[turbo_tasks::value]
pub struct PostCssTransform {
evaluate_context: Vc<Box<dyn AssetContext>>,
execution_context: Vc<ExecutionContext>,
config_location: PostCssConfigLocation,
}
#[turbo_tasks::value_impl]
impl PostCssTransform {
#[turbo_tasks::function]
pub fn new(
evaluate_context: Vc<Box<dyn AssetContext>>,
execution_context: Vc<ExecutionContext>,
config_location: PostCssConfigLocation,
) -> Vc<Self> {
PostCssTransform {
evaluate_context,
execution_context,
config_location,
}
.cell()
}
}
#[turbo_tasks::value_impl]
impl SourceTransform for PostCssTransform {
#[turbo_tasks::function]
fn transform(&self, source: Vc<Box<dyn Source>>) -> Vc<Box<dyn Source>> {
Vc::upcast(
PostCssTransformedAsset {
evaluate_context: self.evaluate_context,
execution_context: self.execution_context,
config_location: self.config_location,
source,
}
.cell(),
)
}
}
#[turbo_tasks::value]
struct PostCssTransformedAsset {
evaluate_context: Vc<Box<dyn AssetContext>>,
execution_context: Vc<ExecutionContext>,
config_location: PostCssConfigLocation,
source: Vc<Box<dyn Source>>,
}
#[turbo_tasks::value_impl]
impl Source for PostCssTransformedAsset {
#[turbo_tasks::function]
fn ident(&self) -> Vc<AssetIdent> {
self.source.ident()
}
}
#[turbo_tasks::value_impl]
impl Asset for PostCssTransformedAsset {
#[turbo_tasks::function]
async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
let this = self.await?;
Ok(self
.process()
.issue_file_path(this.source.ident().path(), "PostCSS processing")
.await?
.await?
.content)
}
}
#[turbo_tasks::value]
struct ProcessPostCssResult {
content: Vc<AssetContent>,
assets: Vec<Vc<VirtualSource>>,
}
#[turbo_tasks::function]
async fn config_changed(
asset_context: Vc<Box<dyn AssetContext>>,
postcss_config_path: Vc<FileSystemPath>,
) -> Result<Vc<Completion>> {
let config_asset = asset_context
.process(
Vc::upcast(FileSource::new(postcss_config_path)),
Value::new(ReferenceType::Internal(InnerAssets::empty())),
)
.module();
Ok(Vc::<Completions>::cell(vec![
any_content_changed_of_module(config_asset),
extra_configs_changed(asset_context, postcss_config_path),
])
.completed())
}
#[turbo_tasks::function]
async fn extra_configs_changed(
asset_context: Vc<Box<dyn AssetContext>>,
postcss_config_path: Vc<FileSystemPath>,
) -> Result<Vc<Completion>> {
let parent_path = postcss_config_path.parent();
let config_paths = [
parent_path.join("tailwind.config.js".to_string()),
parent_path.join("tailwind.config.ts".to_string()),
];
let configs = config_paths
.into_iter()
.map(|path| async move {
Ok(
if matches!(&*path.get_type().await?, FileSystemEntryType::File) {
match *asset_context
.process(
Vc::upcast(FileSource::new(path)),
Value::new(ReferenceType::Internal(InnerAssets::empty())),
)
.await?
{
ProcessResult::Module(module) => {
Some(any_content_changed_of_module(module))
}
ProcessResult::Ignore => None,
}
} else {
None
},
)
})
.try_flat_join()
.await?;
Ok(Vc::<Completions>::cell(configs).completed())
}
#[turbo_tasks::function]
pub(crate) async fn config_loader_source(
project_path: Vc<FileSystemPath>,
postcss_config_path: Vc<FileSystemPath>,
) -> Result<Vc<Box<dyn Source>>> {
let postcss_config_path_value = &*postcss_config_path.await?;
// We can only load js files with `import()`.
if !postcss_config_path_value.path.ends_with(".js") {
return Ok(Vc::upcast(FileSource::new(postcss_config_path)));
}
let Some(config_path) = project_path
.await?
.get_relative_path_to(postcss_config_path_value)
else {
bail!("Unable to get relative path to postcss config");
};
// We don't want to bundle the config file, so we load it with `import()`.
// Bundling would break the ability to use `require.resolve` in the config file.
let code = formatdoc! {
r#"
const configPath = `${{process.cwd()}}/{config_path}`;
const mod = await __turbopack_external_import__(configPath);
export default mod.default ?? mod;
"#,
config_path = config_path,
};
Ok(Vc::upcast(VirtualSource::new(
postcss_config_path.append("_.loader.mjs".to_string()),
AssetContent::file(File::from(code).into()),
)))
}
#[turbo_tasks::function]
async fn postcss_executor(
asset_context: Vc<Box<dyn AssetContext>>,
project_path: Vc<FileSystemPath>,
postcss_config_path: Vc<FileSystemPath>,
) -> Result<Vc<ProcessResult>> {
let config_asset = asset_context
.process(
config_loader_source(project_path, postcss_config_path),
Value::new(ReferenceType::Entry(EntryReferenceSubType::Undefined)),
)
.module();
Ok(asset_context.process(
Vc::upcast(VirtualSource::new(
postcss_config_path.join("transform.ts".to_string()),
AssetContent::File(embed_file("transforms/postcss.ts".to_string())).cell(),
)),
Value::new(ReferenceType::Internal(Vc::cell(indexmap! {
"CONFIG".to_string() => config_asset
}))),
))
}
async fn find_config_in_location(
project_path: Vc<FileSystemPath>,
location: PostCssConfigLocation,
source: Vc<Box<dyn Source>>,
) -> Result<Option<Vc<FileSystemPath>>> {
if let FindContextFileResult::Found(config_path, _) =
*find_context_file(project_path, postcss_configs()).await?
{
return Ok(Some(config_path));
}
if matches!(location, PostCssConfigLocation::ProjectPathOrLocalPath) {
if let FindContextFileResult::Found(config_path, _) =
*find_context_file(source.ident().path().parent(), postcss_configs()).await?
{
return Ok(Some(config_path));
}
}
Ok(None)
}
#[turbo_tasks::value_impl]
impl PostCssTransformedAsset {
#[turbo_tasks::function]
async fn process(self: Vc<Self>) -> Result<Vc<ProcessPostCssResult>> {
let this = self.await?;
let ExecutionContext {
project_path,
chunking_context,
env,
} = *this.execution_context.await?;
// For this postcss transform, there is no gaurantee that looking up for the
// source path will arrives specific project config for the postcss.
// i.e, this is possible
// - root
// - node_modules
// - somepkg/(some.module.css, postcss.config.js) // this could be symlinked
// local, or actual remote pkg or anything
// - packages // root of workspace pkgs
// - pkg1/(postcss.config.js) // The actual config we're looking for
//
// We look for the config in the project path first, then the source path
let Some(config_path) =
find_config_in_location(project_path, this.config_location, this.source).await?
else {
return Ok(ProcessPostCssResult {
content: this.source.content(),
assets: Vec::new(),
}
.cell());
};
let source_content = this.source.content();
let AssetContent::File(file) = *source_content.await? else {
bail!("PostCSS transform only support transforming files");
};
let FileContent::Content(content) = &*file.await? else {
return Ok(ProcessPostCssResult {
content: AssetContent::File(FileContent::NotFound.cell()).cell(),
assets: Vec::new(),
}
.cell());
};
let content = content.content().to_str()?;
let evaluate_context = this.evaluate_context;
// This invalidates the transform when the config changes.
let config_changed = config_changed(evaluate_context, config_path);
let postcss_executor =
postcss_executor(evaluate_context, project_path, config_path).module();
let css_fs_path = this.source.ident().path();
// We need to get a path relative to the project because the postcss loader
// runs with the project as the current working directory.
let css_path = if let Some(css_path) = project_path
.await?
.get_relative_path_to(&*css_fs_path.await?)
{
css_path
} else {
// This shouldn't be an error since it can happen on virtual assets
"".to_string()
};
let config_value = evaluate_webpack_loader(WebpackLoaderContext {
module_asset: postcss_executor,
cwd: project_path,
env,
context_ident_for_issue: this.source.ident(),
asset_context: evaluate_context,
chunking_context,
resolve_options_context: None,
args: vec![Vc::cell(content.into()), Vc::cell(css_path.into())],
additional_invalidation: config_changed,
})
.await?;
let SingleValue::Single(val) = config_value.try_into_single().await? else {
// An error happened, which has already been converted into an issue.
return Ok(ProcessPostCssResult {
content: AssetContent::File(FileContent::NotFound.cell()).cell(),
assets: Vec::new(),
}
.cell());
};
let processed_css: PostCssProcessingResult = parse_json_with_source_context(val.to_str()?)
.context("Unable to deserializate response from PostCSS transform operation")?;
// TODO handle SourceMap
let file = File::from(processed_css.css);
let assets = emitted_assets_to_virtual_sources(processed_css.assets);
let content = AssetContent::File(FileContent::Content(file).cell()).cell();
Ok(ProcessPostCssResult { content, assets }.cell())
}
}
#[turbo_tasks::value]
struct PostCssTransformIssue {
source: Vc<FileSystemPath>,
description: String,
severity: Vc<IssueSeverity>,
title: String,
}
#[turbo_tasks::value_impl]
impl Issue for PostCssTransformIssue {
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.source
}
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text(self.title.to_string()).cell()
}
#[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(
StyledString::Text(self.description.to_string()).cell(),
))
}
#[turbo_tasks::function]
fn severity(&self) -> Vc<IssueSeverity> {
self.severity
}
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::Transform.cell()
}
}