Skip to content

Commit 795fedc

Browse files
authored
feat(plugin/runner): Support pluginEnvVars (#10318)
**Description:** > Currently, `WasiEnvBuilder` clones a lot to pass environment variables to Wasm. I think it should get environment variables from the host dynamically. Any plan to support it? _Originally posted by @kdy1 in [#9668](#9668 (comment) I think this is possible, we can manually add envs to `WasiEnvBuilder` by `add_env`. So I finsh a rough implementation. More suggestions are welcome. .swcrc ```json { "jsc": { "experimental": { "plugins": [["./my_first_plugin.wasm", {}]], "pluginEnvVars": ["BUILD_REPOSITORY_NAME"] } } } ``` plugin.rs ```rs #[plugin_transform] pub fn process_transform(program: Program, _metadata: TransformPluginProgramMetadata) -> Program { for env in std::env::vars() { println!("{}: {}", env.0, env.1); } program } ``` **Related issue:** - Closes #9668
1 parent ddbf3e1 commit 795fedc

File tree

12 files changed

+41
-2
lines changed

12 files changed

+41
-2
lines changed

.changeset/forty-spoons-hug.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
swc_plugin_runner: major
3+
---
4+
5+
feat(plugin/runner): Support pluginEnvVars

crates/swc/src/config/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,7 @@ impl Options {
608608

609609
Box::new(crate::plugin::plugins(
610610
experimental.plugins,
611+
experimental.plugin_env_vars,
611612
transform_metadata_context,
612613
comments.cloned(),
613614
cm.clone(),
@@ -1202,6 +1203,8 @@ pub struct JscExperimental {
12021203
/// This requires cargo feature `plugin`.
12031204
#[serde(default)]
12041205
pub plugins: Option<Vec<PluginConfig>>,
1206+
#[serde(default)]
1207+
pub plugin_env_vars: Option<Vec<Atom>>,
12051208
/// If true, keeps import assertions in the output.
12061209
#[serde(default, alias = "keepImportAssertions")]
12071210
pub keep_import_attributes: BoolConfig<false>,

crates/swc/src/plugin.rs

+6
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use std::path::PathBuf;
1010

1111
use anyhow::{Context, Result};
12+
use atoms::Atom;
1213
use common::FileName;
1314
use serde::{Deserialize, Serialize};
1415
use swc_common::errors::HANDLER;
@@ -34,13 +35,15 @@ pub struct PluginConfig(pub String, pub serde_json::Value);
3435

3536
pub fn plugins(
3637
configured_plugins: Option<Vec<PluginConfig>>,
38+
plugin_env_vars: Option<Vec<Atom>>,
3739
metadata_context: std::sync::Arc<swc_common::plugin::metadata::TransformPluginMetadataContext>,
3840
comments: Option<swc_common::comments::SingleThreadedComments>,
3941
source_map: std::sync::Arc<swc_common::SourceMap>,
4042
unresolved_mark: swc_common::Mark,
4143
) -> impl Pass {
4244
fold_pass(RustPlugins {
4345
plugins: configured_plugins,
46+
plugin_env_vars: plugin_env_vars.map(std::sync::Arc::new),
4447
metadata_context,
4548
comments,
4649
source_map,
@@ -50,6 +53,7 @@ pub fn plugins(
5053

5154
struct RustPlugins {
5255
plugins: Option<Vec<PluginConfig>>,
56+
plugin_env_vars: Option<std::sync::Arc<Vec<Atom>>>,
5357
metadata_context: std::sync::Arc<swc_common::plugin::metadata::TransformPluginMetadataContext>,
5458
comments: Option<swc_common::comments::SingleThreadedComments>,
5559
source_map: std::sync::Arc<swc_common::SourceMap>,
@@ -125,11 +129,13 @@ impl RustPlugins {
125129
.get_fs_cache_root()
126130
.map(std::path::PathBuf::from),
127131
);
132+
128133
let mut transform_plugin_executor =
129134
swc_plugin_runner::create_plugin_transform_executor(
130135
&self.source_map,
131136
&self.unresolved_mark,
132137
&self.metadata_context,
138+
self.plugin_env_vars.clone(),
133139
plugin_module_bytes,
134140
Some(p.1),
135141
runtime,

crates/swc/src/wasm_analysis.rs

+1
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ impl Compiler {
149149
&self.cm,
150150
&unresolved_mark,
151151
transform_metadata_context,
152+
None,
152153
plugin_module_bytes,
153154
Some(p.1.clone()),
154155
runtime,

crates/swc_plugin_runner/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ virtual-fs = { workspace = true }
6464
wasmer = { workspace = true }
6565
wasmer-wasix = { workspace = true }
6666

67+
swc_atoms = { version = "5.0.0", path = '../swc_atoms' }
6768
swc_common = { version = "8.0.1", path = "../swc_common", features = [
6869
"concurrent",
6970
] }
@@ -80,7 +81,6 @@ wasmer-compiler-cranelift = { version = "=5.0.5-rc1", default-features = false }
8081
codspeed-criterion-compat = { workspace = true }
8182
criterion = { workspace = true }
8283

83-
swc_atoms = { version = "5.0.0", path = '../swc_atoms' }
8484
swc_css_ast = { version = "8.0.0", path = "../swc_css_ast", features = [
8585
"rkyv-impl",
8686
] }

crates/swc_plugin_runner/benches/ecma_invoke.rs

+1
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ fn bench_transform(b: &mut Bencher, plugin_dir: &Path) {
9595
"development".to_string(),
9696
None,
9797
)),
98+
None,
9899
Box::new(plugin_module.clone()),
99100
None,
100101
None,

crates/swc_plugin_runner/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ pub fn create_plugin_transform_executor(
2525
source_map: &Arc<SourceMap>,
2626
unresolved_mark: &swc_common::Mark,
2727
metadata_context: &Arc<TransformPluginMetadataContext>,
28+
plugin_env_vars: Option<Arc<Vec<swc_atoms::Atom>>>,
2829
plugin_module: Box<dyn PluginModuleBytes>,
2930
plugin_config: Option<serde_json::Value>,
3031
runtime: Option<Arc<dyn wasmer_wasix::Runtime + Send + Sync>>,
@@ -34,6 +35,7 @@ pub fn create_plugin_transform_executor(
3435
source_map,
3536
unresolved_mark,
3637
metadata_context,
38+
plugin_env_vars,
3739
plugin_config,
3840
runtime,
3941
)
@@ -44,6 +46,7 @@ pub fn create_plugin_transform_executor(
4446
source_map: &Arc<SourceMap>,
4547
unresolved_mark: &swc_common::Mark,
4648
metadata_context: &Arc<TransformPluginMetadataContext>,
49+
plugin_env_vars: Option<Arc<Vec<swc_atoms::Atom>>>,
4750
plugin_module: Box<dyn PluginModuleBytes>,
4851
plugin_config: Option<serde_json::Value>,
4952
runtime: Option<()>,

crates/swc_plugin_runner/src/transform_executor.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ pub struct TransformExecutor {
176176
source_map: Arc<SourceMap>,
177177
unresolved_mark: swc_common::Mark,
178178
metadata_context: Arc<TransformPluginMetadataContext>,
179+
plugin_env_vars: Option<Arc<Vec<swc_atoms::Atom>>>,
179180
plugin_config: Option<serde_json::Value>,
180181
module_bytes: Box<dyn PluginModuleBytes>,
181182
runtime: Option<Arc<dyn Runtime + Send + Sync>>,
@@ -192,6 +193,7 @@ impl TransformExecutor {
192193
source_map: &Arc<SourceMap>,
193194
unresolved_mark: &swc_common::Mark,
194195
metadata_context: &Arc<TransformPluginMetadataContext>,
196+
plugin_env_vars: Option<Arc<Vec<swc_atoms::Atom>>>,
195197
plugin_config: Option<serde_json::Value>,
196198
runtime: Option<Arc<dyn Runtime + Send + Sync>>,
197199
) -> Self {
@@ -208,6 +210,7 @@ impl TransformExecutor {
208210
source_map: source_map.clone(),
209211
unresolved_mark: *unresolved_mark,
210212
metadata_context: metadata_context.clone(),
213+
plugin_env_vars,
211214
plugin_config,
212215
module_bytes,
213216
runtime,
@@ -289,14 +292,22 @@ impl TransformExecutor {
289292
// - should we support this?
290293
// - can we limit to allowlisted input / output only?
291294
// - should there be a top-level config from .swcrc to manually override this?
292-
let wasi_env_builder = if let Ok(cwd) = env::current_dir() {
295+
let mut wasi_env_builder = if let Ok(cwd) = env::current_dir() {
293296
builder
294297
.fs(default_fs_backing())
295298
.map_dirs(vec![("/cwd".to_string(), cwd)].drain(..))?
296299
} else {
297300
builder
298301
};
299302

303+
if let Some(env_vars) = self.plugin_env_vars.as_ref() {
304+
for env in env_vars.iter() {
305+
if let Ok(value) = env::var(env.as_str()) {
306+
wasi_env_builder.add_env(env.as_str(), value);
307+
}
308+
}
309+
}
310+
300311
//create the `WasiEnv`
301312
let mut wasi_env = wasi_env_builder.finalize(&mut store)?;
302313

crates/swc_plugin_runner/tests/css_rkyv.rs

+3
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ fn invoke(input: PathBuf) {
107107
"development".to_string(),
108108
Some(experimental_metadata),
109109
)),
110+
None,
110111
Box::new(PLUGIN_BYTES.clone()),
111112
Some(json!({ "pluginConfig": "testValue" })),
112113
None,
@@ -159,6 +160,7 @@ fn invoke(input: PathBuf) {
159160
"development".to_string(),
160161
Some(experimental_metadata.clone()),
161162
)),
163+
None,
162164
Box::new(PLUGIN_BYTES.clone()),
163165
Some(json!({ "pluginConfig": "testValue" })),
164166
None,
@@ -177,6 +179,7 @@ fn invoke(input: PathBuf) {
177179
"development".to_string(),
178180
Some(experimental_metadata),
179181
)),
182+
None,
180183
Box::new(PLUGIN_BYTES.clone()),
181184
Some(json!({ "pluginConfig": "testValue" })),
182185
None,

crates/swc_plugin_runner/tests/ecma_integration.rs

+2
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ fn internal() {
140140
"development".to_string(),
141141
Some(experimental_metadata),
142142
)),
143+
None,
143144
Box::new(PLUGIN_BYTES.clone()),
144145
Some(json!({ "pluginConfig": "testValue" })),
145146
None,
@@ -214,6 +215,7 @@ fn internal() {
214215
"development".to_string(),
215216
Some(experimental_metadata),
216217
)),
218+
None,
217219
Box::new(PLUGIN_BYTES.clone()),
218220
Some(json!({ "pluginConfig": "testValue" })),
219221
None,

crates/swc_plugin_runner/tests/ecma_rkyv.rs

+3
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ fn internal(input: PathBuf) {
116116
"development".to_string(),
117117
Some(experimental_metadata),
118118
)),
119+
None,
119120
Box::new(PLUGIN_BYTES.clone()),
120121
Some(json!({ "pluginConfig": "testValue" })),
121122
None,
@@ -174,6 +175,7 @@ fn internal(input: PathBuf) {
174175
"development".to_string(),
175176
Some(experimental_metadata.clone()),
176177
)),
178+
None,
177179
Box::new(PLUGIN_BYTES.clone()),
178180
Some(json!({ "pluginConfig": "testValue" })),
179181
None,
@@ -192,6 +194,7 @@ fn internal(input: PathBuf) {
192194
"development".to_string(),
193195
Some(experimental_metadata),
194196
)),
197+
None,
195198
Box::new(PLUGIN_BYTES.clone()),
196199
Some(json!({ "pluginConfig": "testValue" })),
197200
None,

crates/swc_plugin_runner/tests/issues.rs

+1
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ fn issue_6404() -> Result<(), Error> {
116116
"development".to_string(),
117117
Some(experimental_metadata),
118118
)),
119+
None,
119120
Box::new(plugin_module),
120121
Some(json!({ "pluginConfig": "testValue" })),
121122
None,

0 commit comments

Comments
 (0)