Turn on noUnusedLocals/noUnusedParameters so the compiler keeps flagging dead symbols, then clear the 737 findings it reports: unused imports across src/, unused parameters, unreachable locals, and the copy-pasted 135-line import prologues in the seal tool modules (each tool file now imports only what it uses). Also applies the equivalent-safe lint rewrites (Array.from instead of new Array(n).fill, non-null assertions in tests after toBeDefined, simplified spreads, unused catch params) that oxlint will gate in a later commit.
1165 lines
44 KiB
TypeScript
1165 lines
44 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { CorpConfig } from "../../core/config/types.js";
|
|
import { runCli } from "../runner.js";
|
|
|
|
const ORIGINAL_ENV = {
|
|
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
|
config: process.env.SEAL_USE_CONFIG_FILE,
|
|
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
|
|
mappings: process.env.SEAL_USE_MAPPINGS_DIR
|
|
};
|
|
const ORIGINAL_FETCH = globalThis.fetch;
|
|
const tempDirs: string[] = [];
|
|
|
|
afterEach(() => {
|
|
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
|
|
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
|
|
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
|
restoreEnv("SEAL_USE_MAPPINGS_DIR", ORIGINAL_ENV.mappings);
|
|
globalThis.fetch = ORIGINAL_FETCH;
|
|
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
function setupTestEnv() {
|
|
const root = mkdtempSync(join(tmpdir(), "seal-use-bind-test-"));
|
|
const enterprises = join(root, "enterprises");
|
|
const mappings = join(root, "mappings");
|
|
mkdirSync(enterprises, { recursive: true });
|
|
mkdirSync(mappings, { recursive: true });
|
|
tempDirs.push(root);
|
|
|
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
|
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
|
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
|
process.env.SEAL_USE_MAPPINGS_DIR = mappings;
|
|
|
|
const prodCorp: CorpConfig = {
|
|
id: "corp-prod",
|
|
name: "Acme Production",
|
|
environment: "production",
|
|
seal: {
|
|
url: "https://acme-prod.sealai.cc",
|
|
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "prod-token",
|
|
sealUrl: "https://acme-prod.sealai.cc",
|
|
expiresIn: 3600,
|
|
staffId: "seal"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
|
|
const testCorp: CorpConfig = {
|
|
id: "corp-test",
|
|
name: "Acme Staging Test",
|
|
environment: "test",
|
|
seal: {
|
|
url: "https://acme-test.sealai.cc",
|
|
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "test-token",
|
|
sealUrl: "https://acme-test.sealai.cc",
|
|
expiresIn: 3600,
|
|
staffId: "seal"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
|
|
writeFileSync(join(enterprises, "corp-prod.json"), JSON.stringify(prodCorp, null, 2));
|
|
writeFileSync(join(enterprises, "corp-test.json"), JSON.stringify(testCorp, null, 2));
|
|
|
|
return { root, enterprises, prodCorp, testCorp };
|
|
}
|
|
|
|
function restoreEnv(name: string, value: string | undefined) {
|
|
if (value === undefined) delete process.env[name];
|
|
else process.env[name] = value;
|
|
}
|
|
|
|
describe("corps mark", () => {
|
|
test("requires confirmation and exit code 10 without --confirm", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --confirm");
|
|
expect(result.stderr).toContain("seal-use corps mark corp-prod --env test --confirm");
|
|
});
|
|
|
|
test("successfully updates environment with --confirm", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test", "--confirm"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.id).toBe("corp-prod");
|
|
expect(parsed.environment).toBe("test");
|
|
|
|
const saved = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(saved.environment).toBe("test");
|
|
});
|
|
});
|
|
|
|
describe("corps bind-test & unbind-test", () => {
|
|
test("rejects self-binding with exit code 2", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-prod", "--confirm"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("Cannot bind enterprise 'corp-prod' to itself");
|
|
});
|
|
|
|
test("requires confirmation and exit code 10 without --confirm", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --confirm");
|
|
expect(result.stderr).toContain("seal-use corps bind-test corp-prod corp-test --confirm");
|
|
});
|
|
|
|
test("successfully binds 1-to-1 with --confirm and sets tags", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.success).toBe(true);
|
|
expect(parsed.productionEnterprise.id).toBe("corp-prod");
|
|
expect(parsed.productionEnterprise.testCorpId).toBe("corp-test");
|
|
expect(parsed.productionEnterprise.environment).toBe("production");
|
|
expect(parsed.testEnterprise.id).toBe("corp-test");
|
|
expect(parsed.testEnterprise.prodCorpId).toBe("corp-prod");
|
|
expect(parsed.testEnterprise.environment).toBe("test");
|
|
|
|
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(savedProd.testCorpId).toBe("corp-test");
|
|
expect(savedProd.environment).toBe("production");
|
|
|
|
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
|
|
expect(savedTest.prodCorpId).toBe("corp-prod");
|
|
expect(savedTest.environment).toBe("test");
|
|
});
|
|
|
|
test("prevents multi-tier chaining: test corp cannot be bound as prod parent", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const thirdCorp: CorpConfig = {
|
|
id: "corp-subtest",
|
|
name: "Acme Subtest",
|
|
environment: "test",
|
|
seal: { url: "https://sub.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
|
source: { type: "seal", token: "tok", sealUrl: "https://sub.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
writeFileSync(join(enterprises, "corp-subtest.json"), JSON.stringify(thirdCorp, null, 2));
|
|
|
|
const result = await runCli(["corps", "bind-test", "corp-test", "corp-subtest", "--confirm"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("Multi-tier chaining is not permitted");
|
|
});
|
|
|
|
test("requires --force when re-binding an already bound corp", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const testCorp2: CorpConfig = {
|
|
id: "corp-test-2",
|
|
name: "Acme Staging 2",
|
|
environment: "test",
|
|
seal: { url: "https://test2.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
|
source: { type: "seal", token: "tok2", sealUrl: "https://test2.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
writeFileSync(join(enterprises, "corp-test-2.json"), JSON.stringify(testCorp2, null, 2));
|
|
|
|
const conflictResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm"]);
|
|
expect(conflictResult.isError).toBe(true);
|
|
expect(conflictResult.exitCode).toBe(10);
|
|
expect(conflictResult.stderr).toContain("requires --force");
|
|
|
|
const forceResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm", "--force"]);
|
|
expect(forceResult.isError).toBe(false);
|
|
expect(forceResult.exitCode).toBe(0);
|
|
|
|
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(savedProd.testCorpId).toBe("corp-test-2");
|
|
});
|
|
|
|
test("unbind-test requires confirmation then unlinks both sides", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const blockResult = await runCli(["corps", "unbind-test", "corp-prod"]);
|
|
expect(blockResult.isError).toBe(true);
|
|
expect(blockResult.exitCode).toBe(10);
|
|
expect(blockResult.stderr).toContain("without --confirm");
|
|
|
|
const successResult = await runCli(["corps", "unbind-test", "corp-prod", "--confirm"]);
|
|
expect(successResult.isError).toBe(false);
|
|
expect(successResult.exitCode).toBe(0);
|
|
const parsed = JSON.parse(successResult.stdout);
|
|
expect(parsed.success).toBe(true);
|
|
expect(parsed.unboundProduction).toBe("corp-prod");
|
|
expect(parsed.unboundTest).toBe("corp-test");
|
|
|
|
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(savedProd.testCorpId).toBeUndefined();
|
|
|
|
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
|
|
expect(savedTest.prodCorpId).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("corps sync-test", () => {
|
|
test("fails if production corp has no bound test corp", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("has no bound test enterprise");
|
|
});
|
|
|
|
test("dry-run produces preview diff without making network mutations", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const mockMutations: string[] = [];
|
|
mockSealSyncRequests({ onMutation: (method, path) => mockMutations.push(`${method} ${path}`) });
|
|
|
|
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.dryRun).toBe(true);
|
|
expect(parsed.source.id).toBe("corp-prod");
|
|
expect(parsed.target.id).toBe("corp-test");
|
|
expect(parsed.rulesPlan.sourceDraftRuleCount).toBe(2);
|
|
expect(parsed.rulesPlan.targetExistingDraftRuleCount).toBe(1);
|
|
expect(parsed.rulesPlan.toDeleteCount).toBe(1);
|
|
expect(parsed.rulesPlan.toCreateCount).toBe(2);
|
|
expect(parsed.documentsPlan).toBeDefined();
|
|
expect(parsed.documentsPlan.sourceDocumentCount).toBe(2);
|
|
expect(parsed.documentsPlan.targetExistingDocumentCount).toBe(2);
|
|
expect(parsed.documentsPlan.toCreateCount).toBe(1);
|
|
expect(parsed.documentsPlan.toCreate[0].title).toBe("Doc Alpha");
|
|
expect(parsed.documentsPlan.toUpdateCount).toBe(1);
|
|
expect(parsed.documentsPlan.toUpdate[0].title).toBe("Doc Beta");
|
|
expect(parsed.documentsPlan.toDeleteCount).toBe(1);
|
|
expect(parsed.documentsPlan.toDelete[0].title).toBe("Doc Gamma Old");
|
|
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
|
|
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
|
|
|
|
expect(mockMutations).toEqual([]);
|
|
});
|
|
|
|
test("sync-test requires --yes and blocks with exit code 10", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
mockSealSyncRequests();
|
|
|
|
const result = await runCli(["corps", "sync-test", "corp-prod"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --yes");
|
|
expect(result.stderr).toContain("seal-use corps sync-test corp-prod --yes");
|
|
});
|
|
|
|
test("sync-test --yes overwrites test preferences, syncs rules, publishes new test version, and guarantees prod draft safety", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const requests: { method: string; path: string; body?: unknown }[] = [];
|
|
mockSealSyncRequests({
|
|
onMutation: (method, path, body) => requests.push({ method, path, body })
|
|
});
|
|
|
|
const result = await runCli([
|
|
"corps",
|
|
"sync-test",
|
|
"corp-prod",
|
|
"--yes",
|
|
"--version-name",
|
|
"v1.5-staging"
|
|
]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.success).toBe(true);
|
|
expect(parsed.source.id).toBe("corp-prod");
|
|
expect(parsed.source.draftRulesCount).toBe(2);
|
|
expect(parsed.target.id).toBe("corp-test");
|
|
expect(parsed.target.deletedDraftRulesCount).toBe(1);
|
|
expect(parsed.target.createdDraftRulesCount).toBe(2);
|
|
expect(parsed.target.publishedVersion.versionName).toBe("v1.5-staging");
|
|
expect(parsed.target.publishedVersion.versionNumber).toBe(3);
|
|
expect(parsed.documents).toBeDefined();
|
|
expect(parsed.documents.sourceCount).toBe(2);
|
|
expect(parsed.documents.targetExistingCount).toBe(2);
|
|
expect(parsed.documents.createdCount).toBe(1);
|
|
expect(parsed.documents.created[0].title).toBe("Doc Alpha");
|
|
expect(parsed.documents.updatedCount).toBe(1);
|
|
expect(parsed.documents.updated[0].title).toBe("Doc Beta");
|
|
expect(parsed.documents.deletedCount).toBe(1);
|
|
expect(parsed.documents.deleted[0].title).toBe("Doc Gamma Old");
|
|
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
|
|
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
|
|
|
|
expect(parsed.versionMapping).toBeDefined();
|
|
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
|
|
expect(parsed.versionMapping.targetTestVersionNumber).toBe(3);
|
|
expect(parsed.ruleMapping).toHaveLength(2);
|
|
expect(parsed.ruleMapping[0].sourceRuleId).toBe("prod-rule-1");
|
|
expect(parsed.ruleMapping[0].targetRuleCode).toBe("rule-1");
|
|
expect(parsed.mappingSavedTo).toBeDefined();
|
|
|
|
const postPref = requests.find((r) => (r.method === "POST" || r.method === "PATCH") && r.path.includes("config"));
|
|
expect(postPref).toBeDefined();
|
|
expect((postPref!.body as any).decisionPreferences?.explicitApprove).toBe("Prod approve note");
|
|
|
|
const deleteDoc = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/knowledge/articles/test-doc-old");
|
|
expect(deleteDoc).toBeDefined();
|
|
|
|
const patchDoc = requests.find((r) => r.method === "PATCH" && r.path === "/api/v1/knowledge/articles/test-doc-2");
|
|
expect(patchDoc).toBeDefined();
|
|
expect((patchDoc!.body as any).attributes?.content).toBe("Content Beta Updated");
|
|
|
|
const postDoc = requests.find((r) => r.method === "POST" && r.path === "/api/v1/knowledge/articles");
|
|
expect(postDoc).toBeDefined();
|
|
expect((postDoc!.body as any).title).toBe("Doc Alpha");
|
|
|
|
const deleteRule = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/rules/test-rule-old");
|
|
expect(deleteRule).toBeDefined();
|
|
|
|
const createdRules = requests.filter((r) => r.method === "POST" && r.path === "/api/v1/rules");
|
|
expect(createdRules.length).toBe(2);
|
|
expect((createdRules[0]!.body as any).description).toBe("Production Rule A");
|
|
expect((createdRules[1]!.body as any).description).toBe("Production Rule B");
|
|
|
|
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
|
|
expect(publishVersion).toBeDefined();
|
|
expect((publishVersion!.body as any).versionName).toBe("v1.5-staging");
|
|
|
|
const allPublishCalls = requests.filter((r) => r.path === "/api/v1/rule-set-versions/publish");
|
|
expect(allPublishCalls.length).toBe(1);
|
|
});
|
|
|
|
test("sync-test formats semantic version name [Prod v22 · #1 -> Test v3] and rules map inspects local snapshot", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const requests: { method: string; path: string; body?: unknown }[] = [];
|
|
mockSealSyncRequests({
|
|
onMutation: (method, path, body) => requests.push({ method, path, body })
|
|
});
|
|
|
|
const syncResult = await runCli([
|
|
"corps",
|
|
"sync-test",
|
|
"corp-prod",
|
|
"--yes"
|
|
]);
|
|
|
|
expect(syncResult.isError).toBe(false);
|
|
const parsed = JSON.parse(syncResult.stdout);
|
|
expect(parsed.target.publishedVersion.versionName).toBe("Sync from Acme Production [Prod v22 · #1 -> Test v3]");
|
|
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
|
|
expect(parsed.ruleMapping).toHaveLength(2);
|
|
|
|
// Verify rules map command
|
|
const mapResult = await runCli(["rules", "map", "--corp", "corp-test"]);
|
|
expect(mapResult.isError).toBe(false);
|
|
const mapParsed = JSON.parse(mapResult.stdout);
|
|
expect(mapParsed.matchedRules).toBe(2);
|
|
expect(mapParsed.versionMapping.sourceProdVersionNumber).toBe(22);
|
|
|
|
// Verify filtering rules map by targetCode
|
|
const filteredResult = await runCli(["rules", "map", "--corp", "corp-test", "--code", "rule-1"]);
|
|
expect(filteredResult.isError).toBe(false);
|
|
const filteredParsed = JSON.parse(filteredResult.stdout);
|
|
expect(filteredParsed.matchedRules).toBe(1);
|
|
expect(filteredParsed.rules[0].targetRuleCode).toBe("rule-1");
|
|
});
|
|
});
|
|
|
|
describe("buildTestHosecloudOutboundName", () => {
|
|
test("appends (Seal测) suffix, using up to 6 chars of corp name", async () => {
|
|
const { buildTestHosecloudOutboundName } = await import("./corps.js");
|
|
// Short name — all chars fit
|
|
expect(buildTestHosecloudOutboundName("钰泰半导体")).toBe("钰泰半导体(Seal测)");
|
|
// Exactly 6-char prefix
|
|
expect(buildTestHosecloudOutboundName("美年大健康产业控股")).toBe("美年大健康产(Seal测)");
|
|
// Long name — truncated to 6 chars prefix
|
|
expect(buildTestHosecloudOutboundName("钰泰半导体股份有限公司")).toBe("钰泰半导体股(Seal测)");
|
|
// Total is always ≤ 13 chars
|
|
const name = buildTestHosecloudOutboundName("一二三四五六七八九十");
|
|
expect([...name].length).toBeLessThanOrEqual(13);
|
|
expect(name.endsWith("(Seal测)")).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("sync-test hosecloud integration auto-sync", () => {
|
|
function setupHoseTestEnv() {
|
|
const root = mkdtempSync(join(tmpdir(), "seal-use-hose-sync-"));
|
|
const enterprises = join(root, "enterprises");
|
|
const mappings = join(root, "mappings");
|
|
mkdirSync(enterprises, { recursive: true });
|
|
mkdirSync(mappings, { recursive: true });
|
|
tempDirs.push(root);
|
|
|
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
|
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
|
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
|
process.env.SEAL_USE_MAPPINGS_DIR = mappings;
|
|
|
|
// Prod corp is hose-sourced (has appKey/appSecurity)
|
|
const prodCorp: CorpConfig = {
|
|
id: "hose-prod",
|
|
name: "钰泰半导体股份有限公司",
|
|
environment: "production",
|
|
testCorpId: "hose-test",
|
|
seal: {
|
|
url: "https://hose-prod.sealai.cc",
|
|
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
|
},
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://wx2.ekuaibao.com",
|
|
appKey: "test-app-key-123",
|
|
appSecurity: "test-app-secret-456",
|
|
staffId: "hose-prod:staffid",
|
|
corpId: "hose-prod"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
|
|
const testCorp: CorpConfig = {
|
|
id: "hose-test",
|
|
name: "谢子豪测试环境",
|
|
environment: "test",
|
|
prodCorpId: "hose-prod",
|
|
seal: {
|
|
url: "https://hose-test.sealai.cc",
|
|
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "test-token",
|
|
sealUrl: "https://hose-test.sealai.cc",
|
|
expiresIn: 3600,
|
|
staffId: "seal"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
|
|
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorp, null, 2));
|
|
writeFileSync(join(enterprises, "hose-test.json"), JSON.stringify(testCorp, null, 2));
|
|
|
|
return { root, enterprises };
|
|
}
|
|
|
|
function mockHoseSyncRequests(options: {
|
|
prodHosecloudIntegrations?: any[];
|
|
testHosecloudIntegrations?: any[];
|
|
onConfigWrite?: (isProd: boolean, body: unknown) => void;
|
|
} = {}) {
|
|
const prodIntegrations = options.prodHosecloudIntegrations ?? [
|
|
{
|
|
type: "hosecloud",
|
|
signKey: "prod-sign-key",
|
|
outboundName: "钰泰正式审批",
|
|
mode: "fully_automatic",
|
|
apiKey: "test-app-key-123",
|
|
apiSecret: "test-app-secret-456",
|
|
apiOrigin: "custom",
|
|
customApiUrl: "https://wx2.ekuaibao.com",
|
|
corporationId: "hose-prod"
|
|
}
|
|
];
|
|
const testIntegrations = options.testHosecloudIntegrations ?? [];
|
|
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const requestUrl = typeof input === "string" ? input
|
|
: input instanceof URL ? input.toString() : input.url;
|
|
const method = (
|
|
init?.method ??
|
|
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
|
|
).toUpperCase();
|
|
const url = new URL(requestUrl);
|
|
const isProd = url.host.includes("prod");
|
|
|
|
let rawBody = typeof init?.body === "string" ? init.body : undefined;
|
|
if (!rawBody && typeof input === "object" && "text" in input) {
|
|
rawBody = await (input as Request).clone().text().catch(() => "{}");
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/auth/me") {
|
|
return jsonResponse({
|
|
data: {
|
|
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
|
|
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "hose-prod" : "hose-test" }
|
|
}
|
|
});
|
|
}
|
|
|
|
// Hose → Seal SSO token exchange (used when prod corp is hose-sourced)
|
|
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
|
|
return jsonResponse({ token: "mock-hose-seal-token", expiresIn: 3600 });
|
|
}
|
|
|
|
// Hose openapi token exchange
|
|
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
|
return jsonResponse({ value: { accessToken: "mock-hose-openapi-token" } });
|
|
}
|
|
|
|
// Hose provisional auth URL (getProvisionalAuth) — must return a URL with accessToken param
|
|
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
|
|
return jsonResponse({ value: { message: "https://mock.ekuaibao.com/provisional?accessToken=mock-closeapi-token" } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
|
|
return jsonResponse({
|
|
data: {
|
|
tone: "formal",
|
|
language: "zh-CN",
|
|
decisionPreferences: { explicitApprove: "", explicitReject: "", exemptApprove: "", review: "" },
|
|
thinkingDepthPreference: { defaultLevel: "medium", routingPolicies: [] },
|
|
integrations: isProd ? prodIntegrations : testIntegrations
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onConfigWrite?.(isProd, body);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
// Minimal stubs for rules/docs/versions
|
|
if (url.pathname === "/api/v1/knowledge/articles") {
|
|
return jsonResponse({ data: { articles: [], total: 0 } });
|
|
}
|
|
if (url.pathname === "/api/v1/rules") {
|
|
return jsonResponse({ data: { rules: [], hasPendingDeletes: false } });
|
|
}
|
|
if (url.pathname === "/api/v1/rule-set-versions") {
|
|
return jsonResponse({ data: [] });
|
|
}
|
|
if (url.pathname === "/api/v1/rule-set-versions/publish") {
|
|
return jsonResponse({ data: { version: { id: "v1", versionNumber: 1, versionName: "v1", rules: [] }, rulesCount: 0 } });
|
|
}
|
|
if (url.pathname === "/api/v1/rules/batch-recode") {
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
return jsonResponse({ error: `Unexpected: ${method} ${url.pathname}` }, 404);
|
|
}) as typeof fetch;
|
|
}
|
|
|
|
test("hose-sourced prod corp auto-syncs hosecloud integration with assisted mode and naming convention", async () => {
|
|
setupHoseTestEnv();
|
|
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
|
|
|
let capturedTestConfigBody: any;
|
|
mockHoseSyncRequests({
|
|
onConfigWrite: (isProd, body) => {
|
|
if (!isProd) capturedTestConfigBody = body;
|
|
}
|
|
});
|
|
|
|
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
|
expect(result.isError).toBe(false);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.hosecloudSync).toBeDefined();
|
|
expect(parsed.hosecloudSync.skipped).toBe(false);
|
|
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
|
|
|
const synced = parsed.hosecloudSync.synced[0];
|
|
expect(synced.outboundName).toBe("钰泰半导体股(Seal测)");
|
|
expect(synced.corporationId).toBe("hose-prod");
|
|
expect(synced.action).toBe("created");
|
|
|
|
// Verify the written integration has assisted mode regardless of prod mode
|
|
expect(capturedTestConfigBody).toBeDefined();
|
|
const writtenIntegration = capturedTestConfigBody.integrations?.find((i: any) => i.type === "hosecloud");
|
|
expect(writtenIntegration?.mode).toBe("assisted");
|
|
expect(writtenIntegration?.apiOrigin).toBe("custom");
|
|
expect(writtenIntegration?.customApiUrl).toBe("https://wx2.ekuaibao.com");
|
|
expect(writtenIntegration?.outboundName).toBe("钰泰半导体股(Seal测)");
|
|
});
|
|
|
|
test("preserves existing test signKey when re-syncing (idempotent)", async () => {
|
|
setupHoseTestEnv();
|
|
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
|
|
|
const existingSignKey = "existing-test-sign-key";
|
|
let capturedBody: any;
|
|
mockHoseSyncRequests({
|
|
testHosecloudIntegrations: [
|
|
{
|
|
type: "hosecloud",
|
|
signKey: existingSignKey,
|
|
outboundName: "钰泰半导体股(Seal测)",
|
|
mode: "assisted",
|
|
apiKey: "test-app-key-123",
|
|
apiSecret: "test-app-secret-456",
|
|
apiOrigin: "custom",
|
|
customApiUrl: "https://wx2.ekuaibao.com",
|
|
corporationId: "hose-prod"
|
|
}
|
|
],
|
|
onConfigWrite: (isProd, body) => {
|
|
if (!isProd) capturedBody = body;
|
|
}
|
|
});
|
|
|
|
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
|
expect(result.isError).toBe(false);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.hosecloudSync.synced[0].action).toBe("updated");
|
|
expect(parsed.hosecloudSync.synced[0].signKey).toBe(existingSignKey);
|
|
|
|
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
|
|
expect(writtenIntegration?.signKey).toBe(existingSignKey);
|
|
});
|
|
|
|
test("skips hosecloud sync for non-hose-sourced prod corps", async () => {
|
|
const root = mkdtempSync(join(tmpdir(), "seal-use-skip-hose-"));
|
|
const enterprises = join(root, "enterprises");
|
|
mkdirSync(enterprises, { recursive: true });
|
|
tempDirs.push(root);
|
|
|
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
|
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
|
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
|
process.env.SEAL_USE_MAPPINGS_DIR = join(root, "mappings");
|
|
mkdirSync(join(root, "mappings"), { recursive: true });
|
|
|
|
const sealProd: CorpConfig = {
|
|
id: "seal-prod",
|
|
name: "Acme Seal Native",
|
|
environment: "production",
|
|
testCorpId: "seal-test",
|
|
seal: { url: "https://seal-prod.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
|
|
source: { type: "seal", token: "tok", sealUrl: "https://seal-prod.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
const sealTest: CorpConfig = {
|
|
id: "seal-test",
|
|
name: "Acme Test",
|
|
environment: "test",
|
|
prodCorpId: "seal-prod",
|
|
seal: { url: "https://seal-test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
|
|
source: { type: "seal", token: "tok2", sealUrl: "https://seal-test.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
writeFileSync(join(enterprises, "seal-prod.json"), JSON.stringify(sealProd, null, 2));
|
|
writeFileSync(join(enterprises, "seal-test.json"), JSON.stringify(sealTest, null, 2));
|
|
|
|
mockHoseSyncRequests({});
|
|
|
|
const result = await runCli(["corps", "sync-test", "seal-prod", "--yes"]);
|
|
expect(result.isError).toBe(false);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.hosecloudSync.skipped).toBe(true);
|
|
expect(parsed.hosecloudSync.reason).toContain("not hose");
|
|
});
|
|
|
|
test("deduplicates multiple prod integrations for the same corporationId into one test integration", async () => {
|
|
setupHoseTestEnv();
|
|
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
|
|
|
let capturedBody: any;
|
|
// Prod has TWO integrations for the same corporationId (e.g. assisted and fully_automatic)
|
|
mockHoseSyncRequests({
|
|
prodHosecloudIntegrations: [
|
|
{
|
|
type: "hosecloud",
|
|
signKey: "prod-assisted-key",
|
|
outboundName: "辅助审批",
|
|
mode: "assisted",
|
|
apiKey: "test-app-key-123",
|
|
apiSecret: "test-app-secret-456",
|
|
apiOrigin: "wechat",
|
|
corporationId: "hose-prod"
|
|
},
|
|
{
|
|
type: "hosecloud",
|
|
signKey: "prod-auto-key",
|
|
outboundName: "全自动审批",
|
|
mode: "fully_automatic",
|
|
apiKey: "test-app-key-123",
|
|
apiSecret: "test-app-secret-456",
|
|
apiOrigin: "wechat",
|
|
corporationId: "hose-prod"
|
|
}
|
|
],
|
|
onConfigWrite: (isProd, body) => {
|
|
if (!isProd) capturedBody = body;
|
|
}
|
|
});
|
|
|
|
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
|
expect(result.isError).toBe(false);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
// Synced array should contain exactly 1 entry, not 2
|
|
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
|
expect(parsed.hosecloudSync.synced[0].corporationId).toBe("hose-prod");
|
|
|
|
const writtenIntegrations = (capturedBody?.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
|
expect(writtenIntegrations).toHaveLength(1);
|
|
expect(writtenIntegrations[0].mode).toBe("assisted");
|
|
expect(writtenIntegrations[0].apiOrigin).toBe("wechat");
|
|
});
|
|
|
|
test("supports key/password fallback in source config when appKey/appSecurity are omitted", async () => {
|
|
const { enterprises } = setupHoseTestEnv();
|
|
// Overwrite hose-prod.json to use key / password instead of appKey / appSecurity
|
|
const prodCorpWithKeyPassword = JSON.parse(readFileSync(join(enterprises, "hose-prod.json"), "utf-8"));
|
|
delete prodCorpWithKeyPassword.source.appKey;
|
|
delete prodCorpWithKeyPassword.source.appSecurity;
|
|
prodCorpWithKeyPassword.source.key = "fallback-key-789";
|
|
prodCorpWithKeyPassword.source.password = "fallback-secret-012";
|
|
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorpWithKeyPassword, null, 2));
|
|
|
|
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
|
|
|
let capturedBody: any;
|
|
mockHoseSyncRequests({
|
|
onConfigWrite: (isProd, body) => {
|
|
if (!isProd) capturedBody = body;
|
|
}
|
|
});
|
|
|
|
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
|
expect(result.isError).toBe(false);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.hosecloudSync.skipped).toBe(false);
|
|
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
|
|
|
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
|
|
expect(writtenIntegration?.apiKey).toBe("fallback-key-789");
|
|
expect(writtenIntegration?.apiSecret).toBe("fallback-secret-012");
|
|
});
|
|
});
|
|
|
|
describe("corps list & current", () => {
|
|
test("outputs environment, testCorpId, and prodCorpId", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const listResult = await runCli(["corps", "list"]);
|
|
expect(listResult.isError).toBe(false);
|
|
const list = JSON.parse(listResult.stdout);
|
|
const prodItem = list.find((item: any) => item.id === "corp-prod");
|
|
const testItem = list.find((item: any) => item.id === "corp-test");
|
|
|
|
expect(prodItem.environment).toBe("production");
|
|
expect(prodItem.testCorpId).toBe("corp-test");
|
|
expect(testItem.environment).toBe("test");
|
|
expect(testItem.prodCorpId).toBe("corp-prod");
|
|
|
|
const currentResult = await runCli(["corps", "current", "--corp", "corp-prod"]);
|
|
expect(currentResult.isError).toBe(false);
|
|
const current = JSON.parse(currentResult.stdout);
|
|
expect(current.id).toBe("corp-prod");
|
|
expect(current.environment).toBe("production");
|
|
expect(current.testCorpId).toBe("corp-test");
|
|
});
|
|
});
|
|
|
|
describe("corps replay-test", () => {
|
|
test("requires confirmation before a live replay to a bound test enterprise", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const result = await runCli(["corps", "replay-test", "corp-prod"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --confirm");
|
|
});
|
|
|
|
test("fails if production corp has no bound test corp", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "replay-test", "corp-test"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.stderr).toContain("has no bound test enterprise");
|
|
expect(result.stderr).toContain("seal-use corps bind-test");
|
|
});
|
|
|
|
test("pulls production record and executes dry-run to bound test enterprise", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const mockRun = {
|
|
id: "run-prod-001",
|
|
sourceSystem: "hosecloud",
|
|
sourceDocumentSN: "BX-PROD-001",
|
|
sourceDocumentId: "DOC-PROD-001",
|
|
document: {
|
|
id: "DOC-PROD-001",
|
|
sn: "BX-PROD-001",
|
|
fields: [{ key: "f1", label: "项目", type: "TEXT", value: "团建" }]
|
|
}
|
|
};
|
|
|
|
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
|
const requestUrl =
|
|
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
|
|
if (requestUrl.includes("/api/v1/approvals")) {
|
|
return jsonResponse({ data: { records: [mockRun] } });
|
|
}
|
|
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
|
return jsonResponse({
|
|
data: {
|
|
integrations: [
|
|
{
|
|
type: "webhook",
|
|
id: "wh-1",
|
|
name: "测试通道",
|
|
mode: "assisted",
|
|
incomingDocumentWebhook: { id: "wh-1", url: "https://test.example/wh" },
|
|
outgoingResultWebhook: "https://test.example/out",
|
|
incomingManualResultWebhook: { id: "wh-1", url: "https://test.example/manual" },
|
|
secret: "sec"
|
|
}
|
|
]
|
|
}
|
|
});
|
|
}
|
|
return jsonResponse({ error: "not found" }, 404);
|
|
}) as any;
|
|
|
|
const result = await runCli(["corps", "replay-test", "corp-prod", "--dry-run"]);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.stderr).toContain("正式企业「Acme Production」");
|
|
expect(result.stderr).toContain("测试企业「Acme Staging Test」");
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.dryRun).toBe(true);
|
|
expect(parsed.sourceCorp.id).toBe("corp-prod");
|
|
expect(parsed.targetCorp.id).toBe("corp-test");
|
|
expect(parsed.document.documentSN).toBe("BX-PROD-001");
|
|
});
|
|
|
|
test("allows replay within production if --force is explicitly provided even without bound test corp", async () => {
|
|
setupTestEnv();
|
|
const mockRun = {
|
|
id: "run-prod-002",
|
|
sourceDocumentSN: "BX-PROD-002",
|
|
document: { id: "DOC-002", sn: "BX-PROD-002", fields: [] }
|
|
};
|
|
|
|
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
|
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
if (requestUrl.includes("/api/v1/approvals")) {
|
|
return jsonResponse({ data: { records: [mockRun] } });
|
|
}
|
|
return jsonResponse({
|
|
data: {
|
|
integrations: [
|
|
{
|
|
type: "webhook",
|
|
id: "wh-prod",
|
|
name: "生产通道",
|
|
mode: "assisted",
|
|
incomingDocumentWebhook: { id: "wh-prod", url: "https://prod.example/wh" }
|
|
}
|
|
]
|
|
}
|
|
});
|
|
}) as any;
|
|
|
|
const result = await runCli(["corps", "replay-test", "corp-prod", "--force", "--dry-run"]);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.sourceCorp.id).toBe("corp-prod");
|
|
expect(parsed.targetCorp.id).toBe("corp-prod");
|
|
});
|
|
});
|
|
|
|
function mockSealSyncRequests(options: {
|
|
onMutation?: (method: string, path: string, body?: unknown) => void;
|
|
} = {}) {
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const requestUrl = typeof input === "string"
|
|
? input
|
|
: input instanceof URL
|
|
? input.toString()
|
|
: input.url;
|
|
const url = new URL(requestUrl);
|
|
const method = (
|
|
init?.method ??
|
|
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
|
|
).toUpperCase();
|
|
const isProd = url.host.includes("prod");
|
|
|
|
let rawBody = typeof init?.body === "string" ? init.body : undefined;
|
|
if (!rawBody && typeof input === "object" && "text" in input) {
|
|
rawBody = await (input as Request).clone().text().catch(() => "{}");
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/auth/me") {
|
|
return jsonResponse({
|
|
data: {
|
|
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
|
|
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "acme-prod" : "acme-test" }
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
|
|
return jsonResponse({
|
|
data: {
|
|
id: isProd ? "pref-prod" : "pref-test",
|
|
tenantId: isProd ? "tenant-prod" : "tenant-test",
|
|
tone: isProd ? "formal" : "casual",
|
|
language: "zh-CN",
|
|
decisionPreferences: {
|
|
explicitApprove: isProd ? "Prod approve note" : "Test approve note",
|
|
explicitReject: "Reject invalid expenses",
|
|
exemptApprove: "",
|
|
review: ""
|
|
},
|
|
thinkingDepthPreference: {
|
|
defaultLevel: isProd ? "high" : "medium",
|
|
routingPolicies: []
|
|
},
|
|
integrations: [
|
|
{ type: "hosecloud", signKey: isProd ? "prod-sign" : "test-sign" }
|
|
]
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.(method, url.pathname, body);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/knowledge/articles" && method === "GET") {
|
|
if (isProd) {
|
|
return jsonResponse({
|
|
data: {
|
|
articles: [
|
|
{
|
|
id: "prod-doc-1",
|
|
title: "Doc Alpha",
|
|
purpose: "Purpose Alpha",
|
|
content: "Content Alpha",
|
|
contentType: "policy",
|
|
status: "published",
|
|
enabled: true,
|
|
scenarios: ["audit"],
|
|
tags: []
|
|
},
|
|
{
|
|
id: "prod-doc-2",
|
|
title: "Doc Beta",
|
|
purpose: "Purpose Beta",
|
|
content: "Content Beta Updated",
|
|
contentType: "policy",
|
|
status: "published",
|
|
enabled: true,
|
|
scenarios: ["audit"],
|
|
tags: []
|
|
}
|
|
],
|
|
total: 2
|
|
}
|
|
});
|
|
} else {
|
|
return jsonResponse({
|
|
data: {
|
|
articles: [
|
|
{
|
|
id: "test-doc-2",
|
|
title: "Doc Beta",
|
|
purpose: "Purpose Beta",
|
|
content: "Content Beta Old",
|
|
contentType: "policy",
|
|
status: "published",
|
|
enabled: true,
|
|
scenarios: ["audit"],
|
|
tags: []
|
|
},
|
|
{
|
|
id: "test-doc-old",
|
|
title: "Doc Gamma Old",
|
|
purpose: "Redundant doc",
|
|
content: "To be deleted",
|
|
contentType: "policy",
|
|
status: "published",
|
|
enabled: true,
|
|
scenarios: ["audit"],
|
|
tags: []
|
|
}
|
|
],
|
|
total: 2
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
if (url.pathname.startsWith("/api/v1/knowledge/articles/") && method === "DELETE") {
|
|
options.onMutation?.("DELETE", url.pathname);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname.startsWith("/api/v1/knowledge/articles/") && method === "PATCH") {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.("PATCH", url.pathname, body);
|
|
return jsonResponse({
|
|
data: {
|
|
id: url.pathname.split("/").pop(),
|
|
...body.attributes
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/knowledge/articles" && method === "POST") {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.("POST", url.pathname, body);
|
|
return jsonResponse({
|
|
data: {
|
|
id: `new-doc-${Date.now()}`,
|
|
...body
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rules" && method === "GET") {
|
|
if (isProd) {
|
|
return jsonResponse({
|
|
data: {
|
|
rules: [
|
|
{ id: "prod-rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
|
|
{ id: "prod-rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
|
|
],
|
|
hasPendingDeletes: false
|
|
}
|
|
});
|
|
} else {
|
|
return jsonResponse({
|
|
data: {
|
|
rules: [
|
|
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
|
|
],
|
|
hasPendingDeletes: false
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
|
|
options.onMutation?.("DELETE", url.pathname);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rules" && method === "POST") {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.("POST", url.pathname, body);
|
|
return jsonResponse({
|
|
data: {
|
|
id: `new-rule-${Date.now()}`,
|
|
...body
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rules/batch-recode" && method === "POST") {
|
|
options.onMutation?.("POST", url.pathname);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rule-set-versions" && method === "GET") {
|
|
if (isProd) {
|
|
return jsonResponse({
|
|
data: [
|
|
{
|
|
id: "ver-prod-22",
|
|
versionNumber: 22,
|
|
versionName: "审核规则 版本22",
|
|
publishedByName: "周晚容",
|
|
rules: [],
|
|
publishedAt: 1786961644896,
|
|
createdAt: 1786961644896
|
|
}
|
|
]
|
|
});
|
|
} else {
|
|
return jsonResponse({
|
|
data: [
|
|
{
|
|
id: "ver-test-2",
|
|
versionNumber: 2,
|
|
versionName: "v1.0-old",
|
|
publishedByName: "管理员",
|
|
rules: [],
|
|
publishedAt: 1783495074421,
|
|
createdAt: 1783495074421
|
|
}
|
|
]
|
|
});
|
|
}
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rule-set-versions/publish" && method === "POST") {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.("POST", url.pathname, body);
|
|
return jsonResponse({
|
|
data: {
|
|
version: {
|
|
id: "ver-3",
|
|
versionNumber: 3,
|
|
versionName: body.versionName ?? "v1.0",
|
|
rules: [
|
|
{ code: "rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
|
|
{ code: "rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
|
|
]
|
|
},
|
|
rulesCount: 2
|
|
}
|
|
});
|
|
}
|
|
|
|
return jsonResponse({ error: `Unexpected request: ${method} ${url.pathname}` }, 404);
|
|
}) as typeof fetch;
|
|
}
|
|
|
|
function jsonResponse(value: unknown, status = 200) {
|
|
return new Response(JSON.stringify(value), {
|
|
status,
|
|
headers: { "content-type": "application/json" }
|
|
});
|
|
}
|