diff --git a/Cargo.lock b/Cargo.lock index 8c43d4591..f8bb032f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1178,7 +1178,6 @@ name = "clash-verge-config-render" version = "0.1.0" dependencies = [ "clash-verge-logging", - "clash-verge-profile-script", "log", "serde", "serde_json", diff --git a/crates/clash-verge-config-render/Cargo.toml b/crates/clash-verge-config-render/Cargo.toml index 66d2120cc..93a947d51 100644 --- a/crates/clash-verge-config-render/Cargo.toml +++ b/crates/clash-verge-config-render/Cargo.toml @@ -4,7 +4,6 @@ version = "0.1.0" edition = "2024" [dependencies] -clash-verge-profile-script = { workspace = true } clash-verge-logging = { workspace = true } log = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/crates/clash-verge-config-render/src/lib.rs b/crates/clash-verge-config-render/src/lib.rs index 5234c18cc..6f45871e9 100644 --- a/crates/clash-verge-config-render/src/lib.rs +++ b/crates/clash-verge-config-render/src/lib.rs @@ -22,6 +22,7 @@ use std::sync::Arc; use tristr::alias::String; pub type ResultLog = Vec<(String, String)>; +pub type ScriptOutcome = (Result, ResultLog); pub const ITEM_SCRIPT: &str = "// Define main function (script entry) @@ -79,14 +80,14 @@ pub struct RenderedConfig { pub discarded_keys: Vec, } -async fn process_override_items( +async fn process_override_items + Send>( mut config: Mapping, mut exists_keys: Vec, mut result_map: HashMap, - merge_item: Arc, - script_item: Arc, + (merge_item, script_item): (Arc, Arc), profile_name: &str, authoritative: &AuthoritativeFields, + execute_script: &(impl Fn(String, serde_json::Value, String) -> Fut + Sync), ) -> (Mapping, Vec, HashMap) { if let ChainType::Merge(merge) = &merge_item.data { exists_keys.extend(use_keys(merge)); @@ -104,7 +105,8 @@ async fn process_override_items( if let ChainType::Script(script) = &script_item.data { let before = authoritative.current(&config); - let (res_config, changed_keys, mut logs) = use_script(script.clone(), config, profile_name.into()).await; + let (res_config, changed_keys, mut logs) = + use_script(script.clone(), config, profile_name.into(), execute_script).await; exists_keys.extend(changed_keys); config = res_config; logs.extend( @@ -633,7 +635,12 @@ fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, M (config, applied) } -pub async fn render(profile: RenderProfile, settings: RenderSettings, dns_config: Option) -> RenderedConfig { +pub async fn render + Send>( + profile: RenderProfile, + settings: RenderSettings, + dns_config: Option, + execute_script: impl Fn(String, serde_json::Value, String) -> Fut + Send + Sync, +) -> RenderedConfig { let RenderSettings { clash_config, enable_tun, @@ -687,10 +694,10 @@ pub async fn render(profile: RenderProfile, settings: RenderSettings, dns_config config, exists_keys, result_map, - global_merge, - global_script, + (global_merge, global_script), profile_name.as_str(), &authoritative, + &execute_script, ) .await; @@ -698,10 +705,10 @@ pub async fn render(profile: RenderProfile, settings: RenderSettings, dns_config config, exists_keys, result_map, - merge_item, - script_item, + (merge_item, script_item), profile_name.as_str(), &authoritative, + &execute_script, ) .await; @@ -1178,16 +1185,23 @@ mod authoritative_field_tests { #[cfg(test)] mod tests { use super::{ - AuthoritativeFields, ChainItem, ChainType, Mapping, cleanup_proxy_groups, ensure_lan_bind_address, - process_override_items, use_keys, + AuthoritativeFields, ChainItem, ChainType, Mapping, ScriptOutcome, String, cleanup_proxy_groups, + ensure_lan_bind_address, process_override_items, use_keys, }; use std::collections::HashMap; + use std::future::{Ready, ready}; use std::sync::Arc; fn mapping(yaml: &str) -> serde_yaml_ng::Mapping { serde_yaml_ng::from_str(yaml).expect("test config should be valid") } + fn apply_script_fixture(script: String, input: serde_json::Value, _: String) -> Ready { + let mut config: Mapping = serde_json::from_value(input).expect("script input should be a mapping"); + config.extend(mapping(script.as_str())); + ready((Ok(config), vec![])) + } + #[tokio::test] async fn dns_settings_override_only_filled_fields_after_merge_and_script() { let profile = mapping( @@ -1203,18 +1217,11 @@ mod tests { "dns: {ipv6: false, nameserver-policy: {merge.example: 1.1.1.1}}\n\ hosts: {merge.example: 192.0.2.3}", ); - let script = r#"function main(config) { - config.dns = { - ipv6: false, - nameserver: ["4.4.4.4"], - "nameserver-policy": {"script.example": "4.4.4.4"}, - "proxy-server-nameserver": ["4.4.4.4"], - fallback: ["4.4.4.4"], - listen: "127.0.0.1:1053" - }; - config.hosts = {"script.example": "192.0.2.4"}; - return config; - }"#; + let script = r#"dns: {ipv6: false, nameserver: ["4.4.4.4"], + nameserver-policy: {script.example: "4.4.4.4"}, + proxy-server-nameserver: ["4.4.4.4"], fallback: ["4.4.4.4"], + listen: "127.0.0.1:1053"} +hosts: {script.example: "192.0.2.4"}"#; for enabled in [false, true] { let (config, dns_settings) = if enabled { @@ -1234,26 +1241,32 @@ mod tests { config, vec![], HashMap::new(), - merge_item("global-merge"), - Arc::new(ChainItem { - uid: "global-script".into(), - data: ChainType::Script(script.into()), - }), + ( + merge_item("global-merge"), + Arc::new(ChainItem { + uid: "global-script".into(), + data: ChainType::Script(script.into()), + }), + ), profile_name, &authoritative, + &apply_script_fixture, ) .await; let (config, _, logs) = process_override_items( config, keys, logs, - merge_item("profile-merge"), - Arc::new(ChainItem { - uid: "profile-script".into(), - data: ChainType::Script(script.into()), - }), + ( + merge_item("profile-merge"), + Arc::new(ChainItem { + uid: "profile-script".into(), + data: ChainType::Script(script.into()), + }), + ), profile_name, &authoritative, + &apply_script_fixture, ) .await; let manual = config.clone(); @@ -1300,14 +1313,9 @@ mod tests { let global_script = Arc::new(ChainItem { uid: "Script".into(), data: ChainType::Script( - r#"function main(config) { - config["global-script-wins"] = "global-script"; - config["profile-merge-wins"] = "global-script"; - config["profile-script-wins"] = "global-script"; - config.nested.winner = "global-script"; - return config; - }"# - .into(), + r"{global-script-wins: global-script, profile-merge-wins: global-script, + profile-script-wins: global-script, nested: {winner: global-script}}" + .into(), ), }); let profile_merge = Arc::new(ChainItem { @@ -1319,14 +1327,7 @@ mod tests { }); let profile_script = Arc::new(ChainItem { uid: "profile-script".into(), - data: ChainType::Script( - r#"function main(config) { - config["profile-script-wins"] = "profile-script"; - config.nested.winner = "profile-script"; - return config; - }"# - .into(), - ), + data: ChainType::Script(r"{profile-script-wins: profile-script, nested: {winner: profile-script}}".into()), }); let profile_name = "test-profile"; @@ -1335,20 +1336,20 @@ mod tests { config, exists_keys, HashMap::new(), - global_merge, - global_script, + (global_merge, global_script), profile_name, &authoritative, + &apply_script_fixture, ) .await; let (config, exists_keys, _) = process_override_items( config, exists_keys, result_map, - profile_merge, - profile_script, + (profile_merge, profile_script), profile_name, &authoritative, + &apply_script_fixture, ) .await; diff --git a/crates/clash-verge-config-render/src/script.rs b/crates/clash-verge-config-render/src/script.rs index ffabad583..46254aad1 100644 --- a/crates/clash-verge-config-render/src/script.rs +++ b/crates/clash-verge-config-render/src/script.rs @@ -1,12 +1,16 @@ -use super::field::use_lowercase; -use clash_verge_profile_script::{ScriptLogs, execute}; +use super::{ResultLog, ScriptOutcome, field::use_lowercase}; use serde_yaml_ng::Mapping; use tristr::alias::String; -type ScriptResult = (Mapping, Vec, ScriptLogs); +type ScriptResult = (Mapping, Vec, ResultLog); /// Never fails: exceptions are logged and the input config is returned unchanged. -pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult { +pub(super) async fn use_script + Send>( + script: String, + config: Mapping, + name: String, + execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send, +) -> ScriptResult { // The template is identity-plus-lowercasing; skip the Boa round-trip. if script == super::ITEM_SCRIPT { return (use_lowercase(config), vec![], vec![]); @@ -50,3 +54,28 @@ pub(super) async fn use_script(script: String, config: Mapping, name: String) -> } } } + +#[cfg(test)] +mod tests { + use std::future::ready; + + use super::{Mapping, use_script}; + + #[tokio::test] + async fn default_template_skips_the_executor() { + let mut called = false; + let mut config = Mapping::new(); + config.insert("MiXeD".into(), true.into()); + let (config, changed_keys, logs) = + use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| { + called = true; + ready((Ok(Mapping::new()), vec![])) + }) + .await; + + assert!(!called); + assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true)); + assert!(changed_keys.is_empty()); + assert!(logs.is_empty()); + } +} diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index 7112df0ea..674863efe 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -281,7 +281,13 @@ pub(crate) async fn enhance( exists_keys, logs, discarded_keys, - } = render(inputs.profile, inputs.settings, inputs.dns_config).await; + } = render( + inputs.profile, + inputs.settings, + inputs.dns_config, + clash_verge_profile_script::execute, + ) + .await; notify_discarded_keys(discarded_keys); (config, exists_keys, logs, inputs.dns_override) }