Skip to content

Commit

Permalink
Forward tsconfig transformer options (#9910)
Browse files Browse the repository at this point in the history
  • Loading branch information
MonicaOlejniczak authored Aug 13, 2024
1 parent 4abdb26 commit d840801
Show file tree
Hide file tree
Showing 23 changed files with 461 additions and 312 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 0 additions & 25 deletions crates/node-bindings/src/transformer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,6 @@ use napi::JsObject;
use napi::JsUnknown;
use napi_derive::napi;

use parcel_core::plugin::{
InitialAsset, RunTransformContext, TransformationInput, TransformerPlugin,
};
use parcel_plugin_transformer_js::ParcelJsTransformerPlugin;

use parcel_napi_helpers::anyhow_to_napi;

#[napi]
pub fn _testing_run_parcel_js_transformer_plugin(
target_path: String,
env: Env,
) -> napi::Result<JsUnknown> {
let mut transformer = ParcelJsTransformerPlugin::new();
let mut context = RunTransformContext::default();
let input = TransformationInput::InitialAsset(InitialAsset {
file_path: target_path.into(),
..Default::default()
});
let result = transformer
.transform(&mut context, input)
.map_err(anyhow_to_napi)?;
let result = env.to_js_value(&result)?;
Ok(result)
}

#[napi]
pub fn transform(opts: JsObject, env: Env) -> napi::Result<JsUnknown> {
let config: parcel_js_swc_core::Config = env.from_js_value(opts)?;
Expand Down
4 changes: 4 additions & 0 deletions crates/parcel/src/parcel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,11 @@ impl Parcel {
config,
PluginContext {
config: Arc::clone(&config_loader),
file_system: self.fs.clone(),
options: Arc::new(PluginOptions {
core_path: self.options.core_path.clone(),
env: self.options.env.clone(),
log_level: self.options.log_level.clone(),
mode: self.options.mode.clone(),
project_root: self.project_root.clone(),
}),
Expand Down
18 changes: 13 additions & 5 deletions crates/parcel/src/plugins/config_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ impl Plugins for ConfigPlugins {
}

if transformer.package_name == "@parcel/transformer-js" {
transformers.push(Box::new(ParcelJsTransformerPlugin::new()));
transformers.push(Box::new(ParcelJsTransformerPlugin::new(&self.ctx)?));
continue;
}

Expand Down Expand Up @@ -305,13 +305,21 @@ mod tests {

#[test]
fn returns_transformers() {
let transformers = config_plugins(make_test_plugin_context())
let pipeline = config_plugins(make_test_plugin_context())
.transformers(Path::new("a.ts"), None)
.expect("Not to panic");

assert_eq!(
format!("{:?}", transformers),
r"TransformerPipeline { transformers: [ParcelJsTransformerPlugin] }"
)
format!("{:?}", pipeline),
format!(
"{:?}",
TransformerPipeline {
transformers: vec![Box::new(
ParcelJsTransformerPlugin::new(&make_test_plugin_context()).unwrap()
)],
hash: 1
}
)
);
}
}
55 changes: 29 additions & 26 deletions crates/parcel/src/requests/asset_graph_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ mod test {

use tracing::Level;

use parcel_core::types::Code;
use parcel_core::types::{Code, ParcelOptions};
use parcel_filesystem::in_memory_file_system::InMemoryFileSystem;
use parcel_filesystem::FileSystem;

Expand Down Expand Up @@ -449,55 +449,59 @@ console.log('hello world');

#[test]
fn test_asset_graph_request_with_a_couple_of_entries() {
let _ = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(Level::TRACE)
.try_init();

let mut options = RequestTrackerTestOptions::default();
let fs = InMemoryFileSystem::default();
#[cfg(not(target_os = "windows"))]
let temporary_dir = PathBuf::from("/parcel_tests");
#[cfg(target_os = "windows")]
let temporary_dir = PathBuf::from("C:\\windows\\parcel_tests");

let core_path = temporary_dir.join("parcel_core");
let fs = InMemoryFileSystem::default();

fs.create_directory(&temporary_dir).unwrap();
fs.set_current_working_directory(&temporary_dir); // <- resolver is broken without this
options
.parcel_options
.entries
.push(temporary_dir.join("entry.js").to_str().unwrap().to_string());
options.project_root = temporary_dir.clone();
options.search_path = temporary_dir.clone();
options.parcel_options.core_path = temporary_dir.clone().join("parcel_core");
fs.set_current_working_directory(&temporary_dir);

fs.write_file(
&temporary_dir.join("entry.js"),
String::from(
r#"
import {x} from './a';
import {y} from './b';
console.log(x + y);
import {x} from './a';
import {y} from './b';
console.log(x + y);
"#,
),
);

fs.write_file(
&temporary_dir.join("a.js"),
String::from(
r#"
export const x = 15;
export const x = 15;
"#,
),
);

fs.write_file(
&temporary_dir.join("b.js"),
String::from(
r#"
export const y = 27;
export const y = 27;
"#,
),
);
setup_core_modules(&fs, &options.parcel_options.core_path);
options.fs = Arc::new(fs);

let mut request_tracker = request_tracker(options);
setup_core_modules(&fs, &core_path);

let mut request_tracker = request_tracker(RequestTrackerTestOptions {
fs: Arc::new(fs),
parcel_options: ParcelOptions {
core_path,
entries: vec![temporary_dir.join("entry.js").to_str().unwrap().to_string()],
..ParcelOptions::default()
},
project_root: temporary_dir.clone(),
search_path: temporary_dir.clone(),
..RequestTrackerTestOptions::default()
});

let asset_graph_request = AssetGraphRequest {};
let RequestResult::AssetGraph(asset_graph_request_result) = request_tracker
Expand Down Expand Up @@ -529,11 +533,10 @@ export const y = 27;
let transformer_path = core_path
.join("node_modules")
.join("@parcel/transformer-js");
let source_path = transformer_path.join("src");
fs.create_directory(&source_path).unwrap();

fs.write_file(&transformer_path.join("package.json"), String::from("{}"));
fs.write_file(
&source_path.join("esmodule-helpers.js"),
&transformer_path.join("src").join("esmodule-helpers.js"),
String::from("/* helpers */"),
);
}
Expand Down
22 changes: 4 additions & 18 deletions crates/parcel/src/requests/asset_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use parcel_core::plugin::AssetBuildEvent;
use parcel_core::plugin::BuildProgressEvent;
use parcel_core::plugin::InitialAsset;
use parcel_core::plugin::ReporterEvent;
use parcel_core::plugin::RunTransformContext;
use parcel_core::plugin::TransformResult;
use parcel_core::plugin::TransformationInput;
use parcel_core::types::Asset;
Expand Down Expand Up @@ -65,11 +64,6 @@ impl Request for AssetRequest {
.and_then(|s| s.to_str())
.unwrap_or(""),
);
let mut transform_ctx = RunTransformContext::new(
request_context.file_system().clone(),
request_context.options.clone(),
request_context.project_root.clone(),
);

let result = run_pipeline(
pipeline,
Expand All @@ -82,7 +76,6 @@ impl Request for AssetRequest {
}),
asset_type,
request_context.plugins().clone(),
&mut transform_ctx,
)?;

Ok(ResultAndInvalidations {
Expand All @@ -105,9 +98,8 @@ impl Request for AssetRequest {
fn run_pipeline(
mut pipeline: TransformerPipeline,
input: TransformationInput,
asset_type: FileType,
file_type: FileType,
plugins: PluginsRef,
transform_ctx: &mut RunTransformContext,
) -> anyhow::Result<TransformResult> {
let mut dependencies = vec![];
let mut invalidations = vec![];
Expand All @@ -116,8 +108,8 @@ fn run_pipeline(

let pipeline_hash = pipeline.hash();
for transformer in &mut pipeline.transformers {
let transform_result = transformer.transform(transform_ctx, transform_input)?;
let is_different_asset_type = transform_result.asset.asset_type != asset_type;
let transform_result = transformer.transform(transform_input)?;
let is_different_asset_type = transform_result.asset.file_type != file_type;

transform_input = TransformationInput::Asset(transform_result.asset);

Expand All @@ -126,13 +118,7 @@ fn run_pipeline(
let next_pipeline = plugins.transformers(transform_input.file_path(), None)?;

if next_pipeline.hash() != pipeline_hash {
return run_pipeline(
next_pipeline,
transform_input,
asset_type,
plugins,
transform_ctx,
);
return run_pipeline(next_pipeline, transform_input, file_type, plugins);
};
}

Expand Down
12 changes: 9 additions & 3 deletions crates/parcel/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::path::PathBuf;
use std::sync::Arc;

use parcel_config::parcel_config_fixtures::default_config;
use parcel_core::types::BuildMode;
use parcel_core::{
config_loader::ConfigLoader,
plugin::{PluginContext, PluginLogger, PluginOptions},
Expand All @@ -16,12 +15,15 @@ use crate::{
};

pub(crate) fn make_test_plugin_context() -> PluginContext {
let fs = Arc::new(InMemoryFileSystem::default());

PluginContext {
config: Arc::new(ConfigLoader {
fs: Arc::new(InMemoryFileSystem::default()),
fs: fs.clone(),
project_root: PathBuf::default(),
search_path: PathBuf::default(),
}),
file_system: fs.clone(),
options: Arc::new(PluginOptions::default()),
logger: PluginLogger::default(),
}
Expand Down Expand Up @@ -71,8 +73,12 @@ pub(crate) fn request_tracker(options: RequestTrackerTestOptions) -> RequestTrac
let plugins = plugins.unwrap_or_else(|| {
config_plugins(PluginContext {
config: Arc::clone(&config_loader),
file_system: fs.clone(),
options: Arc::new(PluginOptions {
mode: BuildMode::default(),
core_path: parcel_options.core_path.clone(),
env: parcel_options.env.clone(),
log_level: parcel_options.log_level.clone(),
mode: parcel_options.mode.clone(),
project_root: project_root.clone(),
}),
logger: PluginLogger::default(),
Expand Down
14 changes: 10 additions & 4 deletions crates/parcel_core/src/plugin.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

Expand All @@ -17,6 +18,7 @@ mod packager_plugin;
pub use packager_plugin::*;

mod reporter_plugin;
use parcel_filesystem::FileSystemRef;
pub use reporter_plugin::*;

mod resolver_plugin;
Expand All @@ -31,20 +33,24 @@ pub use transformer_plugin::*;
mod validator_plugin;
pub use validator_plugin::*;

use crate::config_loader::ConfigLoader;
use crate::types::BuildMode;
use crate::config_loader::{ConfigLoader, ConfigLoaderRef};
use crate::types::{BuildMode, LogLevel};

pub struct PluginContext {
pub config: Arc<ConfigLoader>,
pub options: Arc<PluginOptions>,
pub config: ConfigLoaderRef,
pub file_system: FileSystemRef,
pub logger: PluginLogger,
pub options: Arc<PluginOptions>,
}

#[derive(Default)]
pub struct PluginLogger {}

#[derive(Debug, Default)]
pub struct PluginOptions {
pub core_path: PathBuf,
pub env: Option<HashMap<String, String>>,
pub log_level: LogLevel,
pub mode: BuildMode,
pub project_root: PathBuf,
}
Loading

0 comments on commit d840801

Please sign in to comment.