From 918acf4b2b68b51ff075332cfd35b42ac339fc63 Mon Sep 17 00:00:00 2001 From: Dennis Chen Date: Thu, 3 Dec 2026 22:41:43 +0000 Subject: [PATCH] feat: generate experimental API commands with compatibility guidance Co-authored-by: Codex --- README.md | 23 ++ package.json | 2 +- scripts/generate-experimental.ts | 13 + src/codegen/experimental.test.ts | 91 ++++++ src/codegen/experimental.ts | 274 +++++++++++++++++ src/codegen/fixtures/experimental.json | 144 +++++++++ src/commands/experimental.test.ts | 391 +++++++++++++++++++++++++ src/commands/experimental.ts | 173 +++++++++++ src/commands/index.ts | 2 + src/test-support.ts | 2 +- 10 files changed, 1113 insertions(+), 2 deletions(-) create mode 100644 scripts/generate-experimental.ts create mode 100644 src/codegen/experimental.test.ts create mode 100644 src/codegen/experimental.ts create mode 100644 src/codegen/fixtures/experimental.json create mode 100644 src/commands/experimental.test.ts create mode 100644 src/commands/experimental.ts diff --git a/README.md b/README.md index 40fad41..9eeb2d8 100644 --- a/README.md +++ b/README.md @@ -168,3 +168,26 @@ VANTA_VERSION=0.2.0 pnpm build:binaries ``` The typed API client is generated from [`api-spec.json`](api-spec.json) with [`@hey-api/openapi-ts`](https://heyapi.dev/). + +Experimental APIs appear under `vanta experimental `. Names come +from the OpenAPI operation ID converted to kebab-case, so `trySomethingNew` becomes +`vanta experimental try-something-new`. Experimental APIs do not need to follow +the stable API's resource and verb naming conventions. + +Run `vanta experimental --help` to discover available commands, then use a +command's `--help` to discover its flags. Experimental endpoints may change or be +removed without notice, and commands may require a CLI update. Warnings go to +stderr so stdout remains available for response data. +If an experimental endpoint fails or returns an incompatible response, the CLI +includes the HTTP status and original error, explains that the endpoint may have +changed or been removed, and suggests updating the CLI. Authentication, rate +limits, network failures, and local input or file errors keep their specific +errors. + +`pnpm generate` also generates the experimental command catalog from operations +marked `x-vanta-experimental: true` or paths under `/experimental/`. The request +path is preserved; the API base stays at `/v1`. Path, query, header, and multipart +inputs become flags using their original names in kebab-case. JSON bodies use +`--json` or `--file`; downloads support `--output`. Stable commands are maintained +separately. A build whose spec has no experimental operations still exposes +`vanta experimental --help` and explains that no endpoints are included. diff --git a/package.json b/package.json index 9354ac1..d13c982 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ ], "type": "module", "scripts": { - "generate": "openapi-ts", + "generate": "openapi-ts && tsx scripts/generate-experimental.ts", "dev": "tsx src/cli.ts", "build": "pnpm run generate && tsup", "typecheck": "tsc --noEmit", diff --git a/scripts/generate-experimental.ts b/scripts/generate-experimental.ts new file mode 100644 index 0000000..a97c0cb --- /dev/null +++ b/scripts/generate-experimental.ts @@ -0,0 +1,13 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { generateExperimentalOperations } from "../src/codegen/experimental.js"; + +const spec = JSON.parse( + await readFile(process.argv[2] ?? "api-spec.json", "utf8"), +); +const operations = generateExperimentalOperations(spec); +await writeFile( + "src/generated/experimental.gen.ts", + `// Generated by scripts/generate-experimental.ts. Do not edit.\n` + + `import type { ExperimentalOperation } from "../codegen/experimental.js";\n` + + `export const experimentalOperations: ExperimentalOperation[] = ${JSON.stringify(operations, null, 2)};\n`, +); diff --git a/src/codegen/experimental.test.ts b/src/codegen/experimental.test.ts new file mode 100644 index 0000000..54a0e8e --- /dev/null +++ b/src/codegen/experimental.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { readFileSync } from "node:fs"; +import { generateExperimentalOperations } from "./experimental.js"; + +const fixture = () => + JSON.parse( + readFileSync( + new URL("./fixtures/experimental.json", import.meta.url), + "utf8", + ), + ); + +describe("experimental codegen", () => { + it("uses operation IDs regardless of path conventions and keeps stable operations out", () => { + const ops = generateExperimentalOperations(fixture()); + assert.deepEqual( + ops.map((op) => op.command), + ["attach-evidence", "fetch-report", "ping", "try-something-new"], + ); + const op = ops.find((op) => op.command === "try-something-new")!; + assert.equal(op.path, "/experimental/odd:route/{subjectId}/doSomething"); + assert.equal(op.method, "POST"); + assert.equal(op.description, "Try a new operation"); + assert.deepEqual(op.body, { type: "json", required: true }); + assert.equal(op.inputs.filter((p) => p.name === "mode").length, 1); + assert.match( + op.inputs.find((p) => p.name === "mode")!.description, + /Processing mode.*FAST, THOROUGH/, + ); + assert.equal(op.inputs.find((p) => p.name === "subjectId")!.required, true); + assert.equal( + op.inputs.find((p) => p.name === "subjectId")!.placeholder, + "id", + ); + assert.match( + op.inputs.find((p) => p.name === "after")!.description, + /ISO 8601 timestamp/, + ); + assert.equal(op.inputs.find((p) => p.name === "tag")!.array, true); + assert.equal(op.inputs.find((p) => p.name === "enabled")!.kind, "boolean"); + }); + + it("recognizes multipart files and downloads", () => { + const ops = generateExperimentalOperations(fixture()); + const upload = ops.find((op) => op.command === "attach-evidence")!; + assert.deepEqual(upload.body, { type: "multipart", required: true }); + assert.equal(upload.inputs[0].kind, "file"); + assert.equal(upload.inputs[0].required, true); + assert.equal( + ops.find((op) => op.command === "fetch-report")!.download, + true, + ); + }); + + it("handles promotion by removing the experimental path and marker", () => { + const spec = fixture(); + spec.paths["/ping"] = spec.paths["/experimental/ping"]; + delete spec.paths["/experimental/ping"]; + assert( + !generateExperimentalOperations(spec).some((op) => op.command === "ping"), + ); + }); + + it("rejects ambiguous names and flags during generation", () => { + const missing = fixture(); + delete missing.paths["/experimental/ping"].get.operationId; + assert.throws(() => generateExperimentalOperations(missing), /operationId/); + const duplicate = fixture(); + duplicate.paths["/experimental/ping"].get.operationId = "try-something-new"; + assert.throws(() => generateExperimentalOperations(duplicate), /duplicate/); + const collision = fixture(); + collision.paths["/experimental/ping"].get.parameters = [ + { name: "fooBar", in: "query" }, + { name: "foo-bar", in: "header" }, + ]; + assert.throws( + () => generateExperimentalOperations(collision), + /Conflicting.*--foo-bar/, + ); + }); + + it("rejects a marked operation outside the experimental namespace", () => { + const spec = fixture(); + spec.paths["/controls"].get["x-vanta-experimental"] = true; + assert.throws( + () => generateExperimentalOperations(spec), + /must use \/experimental\//, + ); + }); +}); diff --git a/src/codegen/experimental.ts b/src/codegen/experimental.ts new file mode 100644 index 0000000..fd74ba9 --- /dev/null +++ b/src/codegen/experimental.ts @@ -0,0 +1,274 @@ +/** The small part of OpenAPI used to generate experimental CLI commands. */ +type Schema = { + $ref?: string; + type?: string; + format?: string; + description?: string; + enum?: unknown[]; + items?: Schema; + properties?: Record; + required?: string[]; +}; +type Parameter = { + $ref?: string; + name: string; + in: string; + description?: string; + required?: boolean; + schema?: Schema; +}; +type Media = { schema?: Schema }; +type RequestBody = { + $ref?: string; + required?: boolean; + content?: Record; +}; +type Operation = { + operationId?: string; + summary?: string; + description?: string; + "x-vanta-experimental"?: boolean; + parameters?: Parameter[]; + requestBody?: RequestBody; + responses?: Record< + string, + { $ref?: string; content?: Record } + >; +}; +type HttpMethod = + | "GET" + | "POST" + | "PUT" + | "PATCH" + | "DELETE" + | "HEAD" + | "OPTIONS"; +export type ExperimentalSpec = { + paths: Record>; +}; + +export type ExperimentalInput = { + name: string; + location: "path" | "query" | "header" | "body"; + flag: string; + description: string; + placeholder: string; + required: boolean; + array: boolean; + kind: "string" | "boolean" | "page-size" | "file"; +}; + +export type ExperimentalOperation = { + command: string; + description: string; + method: HttpMethod; + path: string; + inputs: ExperimentalInput[]; + body?: { type: "json" | "multipart"; required: boolean }; + download: boolean; +}; + +export function kebabCase(value: string): string { + return value + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2") + .replace(/([a-z0-9])([A-Z])/g, "$1-$2") + .replace(/[^a-zA-Z0-9]+/g, "-") + .replace(/^-|-$/g, "") + .toLowerCase(); +} + +/** Generate from operation IDs; experimental routes need no resource conventions. */ +export function generateExperimentalOperations( + spec: ExperimentalSpec, +): ExperimentalOperation[] { + function resolve(value: T): T { + const seen = new Set(); + while (value.$ref) { + const ref = value.$ref; + if (!ref.startsWith("#/") || seen.has(ref)) { + throw new Error(`Unsupported experimental API reference: ${ref}`); + } + seen.add(ref); + let target: unknown = spec; + for (const part of ref.slice(2).split("/")) { + target = (target as Record)?.[ + part.replace(/~1/g, "/").replace(/~0/g, "~") + ]; + } + if (!target || typeof target !== "object") { + throw new Error(`Missing experimental API reference: ${ref}`); + } + value = target as T; + } + return value; + } + + function input( + name: string, + location: ExperimentalInput["location"], + raw: Schema, + required: boolean, + description?: string, + ): ExperimentalInput { + const schema = resolve(raw); + const array = schema.type === "array"; + const item = array ? resolve(schema.items ?? {}) : schema; + const flag = kebabCase(name); + const kind = + item.format === "binary" + ? "file" + : item.type === "boolean" + ? "boolean" + : flag === "page-size" + ? "page-size" + : "string"; + const placeholder = + kind === "file" + ? "path" + : kind === "boolean" + ? "bool" + : /id$/i.test(name) || /ids$/i.test(name) + ? "id" + : item.format === "date-time" + ? "timestamp" + : item.format === "date" + ? "date" + : /^(q|query|search)$/i.test(name) + ? "query" + : kind === "page-size" + ? "n" + : item.enum + ? flag + : "text"; + const details = [description ?? schema.description ?? name]; + if (item.enum) details.push(`Choices: ${item.enum.join(", ")}`); + if (item.format === "date-time") details.push("ISO 8601 timestamp"); + if (array) details.push("(repeatable)"); + return { + name, + location, + flag, + description: details.join(". "), + placeholder, + required, + array, + kind, + }; + } + + const operations: ExperimentalOperation[] = []; + const names = new Set(["help"]); + for (const [path, item] of Object.entries(spec.paths)) { + for (const method of [ + "get", + "post", + "put", + "patch", + "delete", + "head", + "options", + ]) { + const op = item[method] as Operation | undefined; + if ( + !op || + !( + op["x-vanta-experimental"] === true || + path.startsWith("/experimental/") + ) + ) + continue; + if (!path.startsWith("/experimental/")) { + throw new Error( + `Experimental operation must use /experimental/: ${method} ${path}`, + ); + } + const command = kebabCase(op.operationId ?? ""); + if (!command || names.has(command)) { + throw new Error( + `Missing or duplicate experimental operationId: ${method} ${path}`, + ); + } + names.add(command); + const params = new Map(); + for (const raw of [ + ...(item.parameters ?? []), + ...(op.parameters ?? []), + ]) { + const param = resolve(raw); + params.set(`${param.in}:${param.name}`, param); + } + const inputs = [...params.values()].map((param) => { + if (!["path", "query", "header"].includes(param.in)) { + throw new Error( + `Unsupported experimental parameter location: ${param.in}`, + ); + } + return input( + param.name, + param.in as ExperimentalInput["location"], + param.schema ?? {}, + param.required === true || param.in === "path", + param.description, + ); + }); + let body: ExperimentalOperation["body"]; + if (op.requestBody) { + const request = resolve(op.requestBody); + const content = request.content ?? {}; + if (content["application/json"]) { + body = { type: "json", required: request.required === true }; + } else if (content["multipart/form-data"]) { + body = { type: "multipart", required: request.required === true }; + const schema = resolve(content["multipart/form-data"].schema ?? {}); + for (const [name, raw] of Object.entries(schema.properties ?? {})) { + inputs.push( + input( + name, + "body", + raw, + request.required === true && + (schema.required ?? []).includes(name), + ), + ); + } + } else { + throw new Error( + `Unsupported experimental request body: ${method} ${path}`, + ); + } + } + const download = Object.entries(op.responses ?? {}).some( + ([status, raw]) => + /^2/.test(status) && + Object.entries(resolve(raw).content ?? {}).some( + ([type, media]) => + resolve(media.schema ?? {}).format === "binary" || + !/json/.test(type), + ), + ); + const flags = new Set([ + "help", + ...(body?.type === "json" ? ["json", "file"] : []), + ...(download ? ["output"] : []), + ]); + for (const field of inputs) { + if (!field.flag || flags.has(field.flag)) { + throw new Error( + `Conflicting experimental flag --${field.flag}: ${command}`, + ); + } + flags.add(field.flag); + } + operations.push({ + command, + description: op.summary ?? op.description ?? op.operationId!, + method: method.toUpperCase() as HttpMethod, + path, + inputs, + body, + download, + }); + } + } + return operations.sort((a, b) => a.command.localeCompare(b.command)); +} diff --git a/src/codegen/fixtures/experimental.json b/src/codegen/fixtures/experimental.json new file mode 100644 index 0000000..56214cc --- /dev/null +++ b/src/codegen/fixtures/experimental.json @@ -0,0 +1,144 @@ +{ + "openapi": "3.0.0", + "info": { "title": "Experimental CLI fixture", "version": "1" }, + "paths": { + "/controls": { + "get": { + "operationId": "listControls", + "responses": { "200": { "description": "OK" } } + } + }, + "/experimental/odd:route/{subjectId}/doSomething": { + "parameters": [ + { + "$ref": "#/components/parameters/Subject", + "name": "subjectId", + "in": "path" + }, + { + "name": "mode", + "in": "query", + "description": "Inherited mode", + "schema": { "type": "string" } + } + ], + "post": { + "operationId": "trySomethingNew", + "summary": "Try a new operation", + "description": "Experimental endpoint. May change without notice.", + "x-vanta-experimental": true, + "parameters": [ + { + "name": "mode", + "in": "query", + "description": "Processing mode", + "schema": { "type": "string", "enum": ["FAST", "THOROUGH"] } + }, + { + "name": "tag", + "in": "query", + "description": "Tags to include", + "schema": { "type": "array", "items": { "type": "string" } } + }, + { "name": "enabled", "in": "query", "schema": { "type": "boolean" } }, + { + "name": "pageSize", + "in": "query", + "schema": { "type": "integer" } + }, + { + "name": "after", + "in": "query", + "schema": { "type": "string", "format": "date-time" } + }, + { + "name": "X-Request-Id", + "in": "header", + "schema": { "type": "string" } + } + ], + "requestBody": { "$ref": "#/components/requestBodies/Payload" }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { "schema": { "type": "object" } } + } + } + } + } + }, + "/experimental/weirdUpload": { + "post": { + "operationId": "attachEvidence", + "x-vanta-experimental": true, + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": ["evidence"], + "properties": { + "evidence": { + "type": "string", + "format": "binary", + "description": "Evidence file" + }, + "labels": { "type": "array", "items": { "type": "string" } }, + "approved": { "type": "boolean" } + } + } + } + } + }, + "responses": { "201": { "description": "Created" } } + } + }, + "/experimental/fetch-report": { + "get": { + "operationId": "fetchReport", + "x-vanta-experimental": true, + "responses": { + "200": { + "description": "Report", + "content": { + "application/octet-stream": { + "schema": { "type": "string", "format": "binary" } + } + } + } + } + } + }, + "/experimental/ping": { + "get": { + "operationId": "ping", + "responses": { "204": { "description": "OK" } } + } + }, + "/experimental-other/ignore": { + "get": { + "operationId": "ignore", + "responses": { "200": { "description": "OK" } } + } + } + }, + "components": { + "parameters": { + "Subject": { + "name": "subjectId", + "in": "path", + "required": true, + "description": "Subject ID", + "schema": { "type": "string" } + } + }, + "requestBodies": { + "Payload": { + "required": true, + "content": { "application/json": { "schema": { "type": "object" } } } + } + } + } +} diff --git a/src/commands/experimental.test.ts b/src/commands/experimental.test.ts new file mode 100644 index 0000000..098d083 --- /dev/null +++ b/src/commands/experimental.test.ts @@ -0,0 +1,391 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, it, mock } from "node:test"; +import { Command } from "commander"; +import { generateExperimentalOperations } from "../codegen/experimental.js"; +import { jsonResponse, stubFetch, useTempHome } from "../test-support.js"; +import { registerExperimentalCommand } from "./experimental.js"; + +const operations = generateExperimentalOperations( + JSON.parse( + readFileSync( + new URL("../codegen/fixtures/experimental.json", import.meta.url), + "utf8", + ), + ), +); + +describe("experimental commands", () => { + let home: Awaited>; + let net: ReturnType; + let dryRun: boolean; + let output: string; + let warnings: string; + + function program() { + const cmd = new Command().exitOverride().configureOutput({ + writeOut: (text) => { + output += text; + }, + writeErr: (text) => { + warnings += text; + }, + }); + registerExperimentalCommand( + cmd, + () => ({ + dryRun, + verbose: false, + pretty: false, + agentMode: false, + apiBase: "https://api.vanta.com/v1", + clientId: "test-client", + clientSecret: "test-secret", + }), + operations, + ); + return cmd; + } + + beforeEach(async () => { + home = await useTempHome(); + dryRun = false; + output = ""; + warnings = ""; + mock.method(process.stdout, "write", (chunk: string) => { + output += chunk; + return true; + }); + mock.method(process.stderr, "write", (chunk: string) => { + warnings += chunk; + return true; + }); + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : jsonResponse(200, { ok: true }), + ); + }); + + afterEach(async () => { + net.restore(); + mock.restoreAll(); + await home.restore(); + }); + + it("discovers flags, choices, repeatability and the experimental warning in help", () => { + const cmd = program().commands[0].commands.find( + (cmd) => cmd.name() === "try-something-new", + )!; + const help = cmd.helpInformation(); + assert.match(help, /--subject-id /); + assert.match(help, /FAST, THOROUGH/); + assert.match(help, /repeatable/); + assert.match(help, /--after /); + assert.match(help, /--json /); + assert.match(help, /--file /); + assert( + !program().commands.some((cmd) => cmd.name() === "try-something-new"), + ); + }); + + it("preserves arbitrary paths and values, sends bearer auth, and warns on stderr", async () => { + await program().parseAsync( + [ + "experimental", + "try-something-new", + "--subject-id", + "s/a b", + "--mode", + "FUTURE", + "--tag", + "one", + "--tag", + "two", + "--enabled", + "false", + "--page-size", + "-4", + "--x-request-id", + "req-1", + "--json", + '{"count":"001"}', + ], + { from: "user" }, + ); + const req = net.requests.at(-1)!; + const url = new URL(req.url); + assert.equal( + url.pathname, + "/v1/experimental/odd:route/s%2Fa%20b/doSomething", + ); + assert.equal(url.searchParams.get("mode"), "FUTURE"); + assert.deepEqual(url.searchParams.getAll("tag"), ["one", "two"]); + assert.equal(url.searchParams.get("enabled"), "false"); + assert.equal(url.searchParams.get("pageSize"), "-4"); + assert.equal(req.headers.get("authorization"), "Bearer test-token"); + assert.equal(req.headers.get("x-request-id"), "req-1"); + assert.equal(req.method, "POST"); + assert.equal(req.body, '{"count":"001"}'); + assert.deepEqual(JSON.parse(output), { ok: true }); + assert.match(warnings, /may change or be removed/); + }); + + it("reads JSON files and rejects missing or conflicting payloads before sending", async () => { + const file = join(home.dir, "body.json"); + await writeFile(file, '{"name":"example"}'); + await program().parseAsync( + [ + "experimental", + "try-something-new", + "--subject-id", + "s", + "--file", + file, + ], + { from: "user" }, + ); + assert.equal(net.requests.at(-1)!.body, '{"name":"example"}'); + const count = net.requests.length; + await assert.rejects( + program().parseAsync( + ["experimental", "try-something-new", "--subject-id", "s"], + { from: "user" }, + ), + /missing payload/, + ); + await assert.rejects( + program().parseAsync( + [ + "experimental", + "try-something-new", + "--subject-id", + "s", + "--json", + "{}", + "--file", + file, + ], + { from: "user" }, + ), + /either --json or --file/, + ); + await assert.rejects( + program().parseAsync( + ["experimental", "try-something-new", "--json", "{}"], + { from: "user" }, + ), + /required option/, + ); + assert.equal(net.requests.length, count); + }); + + it("uploads multipart file bytes with repeated fields and the correct content type", async () => { + const file = join(home.dir, "evidence.txt"); + await writeFile(file, "sample evidence"); + await program().parseAsync( + [ + "experimental", + "attach-evidence", + "--evidence", + file, + "--labels", + "a", + "--labels", + "b", + "--approved", + "false", + ], + { from: "user" }, + ); + const req = net.requests.at(-1)!; + assert.match( + req.headers.get("content-type")!, + /^multipart\/form-data; boundary=/, + ); + assert.match(req.body, /filename="evidence.txt"/); + assert.match(req.body, /sample evidence/); + assert.equal(req.body.match(/name="labels"/g)?.length, 2); + assert.match(req.body, /name="approved"\r\n\r\nfalse/); + }); + + it("downloads bytes to --output and preserves removed endpoint errors", async () => { + net.restore(); + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : new Response(new Uint8Array([0, 255, 1]), { + headers: { "content-type": "application/octet-stream" }, + }), + ); + const file = join(home.dir, "report.bin"); + await program().parseAsync( + ["experimental", "fetch-report", "--output", file], + { from: "user" }, + ); + assert.deepEqual([...(await readFile(file))], [0, 255, 1]); + net.restore(); + const error = { + message: "Experimental endpoint not found. It may have been removed.", + }; + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : jsonResponse(404, error), + ); + await assert.rejects( + program().parseAsync(["experimental", "fetch-report", "--output", file], { + from: "user", + }), + (err) => { + assert(err instanceof Error); + assert.match(err.message, /fetch-report.*is unavailable.*HTTP 404/); + assert.match(err.message, /endpoint may have changed or been removed/); + assert.match(err.message, /Update the Vanta CLI/); + assert.match(err.message, /Experimental endpoint not found/); + assert.deepEqual(err.cause, error); + return true; + }, + ); + assert.deepEqual([...(await readFile(file))], [0, 255, 1]); + }); + + it("explains incompatible endpoint failures while retaining the full API error", async () => { + for (const status of [400, 404, 405, 410, 422, 500, 503]) { + net.restore(); + const error = { + message: "Request no longer supported", + fields: { newField: "Required" }, + }; + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : jsonResponse(status, error), + ); + await assert.rejects( + program().parseAsync(["experimental", "ping"], { from: "user" }), + (err) => { + assert(err instanceof Error); + assert.match( + err.message, + new RegExp(`vanta experimental ping.*HTTP ${status}`), + ); + assert.match(err.message, /command may no longer be available/); + assert.match(err.message, /Update the Vanta CLI/); + assert.match(err.message, /newField/); + assert.deepEqual(err.cause, error); + return true; + }, + ); + } + assert.equal(output, "", "failures must not emit response data to stdout"); + }); + + it("handles plain text, empty errors, and changed JSON responses", async () => { + for (const [status, body, contentType, detail] of [ + [404, "Route was removed", "text/plain", /Route was removed/], + [410, "", "text/plain", /HTTP 410/], + [200, "{broken json", "application/json", /API error:/], + ] as const) { + net.restore(); + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : new Response(body, { + status, + headers: { "content-type": contentType }, + }), + ); + await assert.rejects( + program().parseAsync(["experimental", "ping"], { from: "user" }), + (err) => { + assert(err instanceof Error); + assert.match( + err.message, + /endpoint may have changed or been removed/, + ); + assert.match(err.message, detail); + return true; + }, + ); + } + }); + + it("preserves authentication and rate-limit errors without suggesting a changed endpoint", async () => { + for (const status of [401, 403, 429]) { + net.restore(); + const error = { message: `Specific failure ${status}` }; + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : jsonResponse(status, error), + ); + await assert.rejects( + program().parseAsync(["experimental", "ping"], { from: "user" }), + (err) => { + assert.deepEqual(err, error); + return true; + }, + ); + } + }); + + it("preserves transport and local output failures", async () => { + net.restore(); + const offline = new TypeError("Connection failed"); + net = stubFetch((req) => { + if (req.url.endsWith("/oauth/token")) + return jsonResponse(200, { + access_token: "test-token", + expires_in: 3600, + }); + throw offline; + }); + await assert.rejects( + program().parseAsync(["experimental", "ping"], { from: "user" }), + (err) => err === offline, + ); + net.restore(); + net = stubFetch((req) => + req.url.endsWith("/oauth/token") + ? jsonResponse(200, { access_token: "test-token", expires_in: 3600 }) + : new Response("report", { + headers: { "content-type": "application/octet-stream" }, + }), + ); + await assert.rejects( + program().parseAsync( + [ + "experimental", + "fetch-report", + "--output", + join(home.dir, "missing", "report.bin"), + ], + { from: "user" }, + ), + /ENOENT/, + ); + }); + + it("dry runs never load credentials or send requests", async () => { + dryRun = true; + await program().parseAsync( + [ + "experimental", + "try-something-new", + "--subject-id", + "s", + "--json", + "{}", + ], + { from: "user" }, + ); + assert.match( + output, + /DRY RUN POST https:\/\/api.vanta.com\/v1\/experimental\/odd:route\/s\/doSomething/, + ); + assert.equal(net.requests.length, 0); + }); +}); diff --git a/src/commands/experimental.ts b/src/commands/experimental.ts new file mode 100644 index 0000000..3966dcb --- /dev/null +++ b/src/commands/experimental.ts @@ -0,0 +1,173 @@ +import { Command, Option } from "commander"; +import type { ExperimentalOperation } from "../codegen/experimental.js"; +import { experimentalOperations } from "../generated/experimental.gen.js"; +import { formDataBodySerializer } from "../generated/client/index.js"; +import { printResponse } from "../output.js"; +import { + addJsonFileOptions, + collectString, + parseOptionalBoolString, + readBinaryFile, + readJSONPayload, + withClient, + writeDownloadedMedia, + type GetFlags, +} from "./helpers.js"; + +const notice = + "Experimental: these endpoints may change or be removed without prior notice. Commands may require a CLI update."; + +function experimentalCommandError( + command: string, + error: unknown, + response?: Response, +): unknown { + // Missing responses indicate transport/request failures. Auth and rate-limit + // failures also have their own remedies, rather than implying a changed API. + if (!response || [401, 403, 429].includes(response.status)) return error; + + const details = + error instanceof Error + ? error.message + : typeof error === "string" + ? error + : JSON.stringify(error, null, 2); + const outcome = [404, 405, 410].includes(response.status) + ? "is unavailable" + : "failed"; + return new Error( + `Experimental command "vanta experimental ${command}" ${outcome} (HTTP ${response.status}).\n` + + "The underlying experimental endpoint may have changed or been removed, so this command may no longer be available. Update the Vanta CLI and try again.\n" + + `API error: ${details || response.statusText || "No error details returned"}`, + { cause: error }, + ); +} + +export function registerExperimentalCommand( + program: Command, + getFlags: GetFlags, + operations: ExperimentalOperation[] = experimentalOperations, +): void { + const experimental = program + .command("experimental") + .description( + "Use experimental APIs (may change or be removed without notice)", + ) + .addHelpText("after", `\n${notice}`); + if (!operations.length) { + experimental.addHelpText( + "after", + "\nNo experimental endpoints are included in this CLI build.", + ); + experimental.action(() => experimental.outputHelp()); + } + for (const operation of operations) { + const cmd = experimental + .command(operation.command) + .description(operation.description) + .addHelpText("after", `\n${notice}`); + for (const field of operation.inputs) { + const option = new Option( + `--${field.flag} <${field.placeholder}>`, + field.description, + ).makeOptionMandatory(field.required); + if (field.array) { + option.argParser((value: string, previous: string[] = []) => + collectString(value, previous), + ); + } + cmd.addOption(option); + } + if (operation.body?.type === "json") addJsonFileOptions(cmd); + if (operation.download) + cmd.option( + "--output ", + "Write downloaded file to this path (default: stdout)", + ); + cmd.action(async () => { + const opts = cmd.opts>(); + const path: Record = {}; + const query: Record = {}; + const headers: Record = {}; + const fields: Record = {}; + for (const field of operation.inputs) { + const value = + opts[ + cmd.options + .find((o) => o.long === `--${field.flag}`)! + .attributeName() + ]; + if (value === undefined) continue; + const convert = async (raw: string) => { + if (field.kind === "file") return readBinaryFile(raw); + if (field.kind === "boolean") + return parseOptionalBoolString(raw, field.flag); + if (field.kind === "page-size") { + const size = Number(raw); + if (!/^[+-]?\d+$/.test(raw) || !Number.isSafeInteger(size)) { + throw new Error("invalid --page-size: expected an integer"); + } + return size; + } + return raw; + }; + const parsed = field.array + ? await Promise.all((value as string[]).map(convert)) + : await convert(value as string); + if (field.location === "path") path[field.name] = parsed; + else if (field.location === "query") query[field.name] = parsed; + else if (field.location === "header") + headers[field.name] = Array.isArray(parsed) + ? parsed.join(",") + : String(parsed); + else fields[field.name] = parsed; + } + let body: unknown; + if (operation.body?.type === "json") { + if ( + operation.body.required || + opts.json !== undefined || + opts.file !== undefined + ) { + body = await readJSONPayload( + opts.json as string | undefined, + opts.file as string | undefined, + ); + } + headers["Content-Type"] = "application/json"; + } else if (operation.body?.type === "multipart") { + headers["Content-Type"] = null; + if (operation.body.required || Object.keys(fields).length) + body = fields; + } + process.stderr.write(`${notice}\n`); + await withClient(getFlags, async (api, flags) => { + const result = await api.client.request({ + url: operation.path, + method: operation.method, + security: [{ scheme: "bearer", type: "http" }], + path, + query, + headers, + body, + ...(operation.body?.type === "multipart" + ? formDataBodySerializer + : {}), + ...(operation.download ? { parseAs: "stream" as const } : {}), + }); + if (result.error !== undefined) + throw experimentalCommandError( + operation.command, + result.error, + result.response, + ); + if (operation.download) + await writeDownloadedMedia( + result.data, + opts.output as string | undefined, + ); + else printResponse(result.data, flags); + }); + }); + } +} diff --git a/src/commands/index.ts b/src/commands/index.ts index 1e0c686..81e516a 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -41,11 +41,13 @@ import { registerVendorDocumentTypesCommand } from "./vendor-document-types.js"; import { registerVendorQuestionnairesCommand } from "./vendor-questionnaires.js"; import { registerVendorSecurityIncidentAlertsCommand } from "./vendor-security-incident-alerts.js"; import type { GetFlags } from "./helpers.js"; +import { registerExperimentalCommand } from "./experimental.js"; export function registerApiCommands( program: Command, getFlags: GetFlags, ): void { + registerExperimentalCommand(program, getFlags); registerControlsCommand(program, getFlags); registerPoliciesCommand(program, getFlags); registerDocumentsCommand(program, getFlags); diff --git a/src/test-support.ts b/src/test-support.ts index b738770..1babb22 100644 --- a/src/test-support.ts +++ b/src/test-support.ts @@ -51,7 +51,7 @@ export function stubFetch( globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const req: RecordedRequest = { url: input instanceof Request ? input.url : String(input), - method: init?.method ?? "GET", + method: init?.method ?? (input instanceof Request ? input.method : "GET"), headers: new Headers(init?.headers), body: typeof init?.body === "string"