import { expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { WorkflowDetailSchema } from "../../src/domains/platform/workflow/types.js"; test("工作流 Schema 导出可重现,保留归一化输出与有效递归引用", () => { const dir = mkdtempSync(join(tmpdir(), "hose-workflow-schema-")); try { const script = resolve(import.meta.dir, "export-workflow-schema.ts"); const generate = () => { const result = spawnSync(process.execPath, [script], { cwd: dir, encoding: "utf8" }); expect(result.status, result.stderr).toBe(0); return readFileSync(join(dir, "specs/workflow-schema.json"), "utf8"); }; const first = generate(); expect(generate()).toBe(first); expect(first).toBe(readFileSync(resolve(import.meta.dir, "../../specs/workflow-schema.json"), "utf8")); const document = JSON.parse(first); expect(Object.keys(document.schemas)).toEqual(["WorkflowDetail", "WorkflowTask", "Workflow"]); const detail = document.schemas.WorkflowDetail; expect(detail.properties.state.type).toBe("number"); expect(detail.required).toContain("tasks"); expect(detail.required).toContain("state"); expect(detail.required).not.toContain("alarm"); const alarm = detail.properties.alarm.anyOf; expect(alarm.map((branch: { type: string }) => branch.type)).toEqual(["object", "null"]); expect(alarm[0].properties.active.type).toBe("boolean"); expect(alarm[0].required).toContain("alarmUser"); for (const input of [{ active: false }, '{"active":false}']) { const normalized = WorkflowDetailSchema.parse({ id: "fixture", state: "1", alarm: input }); expect(normalized.state).toBe(1); expect(normalized.alarm).toEqual({ active: false, alarmUser: [], alarmType: [], alarmScope: "" }); } expect(WorkflowDetailSchema.parse({ id: "fixture", alarm: null }).alarm).toBeNull(); expect(WorkflowDetailSchema.parse({ id: "fixture", alarm: "invalid JSON" }).alarm).toBeUndefined(); for (const schema of Object.values(document.schemas)) { let refs = 0; const visit = (node: any): void => { if (!node || typeof node !== "object") return; if (typeof node.$ref === "string") { expect(node.$ref === "#" || node.$ref.startsWith("#/")).toBe(true); const target = node.$ref === "#" ? schema : node.$ref.slice(2).split("/").reduce((value: any, key: string) => value?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], schema); expect(target).toBeDefined(); refs++; } Object.values(node).forEach(visit); }; visit(schema); expect(refs).toBeGreaterThan(0); } } finally { rmSync(dir, { recursive: true, force: true }); } });