parseArgs decided a flag's kind from whatever token followed it, so `corps list --all now` fed "now" into --all and crashed with Invalid boolean, a bare `--limit` was silently dropped (full dataset pull), and `--limitt` was silently ignored with exit 0. Add BOOLEAN_FLAGS / VALUE_FLAGS / KNOWN_FLAGS registries derived from how the code reads each flag (booleanOption vs stringOption/numberOption). Booleans never consume the next token, value flags must receive one, unknown flags fail with a did-you-mean suggestion, and the three dual-use flags (f, h, version) keep the legacy heuristic. parser.test.ts — previously zero tests on the entry point — locks all of it plus a help.ts cross-check.
426 lines
18 KiB
TypeScript
426 lines
18 KiB
TypeScript
import type { WebhookMode } from "../domains/seal/types.js";
|
|
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
|
|
import type { ParsedArgs } from "./types.js";
|
|
import { usageError } from "./errors.js";
|
|
|
|
/**
|
|
* Flag metadata for argv parsing, derived from how the code reads each flag:
|
|
*
|
|
* - 74 boolean flags never consume the next token, so
|
|
* `corps list --all now` no longer feeds "now" into --all.
|
|
* - 207 value flags must consume a value, so a bare `--limit` is a
|
|
* usage error instead of being silently dropped.
|
|
* - `f` / `h` / `version` are read as boolean in one command and as a value in
|
|
* another (force vs file, help vs host, bare --version vs --version latest),
|
|
* so they keep the legacy next-token heuristic.
|
|
*
|
|
* Anything not in KNOWN_FLAGS is rejected as a typo (`--limitt` used to pass
|
|
* silently). Add a flag here whenever you add one to a command: the
|
|
* cross-check test in parser.test.ts fails when help.ts documents a flag this
|
|
* set lacks.
|
|
*/
|
|
|
|
// Read with booleanOption(...) / Boolean(...) / presence check.
|
|
export const BOOLEAN_FLAGS = new Set([
|
|
"V", "add", "all", "as-hose", "attachments", "auto",
|
|
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
|
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
|
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
|
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "help",
|
|
"hose", "hose-sso", "hoseSso", "include-deleted", "include-simulation", "include-unchanged",
|
|
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
|
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
|
|
"r", "recode", "refresh", "reveal", "rotate-secret", "rotateSecret",
|
|
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-invoice-generation",
|
|
"skipExpenseExtraction", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
|
"summary", "to-downloads", "toDownloads", "v", "wait", "with-flow",
|
|
"workspace", "yes"
|
|
]);
|
|
|
|
// Read with stringOption/numberOption/splitOption(...).
|
|
export const VALUE_FLAGS = new Set([
|
|
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
|
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
|
"code", "concurrency", "content", "content-file", "content-type", "contentFile",
|
|
"contentType", "contextLines", "corp", "corp-id", "corpId", "date",
|
|
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
|
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
|
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
|
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
|
|
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
|
"environment", "expire", "expiresIn", "fields", "file", "flow-concurrency",
|
|
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
|
|
"from-link", "host", "humanResult", "id", "input", "integration",
|
|
"json", "key-id", "keyId", "keyword", "level", "limit",
|
|
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
|
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
|
"n", "name", "note", "o", "offset", "out",
|
|
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
|
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
|
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
|
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
|
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
|
|
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
|
"reuseWindow", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
|
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
|
|
"sealUrl", "search", "secret", "selector", "sign-key", "signKey",
|
|
"simulationBatchId", "since", "sn", "sn-prefix", "sn-suffix", "snPrefix",
|
|
"snSuffix", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
|
"sourceDocumentSN", "sourceSystem", "staff-id", "staff-name", "staff-phone", "staffId",
|
|
"staffName", "staffPhone", "start", "start-date", "start-time", "startDate",
|
|
"startTime", "state", "status", "strictness", "tag", "tag-id",
|
|
"tagId", "tags", "target", "target-corp", "targetCorp", "task-mode",
|
|
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
|
|
"timeout", "timezone", "title", "to", "token", "tokenId",
|
|
"type", "until", "url", "userId", "version-name", "versionName",
|
|
"webhook", "workflow-type-id", "workflowTypeId"
|
|
]);
|
|
|
|
// Registered flags. Unknown flags are rejected.
|
|
export const KNOWN_FLAGS = new Set([
|
|
"V", "access-token", "accessToken", "add", "all", "app-key",
|
|
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
|
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
|
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
|
|
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
|
"content-file", "content-type", "contentFile", "contentType", "contextLines", "corp",
|
|
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
|
|
"default", "departmentId", "dept", "desc", "description", "description-file",
|
|
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
|
|
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
|
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
|
|
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
|
|
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
|
"environment", "exclude-deleted", "expire", "expiresIn", "f", "fail-on-flips",
|
|
"fields", "file", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
|
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
|
"full", "h", "help", "hose", "hose-sso", "hoseSso",
|
|
"host", "humanResult", "id", "include-deleted", "include-simulation", "include-unchanged",
|
|
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
|
"key-id", "keyId", "keyword", "level", "limit", "lines",
|
|
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
|
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
|
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
|
|
"note", "o", "offset", "out", "out-dir", "outDir",
|
|
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
|
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
|
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
|
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
|
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
|
"recordId", "recordIds", "refresh", "reject-node", "rejectNode", "repo",
|
|
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
|
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
|
|
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
|
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
|
"selector", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
|
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
|
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
|
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
|
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
|
|
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
|
|
"startDate", "startTime", "state", "status", "strict", "strictness",
|
|
"summary", "tag", "tag-id", "tagId", "tags", "target",
|
|
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
|
|
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
|
|
"to", "to-downloads", "toDownloads", "token", "tokenId", "type",
|
|
"until", "url", "userId", "v", "version", "version-name",
|
|
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
|
|
"workspace", "yes"
|
|
]);
|
|
|
|
export function parseArgs(argv: string[]): ParsedArgs {
|
|
const command: string[] = [];
|
|
const options: Record<string, string | boolean> = {};
|
|
let json: unknown;
|
|
|
|
for (let index = 0; index < argv.length; index += 1) {
|
|
const arg = argv[index];
|
|
if (!arg) continue;
|
|
|
|
if (arg === "--json") {
|
|
const raw = argv[index + 1];
|
|
if (!raw) throw usageError("--json requires a JSON object argument");
|
|
try {
|
|
json = JSON.parse(raw);
|
|
} catch (error) {
|
|
throw usageError(`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
if (arg.startsWith("-")) {
|
|
const raw = arg.replace(/^-+/, "");
|
|
if (raw.includes("=")) {
|
|
const eqIdx = raw.indexOf("=");
|
|
const key = raw.slice(0, eqIdx);
|
|
const val = raw.slice(eqIdx + 1);
|
|
options[key] = val;
|
|
continue;
|
|
}
|
|
|
|
if (!KNOWN_FLAGS.has(raw)) {
|
|
throw usageError(`Unknown option: --${raw}.${suggestFlag(raw)}`);
|
|
}
|
|
|
|
if (BOOLEAN_FLAGS.has(raw)) {
|
|
options[raw] = true;
|
|
continue;
|
|
}
|
|
|
|
if (VALUE_FLAGS.has(raw)) {
|
|
const next = argv[index + 1];
|
|
if (next === undefined || next.startsWith("--") || (next.startsWith("-") && !isNegativeNumber(next))) {
|
|
throw usageError(`Option --${raw} requires a value.`);
|
|
}
|
|
options[raw] = next;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
// Ambiguous flag (f / h / version): legacy next-token heuristic.
|
|
const next = argv[index + 1];
|
|
if (!next || next.startsWith("-")) {
|
|
options[raw] = true;
|
|
} else {
|
|
options[raw] = next;
|
|
index += 1;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
command.push(arg);
|
|
}
|
|
|
|
return { command, options, json };
|
|
}
|
|
|
|
function isNegativeNumber(token: string): boolean {
|
|
return /^-\d/.test(token) || /^-\.\d/.test(token);
|
|
}
|
|
|
|
/** Closest registered flag within edit distance 2, for `--limitt` -> `--limit`. */
|
|
function suggestFlag(flag: string): string {
|
|
let best: string | undefined;
|
|
let bestDistance = 3;
|
|
for (const candidate of KNOWN_FLAGS) {
|
|
const distance = editDistance(flag, candidate);
|
|
if (distance < bestDistance) {
|
|
bestDistance = distance;
|
|
best = candidate;
|
|
}
|
|
}
|
|
return best ? ` Did you mean --${best}?` : "";
|
|
}
|
|
|
|
function editDistance(a: string, b: string): number {
|
|
if (a === b) return 0;
|
|
const rows = a.length + 1;
|
|
const cols = b.length + 1;
|
|
const matrix: number[][] = Array.from({ length: rows }, (_, i) =>
|
|
Array.from({ length: cols }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))
|
|
);
|
|
for (let i = 1; i < rows; i += 1) {
|
|
for (let j = 1; j < cols; j += 1) {
|
|
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
matrix[i]![j] = Math.min(
|
|
matrix[i - 1]![j]! + 1,
|
|
matrix[i]![j - 1]! + 1,
|
|
matrix[i - 1]![j - 1]! + cost
|
|
);
|
|
}
|
|
}
|
|
return matrix[rows - 1]![cols - 1]!;
|
|
}
|
|
|
|
export function jsonObject(value: unknown): Record<string, unknown> {
|
|
if (value === undefined) return {};
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
throw usageError("--json must be an object");
|
|
}
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
export function stringOption(value: string | boolean | undefined): string | undefined {
|
|
return typeof value === "string" ? value : undefined;
|
|
}
|
|
|
|
export function numberOption(value: string | boolean | undefined): number | undefined {
|
|
if (typeof value !== "string") return undefined;
|
|
const number = Number(value);
|
|
if (!Number.isFinite(number)) throw usageError(`Invalid number: ${value}`);
|
|
return number;
|
|
}
|
|
|
|
export function splitOption(value: string | boolean | undefined): string[] | undefined {
|
|
if (typeof value !== "string") return undefined;
|
|
const items = value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
return items.length ? items : undefined;
|
|
}
|
|
|
|
export function booleanOption(value: string | boolean | undefined): boolean | undefined {
|
|
if (value === undefined) return undefined;
|
|
if (typeof value === "boolean") return value;
|
|
if (value === "true") return true;
|
|
if (value === "false") return false;
|
|
throw usageError(`Invalid boolean: ${value}`);
|
|
}
|
|
|
|
export function requiredString(input: Record<string, unknown>, key: string): string {
|
|
const value = optionalString(input, key);
|
|
if (!value) throw new Error(`Missing required JSON field: ${key}`);
|
|
return value;
|
|
}
|
|
|
|
export function requiredStringAlias(input: Record<string, unknown>, keys: string[]): string {
|
|
for (const key of keys) {
|
|
const value = optionalString(input, key);
|
|
if (value) return value;
|
|
}
|
|
throw new Error(`Missing required JSON field: ${keys.join(" or ")}`);
|
|
}
|
|
|
|
export function optionalString(input: Record<string, unknown>, key: string): string | undefined {
|
|
const value = input[key];
|
|
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
}
|
|
|
|
export function optionalNumber(input: Record<string, unknown>, key: string): number | undefined {
|
|
const value = input[key];
|
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
}
|
|
|
|
export function inferCorpIdFromStaffId(staffId: string): string | undefined {
|
|
const [corpId] = staffId.split(":", 1);
|
|
return corpId || undefined;
|
|
}
|
|
|
|
export function safeFileName(value: string): string {
|
|
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
}
|
|
|
|
export function parseStateMode(value: string): boolean {
|
|
const normalized = value.trim().toLowerCase();
|
|
if (["stateful", "state", "有状态"].includes(normalized)) return true;
|
|
if (["stateless", "无状态"].includes(normalized)) return false;
|
|
throw new Error("Invalid config mode. Use stateful or stateless.");
|
|
}
|
|
|
|
export function parseRuleVersionSelector(value: string) {
|
|
if (value === "latest") return { latest: true };
|
|
const versionNumber = Number(value);
|
|
if (Number.isInteger(versionNumber) && versionNumber > 0) {
|
|
return { versionNumber };
|
|
}
|
|
return { versionId: value };
|
|
}
|
|
|
|
export function ruleVersionSearchOptions(value?: string) {
|
|
if (!value) return {};
|
|
const selector = parseRuleVersionSelector(value);
|
|
if ("latest" in selector) {
|
|
return {
|
|
ruleVersionScope: "version",
|
|
latestRuleVersion: true
|
|
};
|
|
}
|
|
if ("versionNumber" in selector) {
|
|
return {
|
|
ruleVersionScope: "version",
|
|
ruleVersionNumber: selector.versionNumber
|
|
};
|
|
}
|
|
return {
|
|
ruleVersionScope: "version",
|
|
ruleVersionId: selector.versionId
|
|
};
|
|
}
|
|
|
|
export function ruleVersionContextOptions(value?: string) {
|
|
if (!value) return {};
|
|
const selector = parseRuleVersionSelector(value);
|
|
if ("latest" in selector) {
|
|
return { latestRuleVersion: true };
|
|
}
|
|
if ("versionNumber" in selector) {
|
|
return { ruleVersionNumber: selector.versionNumber };
|
|
}
|
|
return { ruleVersionId: selector.versionId };
|
|
}
|
|
|
|
export function ruleVersionGetOptions(value?: string) {
|
|
if (!value) return {};
|
|
const selector = parseRuleVersionSelector(value);
|
|
if ("latest" in selector) {
|
|
return { latest: true };
|
|
}
|
|
if ("versionNumber" in selector) {
|
|
return { versionNumber: selector.versionNumber };
|
|
}
|
|
return { versionId: selector.versionId };
|
|
}
|
|
|
|
export function parseWebhookMode(value?: string): WebhookMode | undefined {
|
|
if (!value) return undefined;
|
|
const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
|
|
const aliases: Record<string, WebhookMode> = {
|
|
assisted: "assisted",
|
|
辅助: "assisted",
|
|
semi_automatic: "semi_automatic",
|
|
半自动: "semi_automatic",
|
|
fully_automatic: "fully_automatic",
|
|
全自动: "fully_automatic"
|
|
};
|
|
const mode = aliases[normalized];
|
|
if (!mode) {
|
|
throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
|
|
}
|
|
return mode;
|
|
}
|
|
|
|
export function webhookRateOption(options: Record<string, string | boolean>): number | undefined {
|
|
const value = numberOption(
|
|
options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]
|
|
);
|
|
if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) {
|
|
throw new Error("Webhook auto approval rate must be an integer between 0 and 100");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
export function webhookShowSecretOption(options: Record<string, string | boolean>): boolean | undefined {
|
|
return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]);
|
|
}
|
|
|
|
export function materialPackFilePolicyOptions(
|
|
options: Record<string, string | boolean>
|
|
): MaterialPackFilePolicyPatch | undefined {
|
|
const clearMaxFileSize = booleanOption(
|
|
options.clearMaxFileSize ?? options["clear-max-file-size"]
|
|
) === true;
|
|
const minFileSizeBytes = numberOption(
|
|
options.minFileSizeBytes ?? options["min-file-size-bytes"] ?? options.minFileSize ?? options["min-file-size"]
|
|
);
|
|
const maxFileSizeBytes = numberOption(
|
|
options.maxFileSizeBytes ?? options["max-file-size-bytes"] ?? options.maxFileSize ?? options["max-file-size"]
|
|
);
|
|
const allowedExtensions = splitOption(
|
|
options.allowedExtensions ?? options["allowed-extensions"] ?? options.extensions
|
|
);
|
|
|
|
if (
|
|
minFileSizeBytes === undefined &&
|
|
maxFileSizeBytes === undefined &&
|
|
allowedExtensions === undefined &&
|
|
!clearMaxFileSize
|
|
) {
|
|
return undefined;
|
|
}
|
|
|
|
return {
|
|
minFileSizeBytes,
|
|
maxFileSizeBytes: clearMaxFileSize ? null : maxFileSizeBytes,
|
|
allowedExtensions
|
|
};
|
|
}
|