485 lines
17 KiB
TypeScript
485 lines
17 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
import type { CorpConfig } from "../../core/config/types.js";
|
|
import type { createSealClient } from "../../core/http/factory.js";
|
|
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rules/mapping.js";
|
|
import { RulePushExecutionError } from "../../domains/seal/rules/push.js";
|
|
import {
|
|
listAvailableLinters,
|
|
PRIMARY_LINTERS_DIR,
|
|
OFFICIAL_LINTERS_DIR
|
|
} from "../../domains/seal/linter/index.js";
|
|
import { runCapability, runCapabilityResult } from "../helpers.js";
|
|
import { confirmationRequired, validationError, usageError } from "../../core/errors.js";
|
|
import {
|
|
booleanOption,
|
|
dryRunOption,
|
|
jsonObject,
|
|
numberOption,
|
|
parseRuleVersionSelector,
|
|
ruleVersionGetOptions,
|
|
ruleVersionSearchOptions,
|
|
splitOption,
|
|
stringOption
|
|
} from "../parser.js";
|
|
import {
|
|
outputOptions,
|
|
printJson,
|
|
protectLargeRuleListOutput,
|
|
RULE_SUMMARY_FIELDS
|
|
} from "../printer.js";
|
|
import type { ParsedArgs } from "../types.js";
|
|
|
|
function readDescriptionInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
|
|
const filePath =
|
|
stringOption(args.options.descriptionFile) ??
|
|
stringOption(args.options["description-file"]);
|
|
if (filePath) {
|
|
return readFileSync(filePath, "utf8").trim();
|
|
}
|
|
const direct = stringOption(args.options.description) ?? stringOption(args.options.desc);
|
|
if (direct !== undefined) return direct;
|
|
return typeof payload.description === "string" ? payload.description : undefined;
|
|
}
|
|
|
|
function resolveVersionOption(args: ParsedArgs, fallback?: string): string | undefined {
|
|
const explicit = stringOption(args.options.version);
|
|
if (explicit !== undefined) return explicit;
|
|
if (booleanOption(args.options.latest)) return "latest";
|
|
if ( fallback !== undefined && !fallback.startsWith("-") ) return fallback;
|
|
return undefined;
|
|
}
|
|
|
|
export async function handleRulesCommand(
|
|
action: string | undefined,
|
|
maybeName: string | undefined,
|
|
client: Awaited<ReturnType<typeof createSealClient>> | null,
|
|
corp: CorpConfig,
|
|
args: ParsedArgs
|
|
) {
|
|
// lint, linters, and map actions can run without a network client
|
|
const clientless = action === "lint" || action === "linters" || action === "linter-list" || action === "map";
|
|
if (!client && !clientless) {
|
|
throw validationError(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
|
|
}
|
|
|
|
if (action === "count") {
|
|
const version = resolveVersionOption(args);
|
|
await runCapability("sealApprovalRulesList", client!, corp, { version, countOnly: true }, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "recode") {
|
|
const result = await runCapabilityResult("sealApprovalRulesRecode", client!, corp, {
|
|
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
|
|
confirmCode: stringOption(args.options.confirmCode) ?? stringOption(args.options["confirm-code"])
|
|
}) as { phase: string; nextCommand?: string };
|
|
printJson(result, outputOptions(args.options));
|
|
if (result.phase === "confirmation_required") {
|
|
throw confirmationRequired("尚未执行规则重排。请核对预览后运行返回的 nextCommand。", result.nextCommand!);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (action === "list") {
|
|
const version = resolveVersionOption(args);
|
|
if (booleanOption(args.options.count)) {
|
|
await runCapability("sealApprovalRulesList", client!, corp, { version, countOnly: true }, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
const limit = numberOption(args.options.limit);
|
|
const offset = numberOption(args.options.offset);
|
|
if (booleanOption(args.options.summary)) {
|
|
await runCapability(
|
|
"sealApprovalRulesList",
|
|
client!,
|
|
corp,
|
|
{
|
|
version,
|
|
fields: RULE_SUMMARY_FIELDS,
|
|
limit,
|
|
offset
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
const result = await runCapabilityResult("sealApprovalRulesList", client!, corp, { version, limit, offset });
|
|
const output = outputOptions(args.options);
|
|
protectLargeRuleListOutput(result, output.allowFull === true || Boolean(output.outputFile));
|
|
printJson(result, output);
|
|
return;
|
|
}
|
|
|
|
if (action === "clear") {
|
|
const confirmed = booleanOption(args.options.yes) === true;
|
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
|
|
if (!confirmed && !dryRun) {
|
|
throw confirmationRequired(
|
|
"Refusing to clear rules without --yes. Use --dry-run to preview.",
|
|
`seal-use rules clear --corp ${corp.id} --dry-run`
|
|
);
|
|
}
|
|
const result = await runCapabilityResult("sealApprovalRulesClear", client!, corp, {
|
|
dryRun,
|
|
recode: booleanOption(args.options.recode)
|
|
});
|
|
if (!confirmed && dryRun && result && typeof result === "object") {
|
|
printJson(
|
|
{
|
|
...result,
|
|
nextCommand: `seal-use rules clear --corp ${corp.id} --yes`
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "versions") {
|
|
await runCapability("sealApprovalRuleVersionsList", client!, corp, {}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "version") {
|
|
const version = resolveVersionOption(args, maybeName);
|
|
if (!version) throw usageError("Usage: seal-use rules version <versionNumber|latest>");
|
|
await runCapability(
|
|
"sealApprovalRuleVersionGet",
|
|
client!,
|
|
corp,
|
|
parseRuleVersionSelector(version),
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "diff") {
|
|
const from = stringOption(args.options.from) ?? maybeName;
|
|
const to = stringOption(args.options.to) ?? args.command[3];
|
|
if (!from || !to) {
|
|
throw usageError("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
|
|
}
|
|
const singleSelector = args.command[4];
|
|
await runCapability(
|
|
"sealApprovalRuleVersionDiff",
|
|
client!,
|
|
corp,
|
|
{
|
|
from,
|
|
to,
|
|
ruleId: stringOption(args.options.ruleId) ?? stringOption(args.options["rule-id"]),
|
|
code: stringOption(args.options.code) ?? singleSelector,
|
|
includeUnchanged: booleanOption(args.options.includeUnchanged) ?? booleanOption(args.options["include-unchanged"]),
|
|
full: booleanOption(args.options.full),
|
|
format: stringOption(args.options.format)
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "get") {
|
|
const target =
|
|
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
|
|
stringOption(args.options.code) ??
|
|
stringOption(args.options.runtimeId) ??
|
|
stringOption(args.options["runtime-id"]) ??
|
|
stringOption(args.options.ruleId) ??
|
|
stringOption(args.options["rule-id"]);
|
|
if (!target) {
|
|
throw usageError("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRuleGet",
|
|
client!,
|
|
corp,
|
|
{
|
|
...ruleVersionGetOptions(resolveVersionOption(args)),
|
|
code: target,
|
|
recordId: stringOption(args.options.recordId) ?? stringOption(args.options["record-id"])
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "create") {
|
|
const payload = jsonObject(args.json);
|
|
const description = readDescriptionInput(args, payload);
|
|
const scope = stringOption(args.options.scope) ?? (typeof payload.scope === "string" ? payload.scope : undefined);
|
|
const strictness =
|
|
stringOption(args.options.strictness) ??
|
|
(typeof payload.strictness === "string" ? payload.strictness : "MUST_FOLLOW");
|
|
if (!description || !scope) {
|
|
throw usageError("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRuleCreate",
|
|
client!,
|
|
corp,
|
|
{ description, scope, strictness, dryRun: dryRunOption(args) },
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "update") {
|
|
const payload = jsonObject(args.json);
|
|
const ruleId =
|
|
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
|
|
stringOption(args.options.ruleId) ??
|
|
stringOption(args.options["rule-id"]) ??
|
|
stringOption(args.options.code) ??
|
|
(typeof payload.ruleId === "string" ? payload.ruleId : undefined);
|
|
const description = readDescriptionInput(args, payload);
|
|
const scope = stringOption(args.options.scope) ?? (typeof payload.scope === "string" ? payload.scope : undefined);
|
|
const strictness =
|
|
stringOption(args.options.strictness) ??
|
|
(typeof payload.strictness === "string" ? payload.strictness : undefined);
|
|
if (!ruleId || (description === undefined && scope === undefined && strictness === undefined)) {
|
|
throw usageError("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRuleUpdate",
|
|
client!,
|
|
corp,
|
|
{ ruleId, description, scope, strictness, dryRun: dryRunOption(args) },
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "delete") {
|
|
const ruleId =
|
|
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
|
|
stringOption(args.options.ruleId) ??
|
|
stringOption(args.options["rule-id"]) ??
|
|
stringOption(args.options.code);
|
|
if (!ruleId) {
|
|
throw usageError("Usage: seal-use rules delete <code> [--dry-run] --yes [--corp <corpId>]");
|
|
}
|
|
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
|
const dryRun = dryRunOption(args);
|
|
if (!confirmed && !dryRun) {
|
|
throw confirmationRequired(
|
|
`Refusing to delete rule '${ruleId}' without --yes.`,
|
|
`seal-use rules delete ${ruleId} --corp ${corp.id} --yes`
|
|
);
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRuleDelete",
|
|
client!,
|
|
corp,
|
|
{ ruleId, dryRun },
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "publish") {
|
|
const payload = jsonObject(args.json);
|
|
const versionName =
|
|
(maybeName && !maybeName.startsWith("-") ? maybeName : undefined) ??
|
|
stringOption(args.options.versionName) ??
|
|
stringOption(args.options["version-name"]) ??
|
|
stringOption(args.options.name) ??
|
|
(typeof payload.versionName === "string" ? payload.versionName : undefined);
|
|
if (!versionName) {
|
|
throw usageError("Usage: seal-use rules publish <versionName> [--dry-run] [--corp <corpId>]");
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRuleVersionPublish",
|
|
client!,
|
|
corp,
|
|
{ versionName, dryRun: dryRunOption(args) },
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "search") {
|
|
const keyword = maybeName ?? stringOption(args.options.query);
|
|
if (!keyword) throw usageError("Usage: seal-use rules search <keyword> [--version <number|latest>] [--max-results 20] [--corp <corpId>]");
|
|
await runCapability(
|
|
"sealApprovalSearch",
|
|
client!,
|
|
corp,
|
|
{
|
|
keywords: [keyword],
|
|
areas: ["rules"],
|
|
maxResults: numberOption(args.options["max-results"]) ?? numberOption(args.options.maxResults),
|
|
contextLines: numberOption(args.options["context-lines"]) ?? numberOption(args.options.contextLines),
|
|
refresh: booleanOption(args.options.refresh),
|
|
snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]),
|
|
maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]),
|
|
fields: splitOption(args.options.fields),
|
|
...ruleVersionSearchOptions(resolveVersionOption(args))
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "pull") {
|
|
const version = resolveVersionOption(args, maybeName);
|
|
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
|
|
if (booleanOption(args.options.official) === true) {
|
|
if (version) {
|
|
throw usageError("rules pull --official uses SealAI's official current-rules CSV export and cannot be combined with --version.");
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRulesExportCsv",
|
|
client!,
|
|
corp,
|
|
{ out },
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
await runCapability(
|
|
"sealApprovalRulesPull",
|
|
client!,
|
|
corp,
|
|
{
|
|
version,
|
|
out
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "push") {
|
|
const statusOnly =
|
|
maybeName === "status" ||
|
|
booleanOption(args.options.check) === true ||
|
|
args.options.status === "true" ||
|
|
args.options.status === true;
|
|
const file =
|
|
stringOption(args.options.file) ??
|
|
stringOption(args.options.f) ??
|
|
(maybeName && maybeName !== "status" && !maybeName.startsWith("-") ? maybeName : undefined);
|
|
if (statusOnly) {
|
|
await runCapability(
|
|
"sealApprovalRulesPush",
|
|
client!,
|
|
corp,
|
|
{ file, statusOnly: true },
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
const confirmed = booleanOption(args.options.yes) === true;
|
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
|
|
const publish = booleanOption(args.options.publish);
|
|
const versionName = stringOption(args.options.versionName) ?? stringOption(args.options["version-name"]);
|
|
|
|
if (!confirmed && !dryRun) {
|
|
throw confirmationRequired(
|
|
"Refusing to push rules without --yes. Use --dry-run to preview.",
|
|
`seal-use rules push --file ${file ?? "./rules.local.json"} --corp ${corp.id} --dry-run`
|
|
);
|
|
}
|
|
|
|
let result: unknown;
|
|
try {
|
|
result = await runCapabilityResult(
|
|
"sealApprovalRulesPush",
|
|
client!,
|
|
corp,
|
|
{
|
|
file,
|
|
dryRun,
|
|
confirm: confirmed,
|
|
publish,
|
|
versionName
|
|
}
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof RulePushExecutionError) {
|
|
printJson(error.recoveryPayload, outputOptions(args.options));
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
if (!confirmed && dryRun && result && typeof result === "object") {
|
|
printJson(
|
|
{
|
|
...result,
|
|
nextCommand: `seal-use rules push --file ${file ?? "./rules.local.json"} --corp ${corp.id} --yes${publish ? " --publish" : ""}`
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "lint") {
|
|
await runCapability(
|
|
"sealApprovalRulesLint",
|
|
client as Awaited<ReturnType<typeof createSealClient>>,
|
|
corp,
|
|
{
|
|
file: stringOption(args.options.file) ?? stringOption(args.options.f),
|
|
linter: stringOption(args.options.linter),
|
|
version: resolveVersionOption(args),
|
|
code: stringOption(args.options.code),
|
|
ruleId: stringOption(args.options.rule) ?? (maybeName && !maybeName.startsWith("-") ? maybeName : undefined),
|
|
minScore: numberOption(args.options.minScore) ?? numberOption(args.options["min-score"]),
|
|
level: stringOption(args.options.level),
|
|
summary: booleanOption(args.options.summary)
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "linters" || action === "linter-list") {
|
|
const linters = listAvailableLinters();
|
|
printJson({
|
|
primaryDirectory: PRIMARY_LINTERS_DIR,
|
|
officialDirectory: OFFICIAL_LINTERS_DIR,
|
|
totalLinters: linters.length,
|
|
linters
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "map") {
|
|
const versionSelector = resolveVersionOption(args, maybeName);
|
|
const code = stringOption(args.options.code) ?? stringOption(args.options.rule);
|
|
const snapshot = loadRuleMappingSnapshot(corp.id, versionSelector);
|
|
if (!snapshot) {
|
|
const vText = versionSelector ? `version '${versionSelector}'` : "latest version";
|
|
printJson({
|
|
error: `No local rule mapping found for enterprise '${corp.name}' (${corp.id}) ${vText}. Run 'seal-use corps sync-test <prodCorp> --yes' to synchronize and generate mapping snapshots.`,
|
|
corpId: corp.id,
|
|
version: versionSelector ?? "latest"
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
const filtered = filterRuleMapping(snapshot.ruleMapping, code);
|
|
printJson({
|
|
corpId: corp.id,
|
|
syncedAt: snapshot.syncedAt,
|
|
source: snapshot.source,
|
|
target: snapshot.target,
|
|
versionMapping: snapshot.versionMapping,
|
|
totalRules: snapshot.ruleMapping.length,
|
|
matchedRules: filtered.length,
|
|
rules: filtered
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
throw usageError(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
|
|
}
|