🔧 修复工具依赖分析问题:新增分析阶段mock require

## 🎯 解决的问题
- 修复工具代码在分析阶段因require失败导致getDependencies()无法调用的问题
- 工具的第一行require('axios')失败时,整个脚本执行中断,module.exports未被设置

## 🔧 实现方案
- 新增createAnalysisRequire()方法,为分析阶段提供mock require
- 内置模块(path、fs等)使用真实require,第三方模块返回Proxy mock对象
- 执行阶段继续使用createSmartRequire()进行真实依赖解析

##  修复效果
-  分析阶段:axios/cheerio被正确mock,脚本完整执行
-  依赖提取:getDependencies()正常调用,返回['axios@^1.6.0', 'cheerio@^1.0.0-rc.12']
-  工具实例化:module.exports正确设置,工具对象创建成功

## 🧪 测试验证
-  heywhale-activity-scraper工具依赖分析成功
-  mock require日志正常输出
-  后续依赖安装准备完成

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
sean
2025-07-05 14:45:51 +08:00
parent 487f02ef03
commit e1bd961ff1

View File

@ -480,7 +480,7 @@ class ToolSandbox {
return { return {
require: supportDependencies ? require: supportDependencies ?
this.createSmartRequire(sandboxPath) : this.createSmartRequire(sandboxPath) :
require, this.createAnalysisRequire(),
module: { exports: {} }, module: { exports: {} },
exports: {}, exports: {},
console: console, console: console,
@ -522,6 +522,35 @@ class ToolSandbox {
}; };
} }
/**
* 创建分析阶段的mock require
* 让所有require调用都成功脚本能完整执行到module.exports
* @returns {Function} mock require函数
*/
createAnalysisRequire() {
return (moduleName) => {
// Node.js内置模块使用真实require
const builtinModules = ['path', 'fs', 'url', 'crypto', 'util', 'os', 'events', 'stream'];
try {
// 检查是否是内置模块
if (builtinModules.includes(moduleName) || moduleName.startsWith('node:')) {
return require(moduleName);
}
} catch (e) {
// 内置模块加载失败继续mock处理
}
// 第三方模块返回通用mock对象
console.log(`[ToolSandbox] 分析阶段mock模块: ${moduleName}`);
return new Proxy({}, {
get: () => () => ({}), // 所有属性和方法都返回空函数/对象
apply: () => ({}), // 如果被当作函数调用
construct: () => ({}) // 如果被当作构造函数
});
};
}
/** /**
* 创建支持依赖解析的require函数 * 创建支持依赖解析的require函数
* @param {string} sandboxPath - 沙箱路径 * @param {string} sandboxPath - 沙箱路径