Merge pull request #146 from yunyingk/fix/codex-review-findings
CI / validate (push) Has been cancelled
CI / validate (push) Has been cancelled
fix: 修复工作流、身份与 CLI 的 Codex 审查问题
This commit is contained in:
44 files changed
+3317
-667
No files matched your search
Vendored
+574
-562
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
||||
Bundled 356 modules in 32ms
|
||||
|
||||
server.js 3.1 MB (entry point)
|
||||
|
||||
✓ Successfully bundled MCP server: /Users/yingqing/.codex/worktrees/f55d/hose-use/dist/mcp/server.js
|
||||
$ node scripts/build-plugin.mjs
|
||||
Whitespace-only changes.
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"corpId": "ID01ofWoOC1wiX",
|
||||
"corpName": "沈玥妍测试企业",
|
||||
"readOnly": true,
|
||||
"checks": [
|
||||
{
|
||||
"name": "workflow-list",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"count": 14
|
||||
},
|
||||
{
|
||||
"name": "workflow-detail",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"taskCount": 4
|
||||
},
|
||||
{
|
||||
"name": "workflow-analyze",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"summary": {
|
||||
"total": 1,
|
||||
"hardBlocks": 0,
|
||||
"softAdvices": 1,
|
||||
"passed": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "workflow-has-error",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"count": 0
|
||||
},
|
||||
{
|
||||
"name": "platform-schema",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"entityCount": 2,
|
||||
"fieldCount": 6
|
||||
},
|
||||
{
|
||||
"name": "bill-trace-legacy-option",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"found": true,
|
||||
"billCode": "B26000022",
|
||||
"compatibilityNotice": true,
|
||||
"sameResultAsWithoutFlag": true,
|
||||
"baselineExitCode": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
$ tsc --noEmit
|
||||
@@ -0,0 +1,70 @@
|
||||
# 2026-10-25 Codex GitHub 审查意见修复完成报告
|
||||
|
||||
日期:2026-10-25(Asia/Shanghai)。分支:`fix/codex-review-findings`。修复基线:`main@0f164b6`。
|
||||
|
||||
## 交付结果
|
||||
|
||||
最近 10 个 PR 中的 16 条已核实意见均已落实对应修复或明确的兼容处置。通过 3 个子智能体分别实现工作流、接口身份、CLI,并由主控整合和最终复核;独立交叉审查额外发现并修正了 JWT 非法管理员值的归一化问题,真实测试企业回归又发现并修正了 JSON 脱敏破坏布尔标记的问题。
|
||||
|
||||
最终 `bun test` 为 **842 pass / 0 fail,108 个测试文件,3986 次断言**;`bun run check` 通过;插件构建成功;源码与重建插件的离线执行契约测试通过。真实接口只在**沈玥妍测试企业**读取既有数据,未创建、提交、审批、修改或删除真实业务数据。
|
||||
|
||||
本次从主分支选择性复用旧 `fix/review-20261023` 的集合转换和引用扫描思路,没有合并旧提交中单据创建、复制、校验等其他修改。旧分支保持原状;以后合入时应单独审查重叠文件。
|
||||
|
||||
## 逐项实际修改及行为差异
|
||||
|
||||
| 编号 / 原评论 | 实际修改与原因 | 修复前 → 修复后 |
|
||||
|---|---|---|
|
||||
| R01 [#142 file 别名](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311509) | [node.ts](../../src/cli/commands/workflow/node.ts):edit 的映射别名移除 file,保留 mapping-file/mapping/json-file,恢复原有代码别名 | edit --file=script.js 被 JSON.parse 拒绝 → 按代码文件读取;独立 node map --file 继续读映射 |
|
||||
| R02 [#142 完整构造器名](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311517) | [mvel-subset.ts](../../src/domains/platform/workflow/script/mvel-subset.ts)、[sandbox.ts](../../src/domains/platform/workflow/script/sandbox.ts):按 token 精确识别零参 java.util.HashMap/ArrayList,避免全文替换影响字面量 | java 未定义 → 与已有短名得到一致 Map/List 结果;其他构造器明确不支持 |
|
||||
| R03 [#142 末尾表达式](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311526) | [mvel-subset.ts](../../src/domains/platform/workflow/script/mvel-subset.ts)、[lint-mvel.ts](../../src/domains/platform/workflow/script/lint-mvel.ts):识别可确定的最后顶层表达式,单次 return 求值,lint 接受此语义 | result; 成功但 undefined → 返回真实结果;复杂末项完成值明确报 UnsupportedMvelSyntax |
|
||||
| R04 [#142 Map.size](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311532) | [mvel-subset.ts](../../src/domains/platform/workflow/script/mvel-subset.ts):Map/List helper 区分自身键数和元素数,处理嵌套调用及方法返回值 | 一个键的 Map 得 undefined → 得 1;覆盖同键不增加计数,length/原型名称键也正确 |
|
||||
| R05 [#142 嵌套摘要](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311540) | [shared.ts](../../src/cli/commands/workflow/shared.ts):默认复用现有 flattenExecutionTree,保持 test/job 相同容器语义 | 条件/循环内代码节点摘要缺失 → 展开并保留每次执行,不按名称去重 |
|
||||
| R06 [#139 发票超时](https://github.com/yunyingk/hose-use/pull/139#discussion_r4347394125) | [bill/api.ts](../../src/domains/bill/api.ts)、[tools.ts](../../src/domains/bill/tools.ts):可选 signal、retry:0、逐票 3 秒整体 deadline、abort 与 finally 清理 | 提前返回后请求/计时器仍存活 → 请求和响应体可被取消,计时器必清;迟到结果不污染返回字典 |
|
||||
| R07 [#139 无效发票参数](https://github.com/yunyingk/hose-use/pull/139#discussion_r4347394145) | [search.ts](../../src/cli/commands/bill/search.ts)、[metadata](../../src/cli/command-metadata.ts)、[flow.ts](../../src/cli/commands/flow.ts):旧参数保留接受、明确兼容空操作并给 stderr 提示;SDK 兼容签名保留 | 假装参数控制详情加载 → 说明 trace 本身不补充发票详情;结果 JSON/退出码保持一致,不增加网络补全 |
|
||||
| R08 [#139 物理字段键](https://github.com/yunyingk/hose-use/pull/139#discussion_r4347394152) | [app-info.ts](../../src/cli/commands/platform/app-info.ts):文本物理列改为 fieldKey ?? name | name 与 fieldKey 不同时误导复制 → 显示真实物理键;JSON 原字段保持原样 |
|
||||
| R09 [#145 表单容器](https://github.com/yunyingk/hose-use/pull/145#discussion_r4358575334) | [analyzer.ts](../../src/domains/platform/workflow/analysis/analyzer.ts):覆盖 inputs/fields/mapping/form 及对象/数组组合,明确字段条目只扫 value | 直接 form、inputs.form 漏检 → 与普通 fields 得到一致诊断;脚本、条目 label/type 元信息不扫描 |
|
||||
| R10 [#145 choose 表示](https://github.com/yunyingk/hose-use/pull/145#discussion_r4358575344) | [analyzer.ts](../../src/domains/platform/workflow/analysis/analyzer.ts):解析 JSON、单双引号/裸路径、多标签、转义;按明确节点/上下文/未知来源分类 | 非 JSON 形式静默跳过 → 缺失明确节点硬阻断,body 等非 descriptor 上下文保留;未知根/畸形表达式软提示 |
|
||||
| R11 [#145 trigger_1](https://github.com/yunyingk/hose-use/pull/145#discussion_r4358575352) | [analyzer.ts](../../src/domains/platform/workflow/analysis/analyzer.ts):删除固定豁免,统一依赖真实节点索引 | 缺失 trigger_1 仍 passed → 缺失阻断、实际存在通过;不自动替换成其他触发器 |
|
||||
| R12 [#136 业务错误](https://github.com/yunyingk/hose-use/pull/136#discussion_r4335138930) | [platform/api.ts](../../src/domains/platform/api.ts)、[pipeline-watcher.ts](../../src/domains/platform/workflow/watch/pipeline-watcher.ts):共用业务错误检查先于列表归一化,watcher 两处 running 鉴权异常重抛 | code:401/data:null 被当[] → AuthenticationError;成功空值/单对象/数组兼容不变,CLI 不再把该鉴权错误当零任务成功 |
|
||||
| R13 [#136 在途错误](https://github.com/yunyingk/hose-use/pull/136#discussion_r4335138939) | [history.ts](../../src/cli/commands/workflow/history.ts):拆开含错与终态谓词,错误列优先显示明确错误 | RUNNING+errorTaskCount>0 被 --has-error 排除 → 保留;state 过滤和计数维持既有兼容行为 |
|
||||
| R14 [#136 未知状态](https://github.com/yunyingk/hose-use/pull/136#discussion_r4335138947) | [job.ts](../../src/cli/commands/workflow/job.ts):四处状态展示共用已知/未知判断 | detail 不可读显示已停用 → 显示未知,保留可用 job/tree;JSON 不捏造 workflow |
|
||||
| R15 [#135 保存 key 回填](https://github.com/yunyingk/hose-use/pull/135#discussion_r4334533782) | [assist services.ts](../../src/domains/assist-platform/services.ts):只回填实际保存目录、同 id/物理企业中完整保留的 key 对 | 磁盘有 keys、运行态没有 → 返回配置/CLI hasOpenApi 与磁盘一致;不恢复旧员工/token/session,不读取其他目录 keys |
|
||||
| R16 [#135 画像完整度](https://github.com/yunyingk/hose-use/pull/135#discussion_r4334533792) | [assist services.ts](../../src/domains/assist-platform/services.ts)、[link-import.ts](../../src/core/auth/link-import.ts):本次确认 boolean admin 后重算缺项与风险,源头严格解析 JWT | 已确认 false 仍不完整 → 清除仅 admin 缺项;null/unknown 等不再被伪装成 false;历史高风险及员工隔离保留 |
|
||||
|
||||
对应的模块 README、内嵌 skill、CLI 帮助均已更新;[插件产物](../../dist/mcp/server.js)从构建生成,包含最终源码和内嵌说明,没有手工修改 bundle。
|
||||
|
||||
## 关键兼容取舍与方案偏差
|
||||
|
||||
1. `node edit --file=<mapping.json>` 的近期调用需要改为 --mapping-file 或 node map --file;恢复的是更早已存在的代码文件别名,不根据扩展名猜用途。
|
||||
2. trace 的旧发票参数被明确为兼容空操作;没有为制造开关效果而新增发票加载。回退单据检索仍可能查 invoice/search,不宣传完全无发票相关请求。
|
||||
3. MVEL 保留原有除法、三元、classic for 等兼容运算。Map.put/get/add 由同组 helper 明确返回语义;不支持的语法从可能静默错算改为明确失败。仍是 QuickJS 子集,不是原生 MVEL/JVM。
|
||||
4. 未知裸 choose 根保持软提示,明确 descriptor 节点键及标准前缀缺失才硬阻断;不会为提高“检出数量”而把所有路径当节点。此处不是完整上游可访问作用域和字段类型分析。
|
||||
5. 两项必要关联修正比初始文件清单增加了范围:独立复核发现 JWT null/unknown 被旧 link-import 转成 false,故收紧其归一化;真实 B26000022 回归发现旧文本脱敏把 keepItSecret:false 改为裸 <redacted> 导致非法 JSON,故在 [printer.ts](../../src/cli/printer.ts) 对完整 JSON 按类型脱敏。凭据字符串、数字及 URL/Bearer 继续遮蔽,业务 boolean/null 和 NDJSON 单行得到保留;普通文本原规则保持。两项均由复现驱动,没有扩大成认证结构或输出协议重构。
|
||||
6. 共享 HTTP 工厂、保存 API 返回类型、state 筛选兼容语义与业务写流程没有重构;原有注释随迁移保留,旧审查证据未覆盖改写。
|
||||
|
||||
## 实际验证
|
||||
|
||||
| 验证 | 实际结果与证据 |
|
||||
|---|---|
|
||||
| 完整测试 | **842 pass / 0 fail,108 文件,3986 断言,9.57 秒**;[完整日志](./2026-10-25-codex-review-evidence/tests.log) |
|
||||
| 类型检查 | `bun run check` exit 0;[日志](./2026-10-25-codex-review-evidence/typecheck.log) |
|
||||
| 插件构建 | `bun run build:plugin` 成功,356 模块,3.1MB;[日志](./2026-10-25-codex-review-evidence/build.log) |
|
||||
| 分发物执行 | [plugin-review-smoke.test.ts](../../scripts/plugin-review-smoke.test.ts)在隔离假企业配置中实际运行源码 CLI 和重建 bundle,验证全限定名集合、Map.size、末尾对象返回、JS 保持及 UnsupportedMvelSyntax 非零退出码;包含在全量测试中 |
|
||||
| 架构边界 | 仓库 architecture-boundaries 测试包含在全量测试中,通过 |
|
||||
| Diff 检查 | `git diff --check` exit 0;[日志](./2026-10-25-codex-review-evidence/diff-check.log) |
|
||||
| 真实只读回归 | 仅沈玥妍测试企业,显式 --corp/--stateless:工作流列表14项、既有4节点流程详情/静态分析、--has-error日志、schema 2对象6字段、既有单据B26000022 trace;全部exit0且JSON可解析。带/不带--basic的trace结果完全一致;[汇总](./2026-10-25-codex-review-evidence/live-readonly.json) |
|
||||
|
||||
新增回归覆盖真实入口、超时后资源生命周期、body读取、401重放、跨目录keys、非法JWT、角色缺项、dry-run无保存、mock保存、状态筛选、嵌套执行和源码/插件一致性。CLI子组还把新回归放回原始HEAD临时副本验证:原实现出现9项失败,修复后通过,避免测试只重复实现。
|
||||
|
||||
首轮全量测试在受限环境出现回环端口、默认SQLite和企业目录写权限失败,不能算通过。最终执行将所有测试配置/账号/企业文件/SQLite隔离到临时目录,并允许本地回环测试后取得以上全绿结果;没有为测试放开真实企业写权限,也未修改你的日常企业配置。
|
||||
|
||||
## 未覆盖及复查重点
|
||||
|
||||
- 真实回归没有发起 Job、创建或提交单据、修改协助身份、发布工作流。401/403、挂起、旧key、字段缺失和非法JWT都用离线mock制造。
|
||||
- 真实 --has-error 样本返回空列表,故在途含错筛选、不可读工作流详情等负面场景由mock证明;未借此宣称所有真实Job状态已覆盖。
|
||||
- 本地 MVEL 不模拟任意 Java 方法、Map字面量、精确JVM数值或末项复合语句完成值;运行错误位置仍来自转换后代码,未实现源位置映射。合思原生引擎特殊语义未在本轮执行验证。
|
||||
- 单票取消信号不撤销已开始的独立认证续期,也不能强制停止忽略AbortSignal的自定义fetch;整体等待及迟到结果隔离有测试覆盖。
|
||||
- 其他 watcher catch、严格FAILED字面语义、schema底层state默认值、gen-props物理键契约、旧分支其他单据修复不在本次扩大。
|
||||
- 重点复查MVEL支持边界、choose未知根软提示、keys来源目录限制,以及JSON脱敏对业务标记与凭据的区分。未把“没有发现问题”当作完整可靠性证明。
|
||||
|
||||
本次未推送、创建PR、合并main、打tag、发布或更新全局安装,也没有发送GitHub评论、关闭旧审查线程。修复应经后续正常PR流程进入主分支;旧机器人线程状态仍需在代码合入并核对后处理。
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
test("source and committed plugin preserve offline review execution contracts", () => {
|
||||
const root = resolve(import.meta.dir, "..");
|
||||
const temp = mkdtempSync(join(tmpdir(), "hose-review-plugin-"));
|
||||
try {
|
||||
const enterprises = join(temp, "enterprises");
|
||||
mkdirSync(enterprises);
|
||||
writeFileSync(join(enterprises, "smoke.json"), JSON.stringify({
|
||||
id: "smoke", name: "离线测试企业", env: "test",
|
||||
credentials: { accessToken: "synthetic-offline-token", corpId: "smoke", staffId: "staff" },
|
||||
}));
|
||||
const env = {
|
||||
...process.env,
|
||||
HOSE_ENTERPRISES_DIR: enterprises,
|
||||
HOSE_CONFIG_FILE: join(temp, "config.json"),
|
||||
HOSE_ACCOUNTS_FILE: join(temp, "accounts.json"),
|
||||
HOSE_APPROVAL_DB: ":memory:",
|
||||
};
|
||||
const fixtures = [
|
||||
{ name: "collections", type: "code", code: 'Map m = new java.util.HashMap(); m.put("x", 7); m.size();', value: 1 },
|
||||
{ name: "final-expression", type: "code", code: 'Map m = new HashMap(); m.put("x", 7); m;', value: { x: 7 } },
|
||||
{ name: "javascript", type: "code-js2", code: "return 7;", value: 7 },
|
||||
{ name: "unsupported", type: "code", code: "new java.util.Date();", error: "UnsupportedMvelSyntax" },
|
||||
];
|
||||
for (const fixture of fixtures) {
|
||||
const file = join(temp, `${fixture.name}.script`);
|
||||
writeFileSync(file, fixture.code);
|
||||
for (const entry of [["src/cli.ts"], ["dist/mcp/server.js", "--hose-use-cli"]]) {
|
||||
const result = Bun.spawnSync([
|
||||
process.execPath, ...entry, "workflow", "eval-script", "--file", file,
|
||||
"--type", fixture.type, "--corp", "smoke", "--stateless", "--json",
|
||||
], { cwd: root, env, timeout: 10000 });
|
||||
expect(result.exitCode).toBe(fixture.error ? 1 : 0);
|
||||
const report = JSON.parse(result.stdout.toString());
|
||||
expect(report.success).toBe(!fixture.error);
|
||||
if (fixture.error) expect(report.error.name).toBe(fixture.error);
|
||||
else expect(report.returnValue).toEqual(fixture.value);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rmSync(temp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -17,6 +17,12 @@ Generate code for Ekuaibao's modified MVEL 2.x runtime, not JavaScript, Groovy,
|
||||
- For Chinese or dynamic field names, prefer `map.get("字段名")` instead of dot access.
|
||||
- Every `if`, `&&`, and `||` operand must be a strict boolean expression. Never write `if (data)`.
|
||||
|
||||
## Local Evaluation Boundary
|
||||
|
||||
`workflow eval-script` runs a limited MVEL-to-JavaScript subset in isolated QuickJS, not the tenant's JVM engine. It supports zero-argument `HashMap`/`ArrayList` constructors, including `java.util.HashMap`/`java.util.ArrayList`, basic collection methods, explicit return, and a determinable final top-level expression evaluated once. Map size counts own keys; list size counts elements.
|
||||
|
||||
Unsupported constructors, generics, or final compound-statement completion values must be reported as unsupported rather than accepted with an incorrect result. Tenant-proven Map literals, Java methods, and precise JVM numeric behavior may exceed the local subset. Do not rewrite working tenant code merely to satisfy the local evaluator; report the limitation and validate native behavior in an authorized test tenant when needed.
|
||||
|
||||
## Code Node Template
|
||||
|
||||
Use this style when the user has shown bare assignments and final-expression return work:
|
||||
|
||||
@@ -54,6 +54,8 @@ hose-use bill get CL20260903001 --json
|
||||
hose-use bill flow CL20260903001
|
||||
```
|
||||
|
||||
`bill trace` / `flow get` 的穿透诊断不补充加载发票详情。旧参数 `--no-invoice` / `--noInvoice` / `--basic` 仍可传入,但不改变结果,CLI 会通过 stderr 说明;未命中流程时的回退检索仍可能查询发票索引。
|
||||
|
||||
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -247,6 +247,8 @@ hose-use workflow logs <pipelineId> --has-error
|
||||
hose-use workflow logs <pipelineId> --state=FAILED --json
|
||||
```
|
||||
|
||||
`--has-error` 也包含 `RUNNING` / `STARTED` 且已出现错误的任务;`--state` 保留既有终态筛选兼容语义,不替代包含错误筛选,客户端筛选范围为当前返回页。`job` 读取不到工作流详情时显示状态未知;`tail` 的在途任务鉴权失败会返回认证错误,不把它当成没有任务。
|
||||
|
||||
扫描企业内工作流列表中的 `errorCount`,并把已提醒的错误计数保存在本地状态文件;同一错误计数不会重复提醒,错误计数增加时才产生新提醒:
|
||||
|
||||
```bash
|
||||
@@ -328,6 +330,7 @@ hose-use workflow node add <pipelineId> --type=http --label="外部通知" --par
|
||||
|
||||
# 4. 定向修改指定节点配置 (别名: update, set)
|
||||
# 支持修改 --label, --desc, --code, --code-file, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
# edit 的 --file 是代码文件别名;JSON 映射使用 --mapping-file,独立 node map 的 --file 仍表示映射文件
|
||||
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地文件导入脚本
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --yes
|
||||
@@ -373,6 +376,8 @@ hose-use workflow tail <pipelineId> --timeout=60
|
||||
|
||||
合思工作流支持自定义 JavaScript (`code-js2`) 与 MVEL (`code`) 脚本节点。以往只能在生产派发调试 Job 才能验证脚本,不仅污染发布版本快照,还容易因死循环、语法报错或悬空上游节点引发流程中断。`hose-use` 提供了纯本地 AST 语法检查与安全隔离沙箱运行能力:
|
||||
|
||||
MVEL 离线仿真为 QuickJS 转译子集,支持零参 `java.util.HashMap` / `java.util.ArrayList` 和短名、基本集合方法与可确定的末尾表达式;不支持的构造器或完成值会明确报错。原生 MVEL 的其他 Java 方法、集合字面量和 JVM 数值语义仍应以授权测试企业的真实引擎为准,不能把本地成功当作完整兼容保证。工作流调试的代码摘要覆盖嵌套执行实例。
|
||||
|
||||
```bash
|
||||
# 1. 静态扫描整条工作流中所有代码节点的语法、return 语句与上游依赖引用
|
||||
hose-use workflow lint-script <pipelineId>
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
完整 JSON 按值类型脱敏,保留 `keepItSecret` 等布尔业务标记和 null,凭据字符串及数值仍被遮蔽;紧凑 NDJSON 保持单行。普通诊断文本沿用 URL、Bearer 和键值脱敏。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
|
||||
@@ -306,7 +306,8 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容"
|
||||
"--comment=<原因> 驳回或评论内容",
|
||||
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"aliases": [
|
||||
"bills",
|
||||
@@ -350,6 +351,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
"usage": "hose-use flow <子命令> [单号|ID]",
|
||||
"options": [
|
||||
"get/trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"commands": {
|
||||
"get": "穿透诊断单据流转",
|
||||
"history": "查看审批流转时间线",
|
||||
|
||||
@@ -207,20 +207,23 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const skipInvoices = booleanOption(parsed.options, ["no-invoice", "noInvoice", "basic"]);
|
||||
const report = await traceBillFlowDetail(client, corpId, target, { skipInvoices });
|
||||
const legacyInvoiceOption = ["no-invoice", "noInvoice", "basic"].some((key) => Object.hasOwn(parsed.options, key));
|
||||
const compatibilityNotice = legacyInvoiceOption
|
||||
? "提示: --no-invoice/--noInvoice/--basic 仅为旧版兼容参数;穿透诊断不补充加载发票详情,传入这些参数不会改变结果。\n"
|
||||
: "";
|
||||
const report = await traceBillFlowDetail(client, corpId, target);
|
||||
|
||||
if (!report.found) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
stderr: `${compatibilityNotice}[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -235,7 +238,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -294,7 +297,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,7 @@ function printFlowHelp(): string {
|
||||
" --corp=<id> 指定操作企业 (默认激活企业)",
|
||||
" --json 以 JSON 结构化格式输出诊断数据",
|
||||
" --verbose 显示完整调试信息",
|
||||
" --no-invoice/--noInvoice/--basic 旧版兼容空操作;穿透诊断本身不补充加载发票详情",
|
||||
" -h, --help 显示帮助信息",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
: "📝 业务字段";
|
||||
return [
|
||||
entity.name,
|
||||
field.name,
|
||||
field.fieldKey ?? field.name,
|
||||
field.label,
|
||||
field.type,
|
||||
roleTag,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import * as billApi from "../../domains/bill/api.js";
|
||||
import * as cache from "../../core/cache/index.js";
|
||||
import * as session from "../../core/http/session-client.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as workflowShared from "./workflow/shared.js";
|
||||
import * as platformShared from "./platform/shared.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { runCli } from "../runner.js";
|
||||
import { commandFlags } from "../command-metadata.js";
|
||||
import { renderScopedHelp } from "../help.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import { handleNodeCommand } from "./workflow/node.js";
|
||||
import { handleLogs } from "./workflow/history.js";
|
||||
import { handleJob } from "./workflow/job.js";
|
||||
import { handleSchema } from "./platform/app-info.js";
|
||||
import { handleBillCommand } from "./bill/index.js";
|
||||
import { handleFlowCommand } from "./flow.js";
|
||||
|
||||
const runtime = {
|
||||
selectedCorp: { id: "fixture-corp", name: "离线测试企业", credentials: { corpId: "fixture-corp" } },
|
||||
jsonMode: true,
|
||||
} as CliRuntime;
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
const directories: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const spy of spies.splice(0).reverse()) spy.mockRestore();
|
||||
await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("review CLI compatibility regressions", () => {
|
||||
it("keeps real trace-shaped boolean flags valid through runner redaction", async () => {
|
||||
const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: "B-FIXTURE", keepItSecret: false, appSecurity: "fixture-credential" }, plan: { nodes: [] } } };
|
||||
spies.push(spyOn(helpers, "initCorpRuntime").mockReturnValue(runtime as any));
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(raw));
|
||||
const result = await runCli(["bill", "trace", "B-FIXTURE", "--basic", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.raw.flowId.form.keepItSecret).toBe(false);
|
||||
expect(data.raw.flowId.form.appSecurity).toBe("<redacted>");
|
||||
expect(result.stdout).not.toContain("fixture-credential");
|
||||
expect(result.stderr).toContain("旧版兼容参数");
|
||||
});
|
||||
|
||||
it("documents legacy trace flags without dropping them from the parser vocabulary", () => {
|
||||
for (const [area, action] of [["bill", "trace"], ["flow", "get"], ["trace", "get"]]) {
|
||||
const help = renderScopedHelp([area!, action!]);
|
||||
expect(help).toContain("兼容空操作");
|
||||
expect(help).toContain("不补充加载发票详情");
|
||||
const documented = help.split("支持选项:\n")[1]!.split("\n\n提示:")[0]!.trim().split("\n").map((line) => line.trim().match(/^--([^=[\s]+)/)?.[1]);
|
||||
expect(documented).toEqual(Object.keys(commandFlags(area, action)));
|
||||
for (const flag of ["no-invoice", "noInvoice", "basic"]) {
|
||||
expect(commandFlags(area, action)[flag]).toBe("boolean");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("restores edit --file as code while explicit mapping and map --file still work", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "hose-node-options-"));
|
||||
directories.push(dir);
|
||||
const codeFile = join(dir, "script.js");
|
||||
const mappingFile = join(dir, "mapping.json");
|
||||
const code = "// Keep exact bytes.\nreturn 7;\n";
|
||||
await writeFile(codeFile, code);
|
||||
await writeFile(mappingFile, JSON.stringify({ label: "mapped" }));
|
||||
const detail = { id: "wf", state: 0, tasks: [{ name: "action_js", type: "code-js2", label: "original", code: "return 0;" }] };
|
||||
spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any));
|
||||
spies.push(spyOn(services, "getWorkflowDetail").mockResolvedValue(detail as any));
|
||||
const save = spyOn(services, "updateWorkflow").mockImplementation(async (_client, workflow) => workflow);
|
||||
spies.push(save);
|
||||
for (const flag of ["file", "code-file"]) {
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--${flag}=${codeFile}`, "--dry-run"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes.updatedFields.code).toContain(`${code.length} 字符`);
|
||||
}
|
||||
for (const [action, flag] of [["edit", "mapping-file"], ["edit", "mapping"], ["edit", "json-file"], ["map", "file"]]) {
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", action!, "wf", "action_js", `--${flag}=${mappingFile}`, "--dry-run"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes.changedKeys).toContain("label");
|
||||
}
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--file=${codeFile}`, "--yes"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse(result.stdout).editedTask.code).toBe(code);
|
||||
expect((save.mock.calls[0]?.[1]?.tasks?.[0] as any).code).toBe(code);
|
||||
});
|
||||
|
||||
for (const fallback of [false, true]) {
|
||||
it(`keeps legacy trace invoice flags as explicit no-ops (${fallback ? "search fallback" : "direct flow"})`, async () => {
|
||||
const target = fallback ? "流水中文" : "B-FIXTURE";
|
||||
const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: target, details: [{ feeTypeForm: { invoices: [{ invoiceId: "invoice" }] } }] }, plan: { nodes: [] } } };
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockImplementation(async (_client, _corp, query) => fallback && query !== "bill" ? undefined : raw));
|
||||
spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise<unknown>) => loader() } as any));
|
||||
spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([]));
|
||||
const search = spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [{ id: "bill", code: target, form: {} }], total: 1 } as any);
|
||||
spies.push(search);
|
||||
const invoice = spyOn(billApi, "getInvoiceValidationDetail").mockRejectedValue(new Error("must not supplement invoices"));
|
||||
spies.push(invoice);
|
||||
const baseline = await handleBillCommand(parseArgs(["bill", "trace", target]), runtime);
|
||||
expect(baseline.stderr).toBe("");
|
||||
expect(baseline.exitCode).toBe(0);
|
||||
for (const [area, action] of [["bill", "trace"], ["bill", "inspect"], ["flow", "get"], ["flow", "trace"], ["flow", "diagnose"]]) {
|
||||
for (const flag of ["no-invoice", "noInvoice", "basic"]) {
|
||||
for (const value of ["true", "false"]) {
|
||||
const parsed = parseArgs([area!, action!, target, `--${flag}=${value}`]);
|
||||
expect(parsed.options[flag]).toBe(value === "true");
|
||||
const result = await (area === "bill" ? handleBillCommand : handleFlowCommand)(parsed, runtime);
|
||||
expect(result.exitCode).toBe(baseline.exitCode);
|
||||
expect(JSON.parse(result.stdout)).toEqual(JSON.parse(baseline.stdout));
|
||||
expect(result.stderr).toContain("仅为旧版兼容参数");
|
||||
}
|
||||
}
|
||||
}
|
||||
const text = await handleBillCommand(parseArgs(["bill", "trace", target, "--basic"]), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout).toContain("单据全域穿透诊断");
|
||||
expect(text.stderr).toContain("不会改变结果");
|
||||
expect(invoice).not.toHaveBeenCalled();
|
||||
if (fallback) expect(search).toHaveBeenCalled();
|
||||
else expect(search).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
|
||||
it("preserves not-found trace output and status with compatibility notices", async () => {
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise<unknown>) => loader() } as any));
|
||||
spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([]));
|
||||
spies.push(spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [], total: 0 } as any));
|
||||
for (const jsonMode of [false, true]) {
|
||||
const result = await handleBillCommand(parseArgs(["bill", "trace", "missing", "--basic=false"]), { ...runtime, jsonMode });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("旧版兼容参数");
|
||||
if (jsonMode) expect(JSON.parse(result.stdout).found).toBe(false);
|
||||
else expect(result.stderr).toContain("[NOT FOUND]");
|
||||
}
|
||||
});
|
||||
|
||||
it("shows actual physical schema keys, preserves JSON and falls back to name", async () => {
|
||||
const fields = [{ name: "alias_name", fieldKey: "E_REAL_KEY", label: "字段", type: "text" }, { name: "fallback_key", label: "旧字段", type: "text" }];
|
||||
spies.push(spyOn(platformShared, "resolveAppAndEntity").mockResolvedValue({ clients: {}, corpId: "corp", platform: { id: "app", name: "应用" }, entity: { id: "entity", name: "对象", fields } } as any));
|
||||
const args = ["platform", "schema", "app", "entity"];
|
||||
const text = await handleSchema(parseArgs(args), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout).toContain("E_REAL_KEY");
|
||||
expect(text.stdout).toContain("fallback_key");
|
||||
expect(text.stdout).not.toContain("alias_name");
|
||||
const json = JSON.parse((await handleSchema(parseArgs(args), runtime)).stdout);
|
||||
expect(json.entities[0].fields).toEqual(fields);
|
||||
const filtered = JSON.parse((await handleSchema(parseArgs([...args, "--keyword=E_REAL_KEY"]), runtime)).stdout);
|
||||
expect(filtered.entities[0].fields).toEqual([fields[0]]);
|
||||
});
|
||||
|
||||
it("finds in-flight errors without expanding the existing terminal state filters", async () => {
|
||||
const jobs = [
|
||||
{ id: "running-boolean", status: "RUNNING", hasError: true },
|
||||
{ id: "started-string", status: "STARTED", hasError: "true" },
|
||||
{ id: "running-localized", status: "RUNNING", hasError: "存在" },
|
||||
{ id: "started-count", status: "STARTED", errorTaskCount: 1 },
|
||||
{ id: "running-normal", status: "RUNNING", hasError: false, errorTaskCount: 0 },
|
||||
{ id: "started-normal", status: "STARTED", hasError: "不存在" },
|
||||
{ id: "completed-normal", status: "COMPLETED", hasError: "false" },
|
||||
{ id: "completed-skip", status: "COMPLETED", errorTaskCount: 1 },
|
||||
{ id: "failed", status: "FAILED" },
|
||||
];
|
||||
const page = { executeCount: 9, successCount: 2, errorCount: 1, totalItems: 9, jobList: jobs };
|
||||
spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any));
|
||||
const logs = spyOn(services, "listWorkflowLogs").mockResolvedValue(page as any);
|
||||
spies.push(logs, spyOn(services, "getWorkflowDetail").mockRejectedValue(new Error("offline unavailable")));
|
||||
const read = async (flags: string[]) => JSON.parse((await handleLogs(parseArgs(["workflow", "logs", "wf", ...flags]), runtime)).stdout);
|
||||
const errors = await read(["--has-error"]);
|
||||
const expected = ["running-boolean", "started-string", "running-localized", "started-count", "completed-skip", "failed"];
|
||||
expect(errors.jobList.map((j: any) => j.id)).toEqual(expected);
|
||||
expect(errors.totalItems).toBe(9);
|
||||
expect(errors.inProgressCount).toBe(6);
|
||||
expect((await read([])).jobList).toEqual(jobs);
|
||||
expect((await read(["--state=FAILED"])).jobList.map((j: any) => j.id)).toEqual(["completed-skip", "failed"]);
|
||||
expect((await read(["--state=COMPLETED"])).jobList.map((j: any) => j.id)).toEqual(["completed-normal"]);
|
||||
expect((await read(["--state=RUNNING"])).jobList).toEqual(jobs.slice(0, 6));
|
||||
expect((await read(["--state=RUNNING", "--has-error"])).jobList.map((j: any) => j.id)).toEqual(expected);
|
||||
expect(logs.mock.calls.at(-1)?.[2]?.state).toBe("RUNNING");
|
||||
const text = await handleLogs(parseArgs(["workflow", "logs", "wf"]), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout.split("\n").find((line) => line.includes("running-boolean"))).toContain("⚠️ 包含错误");
|
||||
expect(text.stdout.split("\n").find((line) => line.includes("running-normal"))).toContain("⏳ 执行中");
|
||||
});
|
||||
|
||||
for (const state of [undefined, 0, 1, 2]) {
|
||||
it(`reports workflow state truthfully when detail state is ${state ?? "unavailable"}`, async () => {
|
||||
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(services, "getJob").mockResolvedValue({ id: "job", pipelineId: "wf", status: "RUNNING" } as any));
|
||||
spies.push(spyOn(services, "getJobExecutionTree").mockResolvedValue([]));
|
||||
spies.push(spyOn(services, "getJobFailedExecutions").mockResolvedValue({ items: [] } as any));
|
||||
const detail = spyOn(services, "getWorkflowDetail");
|
||||
spies.push(detail);
|
||||
if (state === undefined) detail.mockRejectedValue(new Error("offline detail unavailable"));
|
||||
else detail.mockResolvedValue({ id: "wf", state, tasks: [{ name: "trigger", type: "clock" }] } as any);
|
||||
const expected = state === undefined ? "未知(无法读取工作流详情)" : state === 0 ? "⚪ 已停用" : state === 1 ? "🟢 启用中" : "未知";
|
||||
for (const mode of [[], ["--timeline"]]) {
|
||||
const parsed = parseArgs(["workflow", "job", "job", "--platform=p", ...mode]);
|
||||
const text = await handleJob(parsed, { ...runtime, jsonMode: false });
|
||||
expect(text.exitCode).toBe(0);
|
||||
expect(text.stdout).toContain(expected);
|
||||
if (state !== 0) expect(text.stdout).not.toContain("已停用");
|
||||
const json = JSON.parse((await handleJob(parsed, runtime)).stdout);
|
||||
if (state === undefined) {
|
||||
expect(json.workflow).toBeUndefined();
|
||||
expect(json.job.id).toBe("job");
|
||||
} else if (mode.length) expect(json.workflowState).toBe(expected);
|
||||
else expect(json.workflow.stateLabel).toBe(expected);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -39,18 +39,21 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
});
|
||||
const stateOption = stringOption(parsed.options, ["state"]);
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return false;
|
||||
const hasJobError = (job: any): boolean => {
|
||||
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
||||
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
||||
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
||||
return false;
|
||||
};
|
||||
// Preserve the existing terminal-state filters while --has-error also sees in-flight errors.
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
return s !== "STARTED" && s !== "RUNNING" && hasJobError(job);
|
||||
};
|
||||
|
||||
let filteredJobList = rawResult.jobList;
|
||||
if (hasErrorFilter) {
|
||||
filteredJobList = filteredJobList.filter(isJobError);
|
||||
filteredJobList = filteredJobList.filter(hasJobError);
|
||||
} else if (stateOption) {
|
||||
const norm = stateOption.trim().toUpperCase();
|
||||
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
|
||||
@@ -115,8 +118,8 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
const formatErrorColumn = (job: any): string => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (hasJobError(job)) return "⚠️ 包含错误";
|
||||
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
|
||||
if (isJobError(job)) return "⚠️ 包含错误";
|
||||
return "正常";
|
||||
};
|
||||
|
||||
|
||||
@@ -404,6 +404,13 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
})),
|
||||
]);
|
||||
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
|
||||
const workflowStateLabel = !workflowDetail
|
||||
? "未知(无法读取工作流详情)"
|
||||
: workflowDetail.state === 1
|
||||
? "🟢 启用中"
|
||||
: workflowDetail.state === 0
|
||||
? "⚪ 已停用"
|
||||
: "未知";
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
@@ -451,7 +458,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
jobId,
|
||||
pipelineId: job.pipelineId,
|
||||
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
|
||||
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
workflowState: workflowStateLabel,
|
||||
jobStatus: job.state ?? job.status,
|
||||
totalTasks: timeline.length,
|
||||
executedTasks: tree.length,
|
||||
@@ -480,7 +487,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"工作流状态": workflowStateLabel,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"定义总步骤数": timeline.length,
|
||||
"已调度步骤数": tree.length,
|
||||
@@ -509,7 +516,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
id: workflowDetail.id,
|
||||
name: workflowDetail.pipelineName || workflowDetail.label,
|
||||
state: workflowDetail.state,
|
||||
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
stateLabel: workflowStateLabel,
|
||||
totalTasks: workflowDetail.tasks?.length ?? tree.length,
|
||||
}
|
||||
: undefined,
|
||||
@@ -571,7 +578,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"工作流状态": workflowStateLabel,
|
||||
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { handleWorkflowEvalScript } from "./script.js";
|
||||
|
||||
test("MVEL CLI JSON returns the terminal expression and preserves failure exit codes", async () => {
|
||||
for (const [code, success] of [
|
||||
['Map result = new java.util.HashMap(); result.put("value", 7); result;', true],
|
||||
['new java.util.Date();', false],
|
||||
['if (true) { 7; }', false],
|
||||
] as const) {
|
||||
const result = await handleWorkflowEvalScript(parseArgs(["workflow", "eval-script", "--type", "code", "--code", code, "--json"]), { jsonMode: true } as any);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(result.exitCode).toBe(success ? 0 : 1);
|
||||
expect(report.success).toBe(success);
|
||||
if (success) expect(report.returnValue).toEqual({ value: 7 });
|
||||
else expect(report.error.name).toBe("UnsupportedMvelSyntax");
|
||||
}
|
||||
});
|
||||
@@ -387,7 +387,7 @@ async function handleEditNode(
|
||||
}
|
||||
}
|
||||
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "json-file"]);
|
||||
if (mappingFile) {
|
||||
const fs = await import("fs/promises");
|
||||
const rawContent = await fs.readFile(mappingFile, "utf-8");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
@@ -71,7 +71,7 @@ export function extractCodeNodeSummaries(
|
||||
nodes: Array<any>,
|
||||
flattenExecutionTreeFn?: (nodes: any[]) => any[]
|
||||
): CodeNodeSummary[] {
|
||||
const flattened = flattenExecutionTreeFn ? flattenExecutionTreeFn(nodes) : nodes;
|
||||
const flattened = (flattenExecutionTreeFn ?? flattenExecutionTree)(nodes);
|
||||
const summaries: CodeNodeSummary[] = [];
|
||||
|
||||
for (const node of flattened) {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { extractCodeNodeSummaries } from "./shared.js";
|
||||
import { flattenExecutionTree } from "../../../domains/platform/services.js";
|
||||
|
||||
test("test and job summaries retain nested execution containers and repeated loop executions", () => {
|
||||
const tree = [{ id: "loop", type: "every", children: [
|
||||
{ id: "iteration-1", type: "condition", tasks: [{ id: "a", name: "script", type: "code", output: { count: 3 } }] },
|
||||
{ id: "iteration-2", type: "condition", subTasks: [{ id: "b", name: "script", type: "code-js2", output: [1, 2] }] },
|
||||
{ id: "iteration-3", type: "condition", items: [{ id: "c", name: "script", type: "code", output: 7 }] },
|
||||
] }];
|
||||
const summaries = extractCodeNodeSummaries(tree);
|
||||
expect(summaries.map(item => item.id)).toEqual(["a", "b", "c"]);
|
||||
expect(summaries[0].rawOutput).toEqual({ count: 3 });
|
||||
expect(summaries).toEqual(extractCodeNodeSummaries(tree, flattenExecutionTree as any));
|
||||
});
|
||||
@@ -47,6 +47,21 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(redacted).toContain('"password": "<redacted>"');
|
||||
expect(redacted).toContain('"appSecurity": "<redacted>"');
|
||||
});
|
||||
|
||||
test("保留 JSON 中的业务布尔标记与空值,凭据仍脱敏", () => {
|
||||
const source = { keepItSecret: false, nested: { keepItSecret: true, secret: null }, password: "fixture", clientSecret: "fixture-client", appSecurity: 123 };
|
||||
const output = redactSensitiveText(JSON.stringify(source, null, 2));
|
||||
expect(JSON.parse(output)).toEqual({ keepItSecret: false, nested: { keepItSecret: true, secret: null }, password: "<redacted>", clientSecret: "<redacted>", appSecurity: "<redacted>" });
|
||||
expect(output).not.toContain("fixture");
|
||||
});
|
||||
|
||||
test("结构化脱敏保留单行 NDJSON 和字符串转义", () => {
|
||||
const source = { rows: [{ password: 'quoted "credential"', keepItSecret: false }], url: "https://example.test/?token=fixture-token&corpId=corp", description: "two\nlines" };
|
||||
const output = redactSensitiveText(JSON.stringify(source) + "\n");
|
||||
expect(output.split("\n")).toHaveLength(2);
|
||||
expect(JSON.parse(output)).toEqual({ rows: [{ password: "<redacted>", keepItSecret: false }], url: "https://example.test/?token=<redacted>&corpId=corp", description: "two\nlines" });
|
||||
expect(output).not.toContain("credential");
|
||||
});
|
||||
});
|
||||
|
||||
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
|
||||
|
||||
+27
-1
@@ -13,13 +13,39 @@ export function writeStdoutChunk(chunk: string): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
function redactTextFragments(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
const redactValue = (item: unknown, key = ""): unknown => {
|
||||
// Boolean/null flags such as keepItSecret are business metadata, not credentials.
|
||||
if (item === null || typeof item === "boolean") return item;
|
||||
if (/(?:password|passwd|secret|appSecurity)$/i.test(key)) return "<redacted>";
|
||||
if (typeof item === "string") return redactTextFragments(item);
|
||||
if (Array.isArray(item)) return item.map((child) => redactValue(child));
|
||||
if (typeof item === "object") {
|
||||
return Object.fromEntries(Object.entries(item).map(([name, child]) => [name, redactValue(child, name)]));
|
||||
}
|
||||
return item;
|
||||
};
|
||||
const leading = value.match(/^\s*/)?.[0] || "";
|
||||
const trailing = value.match(/\s*$/)?.[0] || "";
|
||||
// Keep compact NDJSON records on one line and ordinary CLI JSON readable.
|
||||
const multiline = value.trim().includes("\n");
|
||||
let json = JSON.stringify(redactValue(parsed), null, multiline || value.includes(": ") ? 2 : undefined);
|
||||
if (!multiline) json = json.replace(/\n\s*/g, " ");
|
||||
return leading + json + trailing;
|
||||
} catch {
|
||||
return redactTextFragments(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
|
||||
if (options.allowFull || options.outputFile) return;
|
||||
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||
|
||||
@@ -281,8 +281,10 @@ export async function importCredentials(
|
||||
if (payload.cellphone) {
|
||||
cellphone = payload.cellphone;
|
||||
}
|
||||
if (payload.isAdmin !== undefined) {
|
||||
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||
if (typeof payload.isAdmin === "boolean") {
|
||||
isAdmin = payload.isAdmin;
|
||||
} else if (payload.isAdmin === "true" || payload.isAdmin === "false") {
|
||||
isAdmin = payload.isAdmin === "true";
|
||||
}
|
||||
if (payload.sourceChannel) {
|
||||
sourceChannel = payload.sourceChannel;
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
- 导入默认沿用底层最佳努力 OpenAPI 密钥提取:无密钥、无读取权限或存在多个密钥均不阻止有效临时会话保存。SDK 显式 `elevate: true` 仍要求成功提取密钥,`elevate: false` 跳过提取。
|
||||
- 身份画像输出可选的 `profileComplete` / `unavailableFields`,配置 `session` 对应保存可选的 `identityComplete` / `identityUnavailableFields`;旧配置仍可读取。员工、管理员标记、角色、权限或部门查询缺失时,完整度为 false;未知的 `isAdmin` / `isSeniorExecutive` 为 null,缺乏已知高风险证据时 `riskLevel` 为 `UNKNOWN`,不会假装 `NORMAL`。
|
||||
- 已知管理员、角色或高权限证据仍显示 HIGH/MEDIUM;导入时补用 JWT 已确认的身份。同一员工的历史权限及高风险状态不会因本次探测不完整而被降级,其他员工的画像不会被沿用。
|
||||
- 本次会话/JWT 确认当前员工的管理员布尔值后,清除对应的 `admin` 缺失项并重新计算完整度,再分析风险;`false` 同样是已知值。仅有历史画像时不冒充本次查询成功,其他缺失字段继续保留。
|
||||
- 新会话未取得 OpenAPI 密钥时,返回配置仅回填本次实际保存目录、同企业文件中已保留的完整密钥对,使运行态与磁盘一致;已有新密钥优先。不从其他目录恢复密钥,也不恢复旧员工的 Token、身份或会话。
|
||||
|
||||
SDK 消费者应处理画像布尔值的 null 和新增的 UNKNOWN 风险枚举;会话结果顶层 `isAdmin` 仍表示请求的授权模式,其 boolean 类型不变。
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||
import { loadCorpConfigs, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { loadCorpConfigs, resolveWritableEnterprisesDir, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
approveAssistTicketApi,
|
||||
@@ -360,6 +360,17 @@ export async function importAssistSessionToLocal(
|
||||
.find((corp) => corp.id === sessionResult.corporationId);
|
||||
const corpConfig = await importFromLink(linkToImport, importOptions);
|
||||
|
||||
// 保存层可能保留目标文件中的旧密钥;仅同步这对已保存凭证,不恢复旧员工会话。
|
||||
if (!corpConfig.credentials.appKey) {
|
||||
const savedCorp = loadCorpConfigs([importOptions.enterprisesDir || resolveWritableEnterprisesDir()])
|
||||
.find((corp) => corp.id === corpConfig.id &&
|
||||
(corp.corpId || corp.credentials.corpId) === (corpConfig.corpId || corpConfig.credentials.corpId));
|
||||
if (savedCorp?.credentials.appKey && savedCorp.credentials.appSecurity) {
|
||||
corpConfig.credentials.appKey = savedCorp.credentials.appKey;
|
||||
corpConfig.credentials.appSecurity = savedCorp.credentials.appSecurity;
|
||||
}
|
||||
}
|
||||
|
||||
// 注入完整身份画像与角色权限风控元数据并保存落盘
|
||||
if (sessionResult.identity) {
|
||||
const ident = sessionResult.identity;
|
||||
@@ -380,6 +391,13 @@ export async function importAssistSessionToLocal(
|
||||
ident.staffId = corpConfig.credentials.staffId || ident.staffId;
|
||||
ident.staffName = corpConfig.session?.staffName || ident.staffName;
|
||||
}
|
||||
if (Array.isArray(ident.unavailableFields)) {
|
||||
// 只有本次会话对当前员工的确认能补齐缺项,历史风险证据不代表本次查询成功。
|
||||
if (typeof corpConfig.session?.isAdmin === "boolean" && ident.staffId === corpConfig.credentials.staffId) {
|
||||
ident.unavailableFields = ident.unavailableFields.filter((field) => field !== "admin");
|
||||
}
|
||||
ident.profileComplete = ident.unavailableFields.length === 0;
|
||||
}
|
||||
Object.assign(ident, analyzeStaffRoleRisk(ident));
|
||||
// 同一员工的历史高风险证据不能因本次探测不完整而被降级。
|
||||
if (ident.profileComplete === false && previousSession?.riskLevel) {
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import ky from "ky";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import type { CorpConfig, CorpSessionInfo } from "../../core/config/types.js";
|
||||
import { saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { handleEnter } from "../../cli/commands/assist-platform/enter.js";
|
||||
import { parseArgs } from "../../cli/parser.js";
|
||||
import * as api from "./api.js";
|
||||
import * as services from "./services.js";
|
||||
import type { AssistIdentityProfile } from "./types.js";
|
||||
|
||||
interface FixtureOptions {
|
||||
meAdmin?: boolean | null;
|
||||
jwtAdmin?: unknown;
|
||||
omitJwtAdmin?: boolean;
|
||||
rolesUnavailable?: boolean;
|
||||
permissionsUnavailable?: boolean;
|
||||
newKeys?: boolean;
|
||||
}
|
||||
|
||||
describe("assist session import credentials and identity", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const envNames = ["HOSE_ENTERPRISES_DIR", "HOSE_USER_ENTERPRISES_DIR", "HOSE_CONFIG_FILE", "HOSE_ASSIST_PLATFORM_FILE"] as const;
|
||||
let oldEnv: Record<string, string | undefined>;
|
||||
let root: string;
|
||||
let target: string;
|
||||
let other: string;
|
||||
let spies: Array<{ mockRestore(): void }>;
|
||||
|
||||
beforeEach(() => {
|
||||
oldEnv = Object.fromEntries(envNames.map((name) => [name, process.env[name]]));
|
||||
root = mkdtempSync(join(tmpdir(), "hose-assist-import-"));
|
||||
target = join(root, "target");
|
||||
other = join(root, "other");
|
||||
mkdirSync(target);
|
||||
mkdirSync(other);
|
||||
process.env.HOSE_ENTERPRISES_DIR = target;
|
||||
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.HOSE_ASSIST_PLATFORM_FILE = join(root, "assist.json");
|
||||
spies = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) spy.mockRestore();
|
||||
globalThis.fetch = originalFetch;
|
||||
for (const name of envNames) {
|
||||
if (oldEnv[name] === undefined) delete process.env[name];
|
||||
else process.env[name] = oldEnv[name];
|
||||
}
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function oldCorp(staffId = "corp:current", session: CorpSessionInfo = {}): CorpConfig {
|
||||
return {
|
||||
id: "corp", name: "old enterprise", source: "account", accountId: "old-account",
|
||||
baseUrl: "https://old.example",
|
||||
credentials: { corpId: "corp", staffId, accessToken: "old-token", appKey: "saved-key", appSecurity: "saved-secret" },
|
||||
auth: { refreshTtl: 300, refreshToken: "old-refresh" },
|
||||
session,
|
||||
};
|
||||
}
|
||||
|
||||
function fixture(options: FixtureOptions = {}) {
|
||||
const meAdmin = options.meAdmin === undefined ? false : options.meAdmin;
|
||||
const jwtAdmin = options.jwtAdmin === undefined ? false : options.jwtAdmin;
|
||||
globalThis.fetch = (async (input: Request | URL | string, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
const url = request.url;
|
||||
if (url.includes("assistPlatform/getToken")) return Response.json({ value: {
|
||||
token: "new-token", baseUrl: "https://session.example",
|
||||
loginUrl: "https://session.example/web/thirdparty.html?accessToken=new-token&ekbCorpId=corp",
|
||||
} });
|
||||
if (url.includes("organization/staffs/me")) return Response.json({ value: {
|
||||
staff: { id: "corp:current", name: "current employee", ...(meAdmin === null ? {} : { admin: meAdmin }) },
|
||||
...(options.permissionsUnavailable ? {} : { permissions: [] }),
|
||||
} });
|
||||
if (url.endsWith("/roles?corpId=corp")) {
|
||||
return options.rolesUnavailable ? new Response("roles denied", { status: 403 }) : Response.json({ items: [] });
|
||||
}
|
||||
if (url.includes("actions/jwt")) return Response.json({ id: `fixture.${Buffer.from(JSON.stringify({
|
||||
staffId: "corp:current", staffName: "current employee", corporationName: "new enterprise",
|
||||
...(options.omitJwtAdmin ? {} : { isAdmin: jwtAdmin }),
|
||||
})).toString("base64url")}.signature` });
|
||||
if (url.includes("account/v2/session")) return Response.json({ value: {
|
||||
id: "session", corporationId: "corp", loginStaffId: "corp:current", platform: "ASSIST", isShortTermToken: true,
|
||||
} });
|
||||
if (url.includes("innerapi/v1/key")) return options.newKeys
|
||||
? Response.json({ items: [{ id: "new-key-id", appKey: "new-key", appSecurity: "new-secret" }] })
|
||||
: new Response("keys denied", { status: 403 });
|
||||
throw new Error(`Unexpected mock URL: ${url}`);
|
||||
}) as typeof fetch;
|
||||
return ky.create({ prefix: "https://assist.example/api" });
|
||||
}
|
||||
|
||||
function imported(options: FixtureOptions = {}, params: Partial<services.ImportAssistSessionParams> = {}) {
|
||||
return services.importAssistSessionToLocal(fixture(options), { corpId: "corp", ticketId: "ticket", enterprisesDir: target, ...params });
|
||||
}
|
||||
|
||||
function persisted(): CorpConfig {
|
||||
return JSON.parse(readFileSync(join(target, "corp.json"), "utf8"));
|
||||
}
|
||||
|
||||
it("restores only the key pair actually retained by the save operation", async () => {
|
||||
saveCorpConfig(oldCorp("corp:previous", { staffName: "old employee", roles: ["主管理员"], isAdmin: true, riskLevel: "HIGH" }), target);
|
||||
const { corpConfig, sessionResult } = await imported({ meAdmin: null });
|
||||
expect(corpConfig.credentials).toEqual({ corpId: "corp", staffId: "corp:current", accessToken: "new-token", appKey: "saved-key", appSecurity: "saved-secret" });
|
||||
expect(persisted().credentials).toEqual(corpConfig.credentials);
|
||||
expect(corpConfig.accountId).toBeUndefined();
|
||||
expect(corpConfig.auth?.refreshToken).toBeUndefined();
|
||||
expect(corpConfig.baseUrl).toBe("https://session.example");
|
||||
expect(sessionResult.identity?.roleNames).toEqual([]);
|
||||
expect(sessionResult.identity?.isAdmin).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("NORMAL");
|
||||
const runtime = new CorpContext([], { stateful: false });
|
||||
runtime.upsertCorp(corpConfig);
|
||||
expect(runtime.listCorps()[0]).toMatchObject({ staffId: "corp:current", hasOpenApi: true });
|
||||
});
|
||||
|
||||
it("keeps newly acquired keys in preference to the old pair", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
const { corpConfig } = await imported({ newKeys: true });
|
||||
expect(corpConfig.credentials.appKey).toBe("new-key");
|
||||
expect(corpConfig.credentials.appSecurity).toBe("new-secret");
|
||||
expect(persisted().credentials.appKey).toBe("new-key");
|
||||
});
|
||||
|
||||
it("does not invent keys when no pair is saved", async () => {
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBeUndefined();
|
||||
expect(corpConfig.credentials.appSecurity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not restore an incomplete saved pair", async () => {
|
||||
const previous = oldCorp();
|
||||
delete previous.credentials.appSecurity;
|
||||
saveCorpConfig(previous, target);
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBeUndefined();
|
||||
expect(corpConfig.credentials.appSecurity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("restores the legacy auth key pair that the loader already preserves", async () => {
|
||||
const previous = oldCorp();
|
||||
delete previous.credentials.appKey;
|
||||
delete previous.credentials.appSecurity;
|
||||
previous.auth = { refreshTtl: 300, appKey: "legacy-key", appSecurity: "legacy-secret" };
|
||||
writeFileSync(join(target, "corp.json"), JSON.stringify(previous));
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBe("legacy-key");
|
||||
expect(corpConfig.credentials.appSecurity).toBe("legacy-secret");
|
||||
});
|
||||
|
||||
it("does not take keys from a same-id file outside the actual write directory", async () => {
|
||||
saveCorpConfig(oldCorp(), other);
|
||||
process.env.HOSE_ENTERPRISES_DIR = other;
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBeUndefined();
|
||||
expect(persisted().credentials.appKey).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves the default write directory when no explicit directory is supplied", async () => {
|
||||
const previous = oldCorp();
|
||||
previous.credentials.appKey = "other-key";
|
||||
saveCorpConfig(previous, other);
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
process.env.HOSE_USER_ENTERPRISES_DIR = target;
|
||||
// A missing test directory must not override the configured user write directory.
|
||||
writeFileSync(process.env.HOSE_CONFIG_FILE!, JSON.stringify({ testEnterprisesDir: join(root, "missing") }));
|
||||
const { corpConfig } = await imported({}, { enterprisesDir: undefined });
|
||||
expect(corpConfig.credentials.appKey).toBe("saved-key");
|
||||
expect(persisted().credentials.appKey).toBe("saved-key");
|
||||
});
|
||||
|
||||
it("restores saved keys even if no identity profile could be generated", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
spies.push(spyOn(api, "getStaffMeAndRolesApi").mockRejectedValue(new Error("identity unavailable")));
|
||||
const { corpConfig, sessionResult } = await imported();
|
||||
expect(sessionResult.identity).toBeUndefined();
|
||||
expect(corpConfig.credentials.appKey).toBe("saved-key");
|
||||
});
|
||||
|
||||
it("does not bypass overwrite protection", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
await expect(imported({}, { overwrite: false })).rejects.toMatchObject({ name: "AuthenticationError" });
|
||||
expect(persisted().credentials.accessToken).toBe("old-token");
|
||||
});
|
||||
|
||||
for (const admin of [false, true, "false", "true"]) {
|
||||
it(`recomputes completeness when the current JWT confirms admin=${JSON.stringify(admin)}`, async () => {
|
||||
const expectedAdmin = admin === true || admin === "true";
|
||||
const { sessionResult, corpConfig } = await imported({ meAdmin: null, jwtAdmin: admin });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: expectedAdmin, unavailableFields: [], profileComplete: true, riskLevel: expectedAdmin ? "HIGH" : "NORMAL" });
|
||||
expect(corpConfig.session).toMatchObject({ isAdmin: expectedAdmin, identityComplete: true, identityUnavailableFields: [], riskLevel: expectedAdmin ? "HIGH" : "NORMAL" });
|
||||
expect(persisted().session).toEqual(corpConfig.session);
|
||||
});
|
||||
}
|
||||
|
||||
for (const admin of [null, "unknown", "", 0, 1, {}, []]) {
|
||||
it(`does not mistake JWT admin=${JSON.stringify(admin)} for a confirmed non-admin`, async () => {
|
||||
const { sessionResult, corpConfig } = await imported({ meAdmin: null, jwtAdmin: admin });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: null, unavailableFields: ["admin"], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
expect(corpConfig.session?.isAdmin).toBeUndefined();
|
||||
expect(persisted().session).toMatchObject({ identityComplete: false, identityUnavailableFields: ["admin"], riskLevel: "UNKNOWN" });
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps an omitted JWT admin unknown", async () => {
|
||||
const { sessionResult } = await imported({ meAdmin: null, omitJwtAdmin: true });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: null, unavailableFields: ["admin"], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
});
|
||||
|
||||
it("does not treat other missing fields as complete after JWT admin recovery", async () => {
|
||||
const { sessionResult } = await imported({ meAdmin: null, rolesUnavailable: true, permissionsUnavailable: true });
|
||||
expect(sessionResult.identity?.unavailableFields).toEqual(["permissions", "roles"]);
|
||||
expect(sessionResult.identity?.profileComplete).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("does not turn historical admin evidence into a successful current query", async () => {
|
||||
saveCorpConfig(oldCorp("corp:current", { isAdmin: false }), target);
|
||||
const { sessionResult } = await imported({ meAdmin: null, jwtAdmin: null });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: false, unavailableFields: ["admin"], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
});
|
||||
|
||||
it("preserves a same-employee high risk while the new profile remains incomplete", async () => {
|
||||
saveCorpConfig(oldCorp("corp:current", { isAdmin: true, riskLevel: "HIGH" }), target);
|
||||
const { sessionResult } = await imported({ meAdmin: null, rolesUnavailable: true });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: false, unavailableFields: ["roles"], profileComplete: false, riskLevel: "HIGH", isSeniorExecutive: true });
|
||||
});
|
||||
|
||||
it("does not inherit another employee's historical admin, roles or risk", async () => {
|
||||
saveCorpConfig(oldCorp("corp:previous", { isAdmin: true, roles: ["主管理员"], permissions: ["SYS_ADMIN"], riskLevel: "HIGH" }), target);
|
||||
const { sessionResult } = await imported({ meAdmin: null, jwtAdmin: null, rolesUnavailable: true, permissionsUnavailable: true });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: null, roleNames: [], permissions: [], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
});
|
||||
|
||||
it("does not assume legacy profiles without a missing-field array are complete", async () => {
|
||||
const identity: AssistIdentityProfile = {
|
||||
staffId: "corp:current", staffName: "current employee", isAdmin: null, profileComplete: false,
|
||||
roles: [], roleNames: [], permissions: [], readablePermissions: [],
|
||||
isSeniorExecutive: null, seniorTitles: [], riskLevel: "UNKNOWN",
|
||||
};
|
||||
spies.push(spyOn(services, "inspectAssistIdentity").mockResolvedValue(identity));
|
||||
const { sessionResult } = await imported();
|
||||
expect(sessionResult.identity?.unavailableFields).toBeUndefined();
|
||||
expect(sessionResult.identity?.profileComplete).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("does not clear missing admin for a profile belonging to a different employee", async () => {
|
||||
spies.push(spyOn(services, "inspectAssistIdentity").mockResolvedValue({
|
||||
staffId: "corp:other", staffName: "other employee", isAdmin: null, profileComplete: false,
|
||||
unavailableFields: ["admin"], roles: [], roleNames: [], permissions: [], readablePermissions: [],
|
||||
isSeniorExecutive: null, seniorTitles: [], riskLevel: "UNKNOWN",
|
||||
}));
|
||||
const { sessionResult } = await imported();
|
||||
expect(sessionResult.identity?.unavailableFields).toEqual(["admin"]);
|
||||
expect(sessionResult.identity?.profileComplete).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("reports saved keys consistently in CLI JSON and the runtime context", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
fixture({ meAdmin: null });
|
||||
const corpContext = new CorpContext([], { stateful: false });
|
||||
const result = await handleEnter(parseArgs(["assist-platform", "enter", "corp", "--save", "--yes", "--overwrite", "--ticket=ticket", "--token=fixture-operator"]), {
|
||||
jsonMode: true, corpContext,
|
||||
} as any);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).enterprise.hasOpenApi).toBe(true);
|
||||
expect(corpContext.getCorp("corp")?.credentials.appKey).toBe("saved-key");
|
||||
expect(result.stdout).not.toContain("saved-secret");
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,7 @@ src/domains/bill/
|
||||
- 内置待办根因诊断引擎,智能判定流转阶段(`DRAFT`、`APPROVING`、`PAYING`、`PAID`、`REJECTED`):
|
||||
- 按实际流程状态(如 `PAYING`)和节点类型判断支付阶段,显示名称不参与阶段判定;流程状态优先于 backlog 状态。缺少当前身份的实际待办证据时,`diagnostic.canApprove` 为 `null`,CLI 显示“未知”,节点配置中的审批人不构成权限保证;
|
||||
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
|
||||
- 穿透诊断不执行发票详情补全;`--no-invoice` / `--noInvoice` / `--basic` 继续接受为兼容空操作,显式使用时通过 stderr 说明,JSON stdout 与结果不变。未命中流程时的单据回退检索仍可能查询发票索引,这些参数不保证跳过该检索。
|
||||
|
||||
9. **草稿派生字段校验 (`validateBillDraft` / `assertBillDraftValid`)**:
|
||||
- 合思服务端把金额/币种/发票总额等派生字段的计算责任交给前端,保存接口只做弱校验
|
||||
@@ -109,3 +110,9 @@ POST /api/v1/flow/plans/computed
|
||||
- 提交/撤回等破坏性动作只在测试企业验证,生产环境禁止演练。
|
||||
|
||||
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
|
||||
## 翻译上下文的发票读取预算
|
||||
|
||||
`getTranslatorContext` 的单张发票补全有 3 秒整体预算,包含请求和响应体读取。超时会取消该票请求,成功或失败都会清理计时器;单票失败不影响其他票和整体翻译,迟到结果不再写入返回字典。发票 GET 显式关闭普通自动重试,`getInvoiceValidationDetail` 的可选第四参数可传入 `signal`,原三参数调用保持兼容。
|
||||
|
||||
共享客户端的鉴权重放保留取消信号;已经开始的独立凭据续期不受该单票信号控制。自定义传输若忽略 AbortSignal,整体等待仍受预算限制,但无法保证强制中止其内部操作。
|
||||
@@ -565,11 +565,14 @@ export async function listEntitySchemas(
|
||||
export async function getInvoiceValidationDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
invoiceId: string
|
||||
invoiceId: string,
|
||||
options: { signal?: AbortSignal } = {}
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const response = await client.get(`api/v2/invoice/validation/$${encodeURIComponent(invoiceId)}`, {
|
||||
searchParams: { masterId: invoiceId, corpId }
|
||||
searchParams: { masterId: invoiceId, corpId },
|
||||
signal: options.signal,
|
||||
retry: 0,
|
||||
});
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
import * as api from "./api.js";
|
||||
import * as cache from "../../core/cache/index.js";
|
||||
import * as dimensions from "../dimension/tools.js";
|
||||
import { createAuthClient } from "../../core/http/factory.js";
|
||||
import { getTranslatorContext } from "./tools.js";
|
||||
|
||||
const rawFlow = (ids = ["invoice"]) => ({
|
||||
form: { details: [{ feeTypeForm: { invoices: ids.map((invoiceId) => ({ invoiceId })) } }] },
|
||||
});
|
||||
|
||||
describe("invoice detail cancellation", () => {
|
||||
const realSetTimeout = globalThis.setTimeout;
|
||||
const realClearTimeout = globalThis.clearTimeout;
|
||||
const originalFetch = globalThis.fetch;
|
||||
let spies: Array<{ mockRestore(): void }>;
|
||||
let deadlines: Set<ReturnType<typeof setTimeout>>;
|
||||
let scheduled: number;
|
||||
|
||||
beforeEach(() => {
|
||||
deadlines = new Set();
|
||||
scheduled = 0;
|
||||
spies = [
|
||||
spyOn(api, "getFeeTypeTree").mockResolvedValue([]),
|
||||
spyOn(api, "listActiveStaffCatalog").mockResolvedValue([]),
|
||||
spyOn(api, "getDepartmentTree").mockResolvedValue([]),
|
||||
spyOn(dimensions, "resolveDimension").mockResolvedValue(undefined as any),
|
||||
spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, load: () => unknown) => load() } as any),
|
||||
spyOn(globalThis, "setTimeout").mockImplementation(((callback: (...args: any[]) => void, delay?: number, ...args: any[]) => {
|
||||
const timer = realSetTimeout(callback, delay === 3000 ? 40 : delay, ...args);
|
||||
if (delay === 3000) {
|
||||
scheduled++;
|
||||
deadlines.add(timer);
|
||||
}
|
||||
return timer;
|
||||
}) as typeof setTimeout),
|
||||
spyOn(globalThis, "clearTimeout").mockImplementation(((timer: ReturnType<typeof setTimeout>) => {
|
||||
deadlines.delete(timer);
|
||||
realClearTimeout(timer);
|
||||
}) as typeof clearTimeout),
|
||||
];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const timer of deadlines) realClearTimeout(timer);
|
||||
for (const spy of spies) spy.mockRestore();
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
function client(fetcher: (request: Request) => Response | Promise<Response>) {
|
||||
return ky.create({ prefix: "https://invoice.example", fetch: async (input) => fetcher(input as Request) });
|
||||
}
|
||||
|
||||
it("clears the deadline on fast success without cancelling the request", async () => {
|
||||
let signal!: AbortSignal;
|
||||
const result = await getTranslatorContext(client((request) => {
|
||||
signal = request.signal;
|
||||
return Response.json({ invoice: "fast" });
|
||||
}), "corp", rawFlow());
|
||||
expect(result.invoiceDetailMap?.get("invoice")).toEqual({ invoice: "fast" });
|
||||
expect(scheduled).toBe(1);
|
||||
expect(deadlines.size).toBe(0);
|
||||
expect(signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it("aborts a pending request and preserves successful invoices", async () => {
|
||||
let aborted = false;
|
||||
const result = await getTranslatorContext(client((request) => {
|
||||
if (request.url.includes("$good")) return Response.json({ invoice: "good" });
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
request.signal.addEventListener("abort", () => {
|
||||
aborted = true;
|
||||
reject(request.signal.reason);
|
||||
}, { once: true });
|
||||
});
|
||||
}), "corp", rawFlow(["good", "pending"]));
|
||||
expect(aborted).toBe(true);
|
||||
expect(result.invoiceDetailMap?.get("good")).toEqual({ invoice: "good" });
|
||||
expect(result.invoiceDetailMap?.has("pending")).toBe(false);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps the deadline active while reading the response body", async () => {
|
||||
let cancelled = false;
|
||||
const result = await getTranslatorContext(client((request) => new Response(new ReadableStream({
|
||||
start(controller) {
|
||||
request.signal.addEventListener("abort", () => {
|
||||
cancelled = true;
|
||||
controller.error(request.signal.reason);
|
||||
}, { once: true });
|
||||
},
|
||||
}))), "corp", rawFlow());
|
||||
expect(cancelled).toBe(true);
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not use a generic Ky client's automatic retry for a 503", async () => {
|
||||
let attempts = 0;
|
||||
const result = await getTranslatorContext(client(() => {
|
||||
attempts++;
|
||||
return new Response("unavailable", { status: 503 });
|
||||
}), "corp", rawFlow());
|
||||
expect(attempts).toBe(1);
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels the existing authentication replay at the same deadline", async () => {
|
||||
let attempts = 0;
|
||||
let renewals = 0;
|
||||
let replayAborted = false;
|
||||
globalThis.fetch = (async (input: Request | URL | string, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
if (++attempts === 1) return new Response("expired", { status: 401 });
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
request.signal.addEventListener("abort", () => {
|
||||
replayAborted = true;
|
||||
reject(request.signal.reason);
|
||||
}, { once: true });
|
||||
});
|
||||
}) as typeof fetch;
|
||||
const authClient = createAuthClient({
|
||||
prefixUrl: "https://invoice.example",
|
||||
getHeaders: () => ({ accesstoken: "fixture" }),
|
||||
onUnauthorized: () => { renewals++; },
|
||||
});
|
||||
const result = await getTranslatorContext(authClient, "corp", rawFlow());
|
||||
expect(attempts).toBe(2);
|
||||
expect(renewals).toBe(1);
|
||||
expect(replayAborted).toBe(true);
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not mutate the returned map when a fetch ignores cancellation", async () => {
|
||||
let finish!: (response: Response) => void;
|
||||
const result = await getTranslatorContext(client(() => new Promise<Response>((resolve) => { finish = resolve; })), "corp", rawFlow());
|
||||
finish(Response.json({ invoice: "late" }));
|
||||
await new Promise((resolve) => realSetTimeout(resolve, 0));
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not create invoice requests or deadlines when skipped", async () => {
|
||||
let attempts = 0;
|
||||
await getTranslatorContext(client(() => {
|
||||
attempts++;
|
||||
return Response.json({});
|
||||
}), "corp", rawFlow(), { skipInvoices: true });
|
||||
expect(attempts).toBe(0);
|
||||
expect(scheduled).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1061,6 +1061,7 @@ function buildDiagnosticReport(
|
||||
|
||||
/**
|
||||
* 全域单据穿透诊断与待办全貌洞察
|
||||
* options.skipInvoices 仅保留旧 SDK 调用兼容性;此诊断不补充加载发票详情。
|
||||
*/
|
||||
export async function traceBillFlowDetail(
|
||||
client: KyInstance,
|
||||
@@ -1688,14 +1689,24 @@ export async function getTranslatorContext(
|
||||
const invoiceFetches = options?.skipInvoices
|
||||
? []
|
||||
: Array.from(invoiceIds).map(async (id) => {
|
||||
const controller = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
reject(new Error("Invoice timeout"));
|
||||
}, 3000);
|
||||
});
|
||||
const detail = await Promise.race([
|
||||
getInvoiceValidationDetail(client, corpId, id),
|
||||
new Promise<null>((_, reject) => setTimeout(() => reject(new Error("Invoice timeout")), 3000)),
|
||||
getInvoiceValidationDetail(client, corpId, id, { signal: controller.signal }),
|
||||
deadline,
|
||||
]);
|
||||
if (detail) invoiceDetailMap.set(id, detail);
|
||||
} catch {
|
||||
// 单张发票详情超时或获取失败不阻断整体流程解析
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+27
-18
@@ -28,8 +28,23 @@ import {
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
function throwEasoResponseError(response: Response, record?: Record<string, unknown>): never {
|
||||
const code = record?.code;
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
|
||||
async function readEasoResponse(response: Response) {
|
||||
const raw = await response.json();
|
||||
const record =
|
||||
raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
@@ -38,23 +53,17 @@ export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promi
|
||||
|
||||
const code = record?.code;
|
||||
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
|
||||
if (hasCodeError) throwEasoResponseError(response, record);
|
||||
return { raw, record };
|
||||
}
|
||||
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const { raw, record } = await readEasoResponse(response);
|
||||
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
||||
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
||||
|
||||
if (hasCodeError || payload === null || payload === undefined) {
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
if (payload === null || payload === undefined) throwEasoResponseError(response, record);
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
@@ -240,8 +249,8 @@ export async function listRunningJobs(
|
||||
const response = await client.get("api/easo/jobs/running", {
|
||||
searchParams: { pipelineId, runType },
|
||||
});
|
||||
const json = (await response.json()) as { code?: number; data?: unknown };
|
||||
const rawData = json?.data;
|
||||
const { record } = await readEasoResponse(response);
|
||||
const rawData = record?.data;
|
||||
if (!rawData) return [];
|
||||
if (Array.isArray(rawData)) {
|
||||
return z.array(WorkflowJobSchema).parse(rawData);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import type { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { classifyCliError } from "../../cli/errors.js";
|
||||
import { listRunningJobs, unwrap } from "./api.js";
|
||||
import { watchWorkflowPipeline } from "./workflow/watch/pipeline-watcher.js";
|
||||
|
||||
const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance;
|
||||
|
||||
describe("running jobs response contract", () => {
|
||||
for (const code of [401, 403, "401", "403"]) {
|
||||
it(`rejects business authentication failure ${JSON.stringify(code)} before empty-data normalization`, async () => {
|
||||
await expect(listRunningJobs(responding({ code, data: null, msg: "session expired" }), "wf"))
|
||||
.rejects.toBeInstanceOf(AuthenticationError);
|
||||
await expect(listRunningJobs(responding({ code, data: { id: "job" } }), "wf"))
|
||||
.rejects.toBeInstanceOf(AuthenticationError);
|
||||
});
|
||||
}
|
||||
|
||||
it("preserves the API error category and server message for other business failures", async () => {
|
||||
await expect(listRunningJobs(responding({ code: 500, data: null, errorMessage: "backend failed" }), "wf"))
|
||||
.rejects.toMatchObject({ name: "EkbApiError", code: "EASO_API_ERROR", status: 500, message: expect.stringContaining("backend failed") });
|
||||
});
|
||||
|
||||
it("preserves successful null, missing, single-job and array responses", async () => {
|
||||
for (const body of [{ code: 200, data: null }, { code: 200 }, { data: [] }]) {
|
||||
expect(await listRunningJobs(responding(body), "wf")).toEqual([]);
|
||||
}
|
||||
const single = await listRunningJobs(responding({ code: 200, data: { jobId: "job" } }), "wf");
|
||||
expect(single.map((job) => job.id)).toEqual(["job"]);
|
||||
const array = await listRunningJobs(responding({ code: "200", data: [{ id: "one" }, { id: "two" }] }), "wf");
|
||||
expect(array.map((job) => job.id)).toEqual(["one", "two"]);
|
||||
});
|
||||
|
||||
it("does not relax unwrap's nonempty-detail requirement", async () => {
|
||||
await expect(unwrap(Response.json({ code: 200, data: null }), z.unknown())).rejects.toBeInstanceOf(EkbApiError);
|
||||
await expect(unwrap(Response.json({ code: "401", data: [] }), z.array(z.unknown()))).rejects.toBeInstanceOf(AuthenticationError);
|
||||
expect(await unwrap(Response.json({ code: 200, value: { id: "detail" } }), z.object({ id: z.string() })))
|
||||
.toEqual({ id: "detail" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("running job watcher error propagation", () => {
|
||||
function watcherClient(running: unknown, otherFailure = false) {
|
||||
let logCalls = 0;
|
||||
const client = { get: async (path: string) => {
|
||||
if (path === "api/easo/jobs/running") return Response.json(running);
|
||||
if (path.endsWith("/log")) {
|
||||
logCalls++;
|
||||
return Response.json({ code: 200, data: { jobList: logCalls > 1 || otherFailure ? [{ jobId: "job", status: "COMPLETED" }] : [] } });
|
||||
}
|
||||
if (path.endsWith("/execution/level/failed")) return Response.json({ data: { items: [] } });
|
||||
if (path.endsWith("/execution")) return Response.json({ data: [] });
|
||||
if (path === "api/easo/jobs/job") return Response.json({ data: { id: "job", pipelineId: "wf", status: "COMPLETED" } });
|
||||
return Response.json({ data: { id: "wf", label: "workflow" } });
|
||||
} } as unknown as KyInstance;
|
||||
return { client, logCalls: () => logCalls };
|
||||
}
|
||||
|
||||
for (const once of [true, false]) {
|
||||
it(`propagates running-job authentication failure in ${once ? "snapshot" : "continuous"} mode`, async () => {
|
||||
const fixture = watcherClient({ code: 401, data: null });
|
||||
try {
|
||||
await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
|
||||
throw new Error("watcher unexpectedly succeeded");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AuthenticationError);
|
||||
expect(classifyCliError(error).exitCode).toBe(11);
|
||||
}
|
||||
expect(fixture.logCalls()).toBe(once ? 0 : 1);
|
||||
});
|
||||
|
||||
it(`retains non-authentication log fallback in ${once ? "snapshot" : "continuous"} mode`, async () => {
|
||||
const fixture = watcherClient({ code: 500, data: null }, once);
|
||||
const report = await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
|
||||
expect(report.totalJobsWatched).toBe(1);
|
||||
expect(report.jobs[0]?.jobId).toBe("job");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -77,6 +77,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
- 代码出参摘要使用同一执行树展开函数,覆盖条件、循环及已有子执行容器;同名节点的多次执行分别保留。
|
||||
- `logs --has-error` 包括已经产生错误的在途任务,错误标记不被 RUNNING/STARTED 覆盖。`--state` 保留原有终态筛选兼容语义,不能替代“包含错误”筛选;筛选仍针对当前返回页。
|
||||
- `job` 无法读取工作流详情时,状态显示“未知”,不会把可用 Job 的未知工作流状态显示成“已停用”。
|
||||
- `tail` 的在途任务接口先校验业务错误码,再兼容成功的空值、单对象和数组;在途任务查询的鉴权错误会终止监听并沿用 CLI 认证错误退出码,其他既有日志回退保留。
|
||||
|
||||
## 企业可用节点探针与灰度开通(Nodes Probe & Grant)
|
||||
|
||||
@@ -137,6 +141,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
|
||||
`eval-script` 使用内嵌 QuickJS/WASM 独立运行时,输入经过 JSON 复制,脚本无法访问宿主的 `process`、`Bun`、文件或网络。保留同步 JavaScript、日志和结构化执行结果;Promise 返回值明确报错。执行时间默认 3000ms,内存上限 32MiB,输入和结果各不超过 1MiB,日志最多 500 条及 64KiB。WASM 随 MCP bundle 和单文件二进制一起分发,不需要额外运行时文件。
|
||||
|
||||
MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `java.util.HashMap` / `java.util.ArrayList` 构造器、Map/List 基本方法,以及可确定的末尾顶层表达式返回;末尾表达式只求值一次,显式 `return` 继续有效。Map.size 按自身键数量计数,List.size 按元素数计数,字符串和注释不参与代码改写。其他 Java 构造器、泛型及无法确定完成值的末项复合语句明确返回 `UnsupportedMvelSyntax`,不把错误仿真结果当作成功。它不模拟 JVM 精确数值、任意 Java 方法或完整原生 MVEL;本地成功不能替代合思真实引擎的兼容性验证。
|
||||
|
||||
`node edit --file=<脚本>` 是 `--code-file` 的兼容别名;编辑字段映射使用 `--mapping-file=<JSON>`,或独立的 `node map --file=<JSON>`。不根据文件扩展名猜测用途。
|
||||
|
||||
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。管理员密码用于额外授权,不能替代写操作确认。
|
||||
|
||||
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
|
||||
@@ -157,6 +165,8 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
|
||||
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
|
||||
|
||||
字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。`body` 等上下文根不按节点处理,来源无法静态确定或无法解析的表达式给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。
|
||||
|
||||
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
|
||||
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析;
|
||||
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
|
||||
|
||||
@@ -53,20 +53,84 @@ const KNOWN_TYPES = new Set([
|
||||
"task-dynamic-delay",
|
||||
]);
|
||||
|
||||
function extractChooseTags(val: unknown): Array<{ raw: string; parsed: any }> {
|
||||
interface ChooseReference {
|
||||
raw: string;
|
||||
key?: string;
|
||||
descriptor?: boolean;
|
||||
problem?: string;
|
||||
}
|
||||
|
||||
/** 只解析 choose 参数,不执行表达式;引号内的括号不参与标签边界匹配。 */
|
||||
function extractChooseTags(val: unknown): ChooseReference[] {
|
||||
if (typeof val !== "string") return [];
|
||||
const results: Array<{ raw: string; parsed: any }> = [];
|
||||
const matches = val.matchAll(/@\{choose\('(.*?)'\)\}/g);
|
||||
for (const m of matches) {
|
||||
const results: ChooseReference[] = [];
|
||||
const marker = /@\{\s*choose\s*\(/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = marker.exec(val))) {
|
||||
const from = marker.lastIndex;
|
||||
let quote = "";
|
||||
let escaped = false;
|
||||
let depth = 1;
|
||||
let end = from;
|
||||
for (; end < val.length; end++) {
|
||||
const ch = val[end];
|
||||
if (quote) {
|
||||
if (escaped) escaped = false;
|
||||
else if (ch === "\\") escaped = true;
|
||||
else if (ch === quote) quote = "";
|
||||
} else if (ch === "'" || ch === '"') quote = ch;
|
||||
else if (ch === "(") depth++;
|
||||
else if (ch === ")" && --depth === 0) break;
|
||||
}
|
||||
const close = /^\s*\}/.exec(val.slice(end + 1));
|
||||
if (depth !== 0 || !close) {
|
||||
results.push({ raw: val.slice(match.index), problem: "choose 标签未闭合或缺少结束标记" });
|
||||
continue;
|
||||
}
|
||||
marker.lastIndex = end + 1 + close[0].length;
|
||||
const raw = val.slice(match.index, marker.lastIndex);
|
||||
const argument = val.slice(from, end).trim();
|
||||
try {
|
||||
results.push({ raw: m[0], parsed: JSON.parse(m[1]) });
|
||||
let value = argument;
|
||||
if (argument.startsWith('"')) value = JSON.parse(argument);
|
||||
else if (argument.startsWith("'")) {
|
||||
if (!argument.endsWith("'")) throw new Error("未闭合的参数字符串");
|
||||
// 单引号是模板包裹符;保留 descriptor 内 JSON 自身的转义。
|
||||
value = argument.slice(1, -1).replace(/\\'/g, "'");
|
||||
}
|
||||
if (typeof value !== "string") throw new Error("参数应为节点描述或路径");
|
||||
if (value.trim().startsWith("{")) {
|
||||
const descriptor: unknown = JSON.parse(value);
|
||||
if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) || typeof (descriptor as Record<string, unknown>).key !== "string" || !(descriptor as { key: string }).key.trim()) throw new Error("节点描述缺少 key");
|
||||
results.push({ raw, key: (descriptor as { key: string }).key.trim(), descriptor: true });
|
||||
} else if (/^[$\p{L}_][$\p{L}\p{N}_]*(?:\.[$\p{L}\p{N}_]+)*$/u.test(value.trim())) {
|
||||
results.push({ raw, key: value.trim(), descriptor: false });
|
||||
} else throw new Error("参数不是可静态识别的节点路径");
|
||||
} catch {
|
||||
// ignore
|
||||
results.push({ raw, problem: "choose 参数不是可静态识别的节点描述或路径" });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function collectExpressionValues(value: unknown, path: string, result: Array<{ key: string; value: string }>, allowEntry = false): void {
|
||||
if (typeof value === "string") result.push({ key: path, value });
|
||||
else if (Array.isArray(value)) value.forEach((item, index) => {
|
||||
collectExpressionValues(item, `${path}[${index}]`, result, true);
|
||||
});
|
||||
else if (value && typeof value === "object") {
|
||||
const entry = value as Record<string, unknown>;
|
||||
if (allowEntry && Object.hasOwn(entry, "key") && typeof entry.key === "string" && Object.hasOwn(entry, "value")) {
|
||||
// 明确 key/value 条目的 label/type 是元信息;普通映射的 label 字段仍是业务值。
|
||||
collectExpressionValues(entry.value, `${path}[${entry.key}].value`, result);
|
||||
} else {
|
||||
for (const [key, child] of Object.entries(value)) collectExpressionValues(child, `${path}.${key}`, result, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const CHOOSE_CONTEXT_ROOTS = new Set(["body", "input", "inputs", "output", "outputs", "context", "ctx"]);
|
||||
|
||||
function buildTaskNameMap(tasks: WorkflowTask[]): Map<string, WorkflowTask> {
|
||||
const map = new Map<string, WorkflowTask>();
|
||||
const walk = (list: WorkflowTask[]) => {
|
||||
@@ -687,25 +751,29 @@ export function analyzeWorkflow(
|
||||
}
|
||||
|
||||
// 诊断 5: 字段变量引用失效校验 (BROKEN_CHOOSE_REFERENCE / BROKEN_LOOP_ITEM_REFERENCE)
|
||||
const inspectFields: Array<{ key?: string; value?: unknown }> = [];
|
||||
const inspectFields: Array<{ key: string; value: string }> = [];
|
||||
const rawTask = task as Record<string, unknown>;
|
||||
if (Array.isArray(task.inputs)) inspectFields.push(...task.inputs);
|
||||
else if (rawTask.inputs && typeof rawTask.inputs === "object") {
|
||||
for (const [k, v] of Object.entries(rawTask.inputs)) inspectFields.push({ key: k, value: v });
|
||||
}
|
||||
if (Array.isArray(rawTask.fields)) inspectFields.push(...(rawTask.fields as Array<{ key?: string; value?: unknown }>));
|
||||
if (Array.isArray(rawTask.mapping)) inspectFields.push(...(rawTask.mapping as Array<{ key?: string; value?: unknown }>));
|
||||
for (const key of ["inputs", "fields", "mapping", "form"]) collectExpressionValues(rawTask[key], key, inspectFields);
|
||||
|
||||
for (const field of inspectFields) {
|
||||
if (typeof field.value === "string") {
|
||||
const chooseList = extractChooseTags(field.value);
|
||||
for (const item of chooseList) {
|
||||
const chooseKey = String(item.parsed?.key || "").trim();
|
||||
if (!chooseKey) continue;
|
||||
const chooseKey = item.key;
|
||||
if (!chooseKey) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||||
message: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const segments = chooseKey.split(".");
|
||||
const root = segments[0];
|
||||
const rootTask = taskNameMap.get(root);
|
||||
|
||||
// 5.1 循环内使用了旧版已弃用的 control_xxx.$item 语法,前端无法解析
|
||||
if (chooseKey.endsWith(".$item")) {
|
||||
const baseNodeKey = chooseKey.replace(/\.\$item$/, "");
|
||||
if (segments[1] === "$item" && (item.descriptor || rootTask?.type === "every" || root.startsWith("control_"))) {
|
||||
const baseNodeKey = root;
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
category: "hard_block",
|
||||
@@ -717,13 +785,20 @@ export function analyzeWorkflow(
|
||||
}
|
||||
|
||||
// 5.2 引用了一个在当前工作流中根本不存在的上游节点
|
||||
if (chooseKey !== "trigger_1" && !taskNameMap.has(chooseKey)) {
|
||||
const sourceKey = item.descriptor ? chooseKey : root;
|
||||
if (taskNameMap.has(sourceKey) || (!item.descriptor && CHOOSE_CONTEXT_ROOTS.has(root))) continue;
|
||||
if (item.descriptor || /^(?:action|control|trigger)_/.test(root)) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
category: "hard_block",
|
||||
code: "BROKEN_CHOOSE_REFERENCE",
|
||||
path,
|
||||
message: `字段 [${field.key || "未知"}] 引用的上游节点 '${chooseKey}' 不存在于当前工作流中,前端设计器将报错【引用变量不存在】并阻断流程保存或运行。`,
|
||||
message: `字段 [${field.key || "未知"}] 引用的上游节点 '${sourceKey}' 不存在于当前工作流中,前端设计器将报错【引用变量不存在】并阻断流程保存或运行。`,
|
||||
});
|
||||
} else {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||||
message: `字段 [${field.key}] 引用了 '${chooseKey}',无法静态确定根 '${root}' 是节点还是上下文;请在真实流程设计器中确认引用来源。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { analyzeWorkflow } from "./analyzer.js";
|
||||
|
||||
const descriptor = (key: string) => `@{choose('${JSON.stringify({ key, properties: [{ key: "data" }] })}')}`;
|
||||
function analyze(config: Record<string, unknown>, sources: Array<Record<string, unknown>> = [{ name: "trigger_actual", type: "webhook" }]) {
|
||||
return analyzeWorkflow({ id: "wf", label: "test", state: 1, version: "1", tasks: [
|
||||
...sources, { name: "action_write", type: "http", ...config },
|
||||
] } as any);
|
||||
}
|
||||
|
||||
describe("choose reference containers and source classification", () => {
|
||||
test("finds missing JSON node references in direct and nested form containers", () => {
|
||||
const tag = descriptor("missing_node");
|
||||
for (const config of [
|
||||
{ fields: [{ key: "title", value: tag }] },
|
||||
{ mapping: [{ key: "title", value: tag }] },
|
||||
{ mapping: { title: { nested: [tag] } } },
|
||||
{ form: [{ key: "title", value: tag }] },
|
||||
{ form: { title: tag } },
|
||||
{ inputs: { form: { title: tag } } },
|
||||
{ inputs: [{ key: "form", value: { title: tag } }] },
|
||||
{ inputs: [{ key: "form", value: [{ key: "title", value: tag }] }] },
|
||||
]) {
|
||||
const result = analyze(config);
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics.filter(item => item.code === "BROKEN_CHOOSE_REFERENCE")).toHaveLength(1);
|
||||
expect(result.diagnostics.find(item => item.code === "BROKEN_CHOOSE_REFERENCE")?.message).toContain("title");
|
||||
}
|
||||
});
|
||||
|
||||
test("does not inspect script, descriptions or descriptor label/type metadata", () => {
|
||||
const tag = descriptor("missing_node");
|
||||
const result = analyze({ code: `return ${JSON.stringify(tag)};`, desc: tag, label: tag, fields: [{ key: "title", label: tag, type: tag, value: "ordinary value" }], inputs: { form: { nested: { key: "title", value: "ordinary value", label: tag, type: tag } } } });
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
// A raw form object may legitimately have a business field named label.
|
||||
expect(analyze({ form: { label: tag } }).summary.passed).toBe(false);
|
||||
expect(analyze({ form: { key: "ordinary field", value: "ordinary value", label: tag } }).summary.passed).toBe(false);
|
||||
});
|
||||
|
||||
test.each([
|
||||
"@{choose(action_missing.data)}",
|
||||
"@{choose('action_missing.data')}",
|
||||
'@{choose("action_missing.data")}',
|
||||
descriptor("action_missing"),
|
||||
])("blocks a clearly identified missing node in %s", tag => {
|
||||
const result = analyze({ mapping: [{ key: "value", value: tag }] });
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_CHOOSE_REFERENCE");
|
||||
});
|
||||
|
||||
test("handles multiple descriptors, escaped quotes and parentheses inside labels", () => {
|
||||
const single = `@{choose('${JSON.stringify({ key: "action_first", label: 'text (with) "quotes"', properties: [] })}')}`;
|
||||
const double = `@{choose(${JSON.stringify(JSON.stringify({ key: "action_second", properties: [] }))})}`;
|
||||
const result = analyze({ inputs: { value: `prefix ${single} / ${double} suffix` } });
|
||||
expect(result.diagnostics.filter(item => item.code === "BROKEN_CHOOSE_REFERENCE")).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("recognizes real custom node names while preserving body and other context roots", () => {
|
||||
for (const tag of ["@{choose(source.data)}", "@{choose('source.data')}", descriptor("source"), "@{choose('body.invoices')}", "@{choose(input.value)}"]) {
|
||||
const result = analyze({ inputs: { value: tag } }, [{ name: "source", type: "webhook" }]);
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("requires explicit descriptor node keys even when they resemble context roots", () => {
|
||||
for (const key of ["body", "context"]) {
|
||||
expect(analyze({ form: { title: descriptor(key) } }).summary.passed).toBe(false);
|
||||
expect(analyze({ form: { title: descriptor(key) } }, [{ name: key, type: "webhook" }]).summary.passed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("warns for unknown bare roots and unsupported or malformed expressions without blocking", () => {
|
||||
for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')", "@{choose('{bad json}')}"]) {
|
||||
const result = analyze({ form: { title: tag } });
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("UNRESOLVED_CHOOSE_REFERENCE");
|
||||
expect(result.diagnostics.every(item => item.category === "soft_advice")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["@{choose(control_loop.$item)}", "@{choose('control_loop.$item.data')}", descriptor("control_loop.$item")])("blocks old loop item paths in %s", tag => {
|
||||
const result = analyze({ fields: [{ key: "value", value: tag }] });
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_LOOP_ITEM_REFERENCE");
|
||||
});
|
||||
|
||||
test("accepts the new loop descriptor with $item in properties", () => {
|
||||
const tag = `@{choose('${JSON.stringify({ key: "control_loop", properties: [{ key: "$item" }, { key: "data" }] })}')}`;
|
||||
const result = analyze({ fields: [{ key: "value", value: tag }] }, [{ name: "control_loop", type: "every", tasks: [{ name: "inner", type: "http" }] }]);
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
});
|
||||
|
||||
test("never aliases missing trigger_1 to an actual trigger with another name", () => {
|
||||
for (const tag of [descriptor("trigger_1"), "@{choose(trigger_1.data)}"]) {
|
||||
expect(analyze({ inputs: { value: tag } }).summary.passed).toBe(false);
|
||||
const real = analyze({ inputs: { value: tag } }, [{ name: "trigger_1", type: "webhook" }]);
|
||||
expect(real.summary.passed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("finds actual nodes in nested task containers", () => {
|
||||
const result = analyze({ fields: [{ key: "value", value: descriptor("action_nested") }] }, [
|
||||
{ name: "condition", type: "condition", tasks: [{ name: "action_nested", type: "http" }] },
|
||||
]);
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -230,7 +230,7 @@ describe("MVEL lexical boundaries", () => {
|
||||
it("does not count quoted or commented return as executable code", () => {
|
||||
const result = lintMvelCode('value = "return"; /* return 1; */ // return 2;');
|
||||
expect(result.hasReturn).toBe(false);
|
||||
expect(result.issues.map(i => i.rule)).toEqual(["missing-return"]);
|
||||
expect(result.issues).toEqual([]); // 赋值本身可作为末尾表达式,仍不算显式 return。
|
||||
});
|
||||
|
||||
it("keeps real references and error coordinates while diagnosing unfinished literals", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasMvelFinalExpression } from "./mvel-subset.js";
|
||||
|
||||
/** Mask literals/comments without moving offsets used by diagnostics. */
|
||||
function scanMvelCode(code: string, issues: ScriptIssue[]): string {
|
||||
@@ -84,10 +85,10 @@ export function lintMvelCode(
|
||||
|
||||
const executableCode = scanMvelCode(code, issues);
|
||||
const hasRet = /\breturn\b/.test(executableCode);
|
||||
if (!hasRet) {
|
||||
if (!hasRet && !hasMvelFinalExpression(code)) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
|
||||
message: "MVEL 代码中未发现显式 return 或可确定的末尾结果表达式;请确认所需结果位于脚本末尾",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { executeJavaScriptSandbox, executeMvelSandbox } from "./sandbox.js";
|
||||
import { lintMvelCode } from "./lint-mvel.js";
|
||||
|
||||
describe("MVEL collection and completion subset", () => {
|
||||
test.each(["HashMap", "Map", "java.util.HashMap"])("returns the final Map expression constructed with %s", async kind => {
|
||||
const result = await executeMvelSandbox(`Map result = new ${kind}(); result.put("value", 7); result;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual({ value: 7 });
|
||||
});
|
||||
|
||||
test.each(["ArrayList", "List", "java.util.ArrayList"])("supports List constructor %s", async kind => {
|
||||
const result = await executeMvelSandbox(`List result = new ${kind}(); result.add(7); result;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual([7]);
|
||||
const direct = await executeMvelSandbox(`new ${kind}().size();`);
|
||||
expect(direct.success).toBe(true);
|
||||
expect(direct.returnValue).toBe(0);
|
||||
});
|
||||
|
||||
test("counts Map keys including length and prototype names, without double counting replacements", async () => {
|
||||
const result = await executeMvelSandbox(`Map m = new HashMap(); List sizes = new ArrayList();
|
||||
sizes.add(m.size()); m.put("length", 99); sizes.add(m.size());
|
||||
m.put("length", 100); sizes.add(m.size()); m.put("__proto__", 8); sizes.add(m.size());
|
||||
sizes.add(m.get("absent")); sizes;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual([0, 1, 1, 2, null]);
|
||||
});
|
||||
|
||||
test("supports nested receivers, nested arguments, indexed inputs and collection return values", async () => {
|
||||
const nested = await executeMvelSandbox(`Map m = new HashMap(); List a = new ArrayList();
|
||||
a.add(Math.max(2, 3)); m.put("items", a); m.get("items").add(m.get("items").size());
|
||||
data.get("rows")[0].put("x", 2); a.add((data.get("rows")[0]).size()); m.get("items");`, { data: { rows: [{}] } });
|
||||
expect(nested.success).toBe(true);
|
||||
expect(nested.returnValue).toEqual([3, 1, 1]);
|
||||
});
|
||||
|
||||
test("preserves literal contents while ignoring comments during conversion", async () => {
|
||||
const literal = 'String x = new java.util.HashMap(); .put("x", 1).size() / 2 ? a : b;';
|
||||
const result = await executeMvelSandbox(`/* new Unsafe(); return 8; */ // new ArrayList(2)
|
||||
${JSON.stringify(literal)}; // final comment`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(literal);
|
||||
});
|
||||
|
||||
test.each(["result", "(result);", "result;;; // final comment", "result /* ; return 0; */"])("supports tail expression %s", async tail => {
|
||||
const result = await executeMvelSandbox(`var result = 7; ${tail}`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(7);
|
||||
});
|
||||
|
||||
test("evaluates a terminal expression once and preserves put's previous-value return", async () => {
|
||||
const increment = await executeMvelSandbox("var count = 0; ++count;");
|
||||
expect(increment.success).toBe(true);
|
||||
expect(increment.returnValue).toBe(1);
|
||||
const put = await executeMvelSandbox('Map m = new HashMap(); m.put("x", 1); m.put("x", 2);');
|
||||
expect(put.success).toBe(true);
|
||||
expect(put.returnValue).toBe(1);
|
||||
});
|
||||
|
||||
test("preserves division, ternary, classic for and explicit return compatibility", async () => {
|
||||
const result = await executeMvelSandbox("int total = 0; for (int i = 0; i < 3; i++) { total += i; } if (total == 3) { total += 2; } else { total = 0; } return total > 0 ? total / 2 : 0;");
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(2.5);
|
||||
const assignment = await executeMvelSandbox("var x = 0; x = 9;");
|
||||
expect(assignment.returnValue).toBe(9);
|
||||
});
|
||||
|
||||
test("does not reject existing JavaScript-compatible blocks before a terminal result", async () => {
|
||||
const result = await executeMvelSandbox('function value() { return 8; } var result = 0; try { throw "probe"; } catch (error) { result = value(); } finally { result += 1; } result;');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(9);
|
||||
});
|
||||
|
||||
test.each(["new java.util.Date();", "new HashMap(5);", "new java.util.ArrayList(2);", "Map<String, Object> m = new HashMap(); m;", "if (true) { 7; }", "var value = 7;", "for (item : items) { item; } item;"])("rejects unsupported syntax or completion: %s", async code => {
|
||||
const result = await executeMvelSandbox(code);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error?.name).toBe("UnsupportedMvelSyntax");
|
||||
});
|
||||
|
||||
test("fails explicitly for invalid receiver types and List bounds", async () => {
|
||||
for (const code of ['value.size();', 'value.get(1);']) {
|
||||
const result = await executeMvelSandbox(code, { value: code.includes("get") ? [] : 7 });
|
||||
expect(result.success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the execution time budget and JavaScript completion behavior", async () => {
|
||||
const result = await executeMvelSandbox("while (true) {} 7;", {}, { timeoutMs: 10 });
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error?.message).toContain("timed out");
|
||||
const js = await executeJavaScriptSandbox("7;");
|
||||
expect(js.success).toBe(true);
|
||||
expect(js.returnValue).toBeUndefined();
|
||||
});
|
||||
|
||||
test("lint accepts a final expression without changing explicit hasReturn meaning", () => {
|
||||
const result = lintMvelCode('Map result = new java.util.HashMap(); result.put("x", 7); result;');
|
||||
expect(result.hasReturn).toBe(false);
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(lintMvelCode("var x = 1;").issues.map(issue => issue.rule)).toContain("missing-return");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { ValidationError } from "../../../../core/errors.js";
|
||||
|
||||
function unsupported(message: string): never {
|
||||
throw new ValidationError(`本地 MVEL 子集不支持 ${message};请使用真实 MVEL 运行时验证`);
|
||||
}
|
||||
|
||||
/** 字符串作为完整 token 保留;注释不参与语法转换。 */
|
||||
function tokenize(source: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
const pattern = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|>>>=|===|!==|>>>|<<=|>>=|\*\*=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|\/=|%=|<<|>>|\*\*|[{}()[\].,;:+*/%=&|^~!<>?-]/y;
|
||||
let offset = 0;
|
||||
while (offset < source.length) {
|
||||
pattern.lastIndex = offset;
|
||||
const match = pattern.exec(source);
|
||||
if (!match) unsupported(`字符 ${JSON.stringify(source[offset])}(偏移 ${offset})`);
|
||||
const token = match[0];
|
||||
offset = pattern.lastIndex;
|
||||
if (!/^\s|^\/\//.test(token) && !token.startsWith("/*")) tokens.push(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function closing(tokens: string[], start: number): number {
|
||||
const stack: string[] = [];
|
||||
const pairs: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
|
||||
for (let i = start; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (pairs[token]) stack.push(pairs[token]);
|
||||
else if ([")", "]", "}"].includes(token)) {
|
||||
if (stack.pop() !== token) unsupported("不匹配的括号");
|
||||
if (!stack.length) return i;
|
||||
}
|
||||
}
|
||||
return unsupported("未闭合的括号");
|
||||
}
|
||||
|
||||
type Statement = { start: number; end: number; kind: "expression" | "return" | "declaration" | "compound" | "empty" };
|
||||
|
||||
/** 只识别语句边界,不模拟复合语句在 MVEL 中的完成值。 */
|
||||
function statementAt(tokens: string[], start: number): Statement {
|
||||
const token = tokens[start];
|
||||
const finish = (end: number, kind: Statement["kind"]): Statement => ({ start, end, kind });
|
||||
if (token === ";") return finish(start + 1, "empty");
|
||||
if (token === "{") return finish(closing(tokens, start) + 1, "compound");
|
||||
if (["if", "for", "while", "switch"].includes(token)) {
|
||||
if (tokens[start + 1] !== "(") unsupported(`${token} 语句`);
|
||||
const conditionEnd = closing(tokens, start + 1);
|
||||
if (token === "for") {
|
||||
// 三元表达式仍可使用冒号;没有分号的增强 for 不属于本地子集。
|
||||
const header = tokens.slice(start + 2, conditionEnd);
|
||||
if (!header.includes(";") && header.includes(":")) unsupported("增强 for 循环");
|
||||
}
|
||||
if (conditionEnd + 1 >= tokens.length) unsupported(`${token} 缺少语句体`);
|
||||
let end = statementAt(tokens, conditionEnd + 1).end;
|
||||
if (token === "if" && tokens[end] === "else") end = statementAt(tokens, end + 1).end;
|
||||
return finish(end, "compound");
|
||||
}
|
||||
if (token === "do") {
|
||||
const bodyEnd = statementAt(tokens, start + 1).end;
|
||||
if (tokens[bodyEnd] !== "while" || tokens[bodyEnd + 1] !== "(") unsupported("do/while 语句");
|
||||
const end = closing(tokens, bodyEnd + 1) + 1;
|
||||
return finish(tokens[end] === ";" ? end + 1 : end, "compound");
|
||||
}
|
||||
if (token === "try") {
|
||||
let end = statementAt(tokens, start + 1).end;
|
||||
if (tokens[end] === "catch") {
|
||||
end++;
|
||||
if (tokens[end] === "(") end = closing(tokens, end) + 1;
|
||||
end = statementAt(tokens, end).end;
|
||||
}
|
||||
if (tokens[end] === "finally") end = statementAt(tokens, end + 1).end;
|
||||
return finish(end, "compound");
|
||||
}
|
||||
if (token === "function" || token === "class") {
|
||||
let body = start + 1;
|
||||
while (body < tokens.length && tokens[body] !== "{") {
|
||||
if (tokens[body] === "(") body = closing(tokens, body);
|
||||
body++;
|
||||
}
|
||||
if (body >= tokens.length) unsupported(`${token} 缺少语句体`);
|
||||
return finish(closing(tokens, body) + 1, "declaration");
|
||||
}
|
||||
if (["catch", "finally", "import", "package"].includes(token)) unsupported(`${token} 语句`);
|
||||
let end = start;
|
||||
while (end < tokens.length && tokens[end] !== ";") {
|
||||
if (["(", "[", "{"].includes(tokens[end])) end = closing(tokens, end);
|
||||
else if ([")", "]", "}"].includes(tokens[end])) unsupported("不匹配的括号");
|
||||
end++;
|
||||
}
|
||||
if (tokens[end] === ";") end++;
|
||||
const kind = token === "return" || token === "throw" ? "return" : ["var", "let", "const"].includes(token) ? "declaration" : "expression";
|
||||
return finish(end, kind);
|
||||
}
|
||||
|
||||
function finalStatement(tokens: string[]): Statement | undefined {
|
||||
let last: Statement | undefined;
|
||||
for (let i = 0; i < tokens.length;) {
|
||||
const statement = statementAt(tokens, i);
|
||||
if (statement.kind !== "empty") last = statement;
|
||||
i = statement.end;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
const declarations = new Set(["String", "int", "Integer", "long", "Long", "double", "Double", "float", "Float", "boolean", "Boolean", "List", "Map", "HashMap", "ArrayList", "Object"]);
|
||||
|
||||
/** lint 保留 hasReturn 的显式 return 含义,同时识别可确定的末尾表达式。 */
|
||||
export function hasMvelFinalExpression(source: string): boolean {
|
||||
try {
|
||||
const tokens = tokenize(source);
|
||||
const tail = finalStatement(tokens);
|
||||
return tail?.kind === "expression" && !declarations.has(tokens[tail.start]);
|
||||
} catch {
|
||||
// 原生 MVEL 可能超出本地子集,静态 lint 不因此宣告其语法非法。
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function receiverStart(tokens: string[], end: number): number {
|
||||
let start = end;
|
||||
if (tokens[end] === ")" || tokens[end] === "]") {
|
||||
const opening = tokens[end] === ")" ? "(" : "[";
|
||||
let depth = 1;
|
||||
while (--start >= 0) {
|
||||
if (tokens[start] === tokens[end]) depth++;
|
||||
if (tokens[start] === opening && --depth === 0) break;
|
||||
}
|
||||
if (start < 0) unsupported("缺少方法接收对象");
|
||||
const previous = tokens[start - 1];
|
||||
const previousIsName = /^[A-Za-z_$][\w$]*$/.test(previous ?? "") && !["return", "throw", "if", "while", "for", "switch"].includes(previous);
|
||||
// 数组字面量不是索引表达式;不能把前面的 return/赋值运算符当作接收对象。
|
||||
if (previousIsName || (opening === "[" && [")", "]"].includes(previous))) start = receiverStart(tokens, start - 1);
|
||||
}
|
||||
if (tokens[start - 1] === ".") start = receiverStart(tokens, start - 2);
|
||||
if (start < 0) unsupported("缺少方法接收对象");
|
||||
return start;
|
||||
}
|
||||
|
||||
const arities: Record<string, number> = { put: 2, get: 1, size: 0, add: 1 };
|
||||
|
||||
function rewriteMethods(input: string[]): string[] {
|
||||
const tokens = [...input];
|
||||
for (let i = 1; i < tokens.length - 2; i++) {
|
||||
const method = tokens[i + 1];
|
||||
if (tokens[i] !== "." || tokens[i + 2] !== "(" || !Object.hasOwn(arities, method)) continue;
|
||||
const end = closing(tokens, i + 2);
|
||||
const args: string[][] = [];
|
||||
let from = i + 3;
|
||||
for (let j = from; j < end; j++) {
|
||||
if (["(", "[", "{"].includes(tokens[j])) j = closing(tokens, j);
|
||||
else if (tokens[j] === ",") { args.push(tokens.slice(from, j)); from = j + 1; }
|
||||
}
|
||||
if (from < end) args.push(tokens.slice(from, end));
|
||||
if (args.length !== arities[method] || args.some(arg => !arg.length)) unsupported(`${method} 的该参数数量`);
|
||||
const start = receiverStart(tokens, i - 1);
|
||||
const replacement = [`__hose_mvel_${method}`, "(", ...tokens.slice(start, i)];
|
||||
for (const arg of args) replacement.push(",", ...rewriteMethods(arg));
|
||||
replacement.push(")");
|
||||
tokens.splice(start, end - start + 1, ...replacement);
|
||||
i = start + replacement.length - 1;
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** 必要的 MVEL 集合与末尾表达式子集;运算仍由隔离 QuickJS 执行。 */
|
||||
export function transpileMvelSubset(source: string): string {
|
||||
const tokens = tokenize(source);
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (/^__hose_mvel_/.test(token)) unsupported("保留的内部标识符");
|
||||
if (declarations.has(token) && tokens[i + 1] === "<") unsupported("泛型声明");
|
||||
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
|
||||
if (declarations.has(token) && /^[A-Za-z_$][\w$]*$/.test(tokens[i + 1] ?? "") && ["=", ";"].includes(tokens[i + 2])) tokens[i] = "var";
|
||||
// 2. 转换 new HashMap() / new ArrayList(),仅精确扩展两个全限定名零参构造器。
|
||||
if (token === "new") {
|
||||
let end = i + 1;
|
||||
while (/^[A-Za-z_$][\w$]*$/.test(tokens[end] ?? "") && tokens[end + 1] === ".") end += 2;
|
||||
const kind = tokens.slice(i + 1, end + 1).join("");
|
||||
const map = ["HashMap", "Map", "java.util.HashMap"].includes(kind);
|
||||
if ((!map && !["ArrayList", "List", "java.util.ArrayList"].includes(kind)) || tokens[end + 1] !== "(" || tokens[end + 2] !== ")") unsupported("该构造器、泛型或构造参数");
|
||||
tokens.splice(i, end + 3 - i, ...(map ? ["__hose_mvel_map", "(", ")"] : ["[", "]"]));
|
||||
}
|
||||
}
|
||||
// 3. 常见 Map/List 方法调用模拟:
|
||||
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
|
||||
// 注入轻量 helper;按 token 边界处理,避免直接正则冲突,并保留方法返回值。
|
||||
const rewritten = rewriteMethods(tokens);
|
||||
const tail = finalStatement(rewritten);
|
||||
if (!tail || !["return", "expression"].includes(tail.kind)) unsupported("末项复合语句或声明的完成值;请添加明确的末尾结果表达式");
|
||||
if (tail.kind === "expression") {
|
||||
const end = rewritten[tail.end - 1] === ";" ? tail.end - 1 : tail.end;
|
||||
rewritten.splice(tail.start, tail.end - tail.start, "return", "(", ...rewritten.slice(tail.start, end), ")", ";");
|
||||
}
|
||||
// 恢复并使用 helper,Map 使用自身属性,避免原型键影响集合语义。
|
||||
const preamble = `
|
||||
function __hose_mvel_map() { return Object.create(null); }
|
||||
function __hose_mvel_put(obj, key, val) { if (!obj || Array.isArray(obj) || typeof obj !== 'object') throw new TypeError('put requires Map'); if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); const old = Object.hasOwn(obj, key) ? obj[key] : null; Object.defineProperty(obj, key, {value:val, writable:true, enumerable:true, configurable:true}); return old; }
|
||||
function __hose_mvel_get(obj, key) { if (!obj || typeof obj !== 'object') throw new TypeError('get requires Map/List'); if (Array.isArray(obj)) { if (!Number.isInteger(key) || key < 0 || key >= obj.length) throw new RangeError('List index out of bounds'); } else if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); return Object.hasOwn(obj, key) ? obj[key] : null; }
|
||||
function __hose_mvel_size(obj) { if (!obj || typeof obj !== 'object') throw new TypeError('size requires Map/List'); return Array.isArray(obj) ? obj.length : Object.keys(obj).length; }
|
||||
function __hose_mvel_add(arr, item) { if (!Array.isArray(arr)) throw new TypeError('add requires List'); arr.push(item); return true; }
|
||||
`;
|
||||
return preamble + rewritten.join(" ");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import variant from "@jitl/quickjs-singlefile-cjs-release-sync";
|
||||
import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
|
||||
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
|
||||
import { transpileMvelSubset } from "./mvel-subset.js";
|
||||
|
||||
const MAX_MEMORY_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_VALUE_BYTES = 1024 * 1024;
|
||||
@@ -127,38 +128,7 @@ export async function executeJavaScriptSandbox(
|
||||
* 转换 MVEL 常用语法为 QuickJS 可执行的 JavaScript,实现轻量仿真
|
||||
*/
|
||||
export function transpileMvelToJs(mvelCode: string): string {
|
||||
let js = mvelCode;
|
||||
|
||||
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
|
||||
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
|
||||
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
|
||||
|
||||
// 2. 转换 new HashMap() / new ArrayList()
|
||||
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
|
||||
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
|
||||
|
||||
// 3. 常见 Map/List 方法调用模拟:
|
||||
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
|
||||
// 注入轻量 helper
|
||||
const preamble = [
|
||||
"function _mvel_put(obj, key, val) { if (obj && typeof obj === 'object') { obj[key] = val; } return val; }",
|
||||
"function _mvel_get(obj, key) { return obj ? obj[key] : undefined; }",
|
||||
"function _mvel_size(obj) { if (!obj) return 0; if (Array.isArray(obj)) return obj.length; if (typeof obj === 'object') return Object.keys(obj).length; return 0; }",
|
||||
"function _mvel_add(arr, item) { if (Array.isArray(arr)) arr.push(item); return arr; }",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, ""); // 避免直接正则冲突,使用下面逐行或更精确替换
|
||||
// 恢复并使用 helper
|
||||
js = mvelCode;
|
||||
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
|
||||
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
|
||||
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
|
||||
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
|
||||
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, "[$1] = $2");
|
||||
js = js.replace(/\.size\s*\(\s*\)/g, ".length");
|
||||
|
||||
return `${preamble}${js}`;
|
||||
return transpileMvelSubset(mvelCode);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,7 +139,12 @@ export async function executeMvelSandbox(
|
||||
inputs: Record<string, unknown> = {},
|
||||
options: { timeoutMs?: number } = {}
|
||||
): Promise<ScriptEvalResult> {
|
||||
const transpiled = transpileMvelToJs(code);
|
||||
const result = await executeJavaScriptSandbox(transpiled, inputs, options);
|
||||
return result;
|
||||
const start = performance.now();
|
||||
try {
|
||||
const transpiled = transpileMvelToJs(code);
|
||||
return await executeJavaScriptSandbox(transpiled, inputs, options);
|
||||
} catch (error) {
|
||||
return { success: false, durationMs: Number((performance.now() - start).toFixed(2)), returnValue: undefined, logs: [],
|
||||
error: { name: "UnsupportedMvelSyntax", message: (error as Error).message }, inputs };
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../../../../core/errors.js";
|
||||
import * as api from "../../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
@@ -76,7 +77,8 @@ export async function watchWorkflowPipeline(
|
||||
try {
|
||||
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
if (running.length > 0) targetJobId = running[0].id;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof AuthenticationError) throw error;
|
||||
// 忽略
|
||||
}
|
||||
|
||||
@@ -149,7 +151,8 @@ export async function watchWorkflowPipeline(
|
||||
if (found) {
|
||||
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
|
||||
}
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof AuthenticationError) throw error;
|
||||
// 忽略
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user