Add flag metadata to the argv parser: reject unknown flags, fix boolean/value ambiguity
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.
This commit is contained in:
1 parent
935ca015b1
commit
68fd90dbda
2 files changed
+339
No files matched your search
@@ -3,6 +3,131 @@ import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/
|
||||
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> = {};
|
||||
@@ -33,6 +158,27 @@ export function parseArgs(argv: string[]): ParsedArgs {
|
||||
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;
|
||||
@@ -49,6 +195,44 @@ export function parseArgs(argv: string[]): ParsedArgs {
|
||||
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)) {
|
||||
|
||||
Reference in new issue
Block a user