refactor(profile): extract script validation and execution

Share the Boa validation and execution API while preserving the save-side timeout and diagnostics.
This commit is contained in:
Tunglies
2026-11-30 18:13:50 +08:00
parent 96c926c33f
commit b232c4506d
6 changed files with 290 additions and 19 deletions
+5 -18
View File
@@ -16,6 +16,7 @@ use crate::core::handle;
use crate::singleton;
use crate::utils::{dirs, help};
use clash_verge_logging::{Type, logging};
use clash_verge_profile_script::MainDeclaration;
const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
@@ -255,22 +256,8 @@ impl CoreConfigValidator {
};
logging!(debug, Type::Validate, "验证脚本文件: {}", path);
let has_main =
content.contains("function main") || content.contains("const main") || content.contains("let main");
// Boa parsing is pure CPU; keep it off the async worker, with a timeout.
let syntax = crate::process::AsyncHandler::spawn_blocking(move || {
use boa_engine::{Context, Source};
let mut context = Context::default();
let _ = context.eval(Source::from_bytes(
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});",
));
context
.eval(Source::from_bytes(&content))
.map(|_| ())
.map_err(|err| err.to_string())
});
let syntax =
crate::process::AsyncHandler::spawn_blocking(move || clash_verge_profile_script::validate(&content));
let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await {
Ok(Ok(evaluated)) => evaluated,
Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")),
@@ -278,10 +265,10 @@ impl CoreConfigValidator {
};
match result {
Ok(()) => {
Ok(main) => {
logging!(debug, Type::Validate, "脚本语法验证通过: {}", path);
if !has_main {
if main == MainDeclaration::Missing {
let error_msg = "Script must contain a main function";
logging!(warn, Type::Validate, "脚本缺少main函数: {}", path);
return Ok(ValidationOutcome::invalid_from_message(error_msg));