diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 223af572..8eb83b5a 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -123217,7 +123217,275 @@ } } ], - "namespaces": [], + "namespaces": [ + { + "segment": "api", + "commands": [ + { + "path": [ + "docs", + "api" + ], + "name": "search", + "parameters": [ + { + "role": "positional", + "name": "query", + "type": "string", + "required": false, + "summary": "Words, an endpoint, or a field path" + }, + { + "role": "flag", + "name": "query", + "type": "string", + "required": true, + "summary": "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] + }, + { + "role": "flag", + "name": "api", + "type": "string", + "required": true, + "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys.", + "validations": [ + { + "kind": "regex", + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" + } + ] + }, + { + "role": "flag", + "name": "api-version", + "type": "string", + "required": false, + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] + }, + { + "role": "flag", + "name": "include-deprecated", + "type": "boolean", + "required": false, + "summary": "Include deprecated operations" + }, + { + "role": "flag", + "name": "page", + "type": "number", + "required": false, + "summary": "Page number", + "defaultValue": "1", + "validations": [ + { + "kind": "range", + "min": "1" + } + ] + }, + { + "role": "flag", + "name": "size", + "type": "number", + "required": false, + "summary": "Results per page", + "defaultValue": "10", + "validations": [ + { + "kind": "range", + "min": "1", + "max": "50" + } + ] + } + ], + "summary": "Search the Elastic REST API reference for operations", + "intent": { + "requiresAuth": false + } + }, + { + "path": [ + "docs", + "api" + ], + "name": "get", + "parameters": [ + { + "role": "positional", + "name": "operation", + "type": "string", + "required": false, + "summary": "An endpoint such as 'GET /_cluster/health', or an operation id" + }, + { + "role": "flag", + "name": "endpoint", + "type": "string", + "required": false, + "summary": "A route as you would call it, e.g. 'GET /my-index/_search'", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] + }, + { + "role": "flag", + "name": "operation-id", + "type": "string", + "required": false, + "summary": "The OpenAPI operation id, e.g. 'cluster-health'", + "validations": [ + { + "kind": "regex", + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" + } + ] + }, + { + "role": "flag", + "name": "api", + "type": "string", + "required": true, + "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys.", + "validations": [ + { + "kind": "regex", + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" + } + ] + }, + { + "role": "flag", + "name": "api-version", + "type": "string", + "required": false, + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] + }, + { + "role": "flag", + "name": "include-body", + "type": "boolean", + "required": false, + "summary": "Include the page body" + } + ], + "summary": "Get one operation from the Elastic REST API reference, with its parameters and fields", + "intent": { + "requiresAuth": false + } + }, + { + "path": [ + "docs", + "api" + ], + "name": "list", + "parameters": [ + { + "role": "positional", + "name": "api", + "type": "string", + "required": false, + "summary": "API key; omit to list every API" + }, + { + "role": "flag", + "name": "api", + "type": "string", + "required": false, + "summary": "API key, e.g. 'elasticsearch'. Omit to list every API.", + "validations": [ + { + "kind": "regex", + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" + } + ] + }, + { + "role": "flag", + "name": "api-version", + "type": "string", + "required": false, + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] + }, + { + "role": "flag", + "name": "group", + "type": "string", + "required": false, + "summary": "List the operations of this group, e.g. 'cluster'. Without it, the API's groups are counted.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] + }, + { + "role": "flag", + "name": "page", + "type": "number", + "required": false, + "summary": "Page of a group listing", + "validations": [ + { + "kind": "range", + "min": "1" + } + ] + }, + { + "role": "flag", + "name": "size", + "type": "number", + "required": false, + "summary": "Operations per page of a group listing (default 10)", + "validations": [ + { + "kind": "range", + "min": "1", + "max": "50" + } + ] + } + ], + "summary": "List the Elastic REST APIs, the groups of one API, or the operations of one group", + "intent": { + "requiresAuth": false + } + } + ], + "namespaces": [], + "summary": "Search, read, and list operations in the Elastic REST API reference" + } + ], "summary": "Search, read, and ask questions about Elastic documentation", "options": [ { diff --git a/src/docs/api.ts b/src/docs/api.ts new file mode 100644 index 00000000..3906fd95 --- /dev/null +++ b/src/docs/api.ts @@ -0,0 +1,207 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { defineCommand, defineGroup } from '../factory.ts' +import type { OpaqueCommandHandle, JsonValue } from '../factory.ts' +import { docsApi } from './client.ts' +import { encodePathParam } from '../lib/path-encoding.ts' + +/** Injectable dependencies for the `docs api` commands. */ +export interface ApiDeps { + docsApi: typeof docsApi +} + +const defaultDeps: ApiDeps = { docsApi } + +// Schema keys are the docs API query parameters (`query` is sent as `q`, `api_version` as `version`); +// toKebabCase turns them into flags. +// A value that is more than whitespace. +const nonBlank = { type: 'string', pattern: '\\S' } +// A value sent as one path segment: non-blank, and not `.` or `..`. encodeURIComponent keeps those and URL parsing +// resolves them out of the path, so they would reach another route. One pattern, so --dry-run fails as a real run +// would and the rule shows in the CLI schema, which carries regex validations only. +const pathSegment = { type: 'string', pattern: '^(?!\\.\\.?$)[\\s\\S]*\\S' } +// Every operation lookup names its API: most operation ids and many routes exist in several APIs +// (elasticsearch and elasticsearch-serverless share most of theirs), so a lookup across APIs could only guess. +const api = { ...pathSegment, description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } +// Not --version: `elastic --version` prints the CLI's own version. +const apiVersion = { ...nonBlank, description: "API version: 'main' or a major such as '9'. Without it, the current version is used." } + +interface Operation { api: string; title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } +/** The path of one API's operations, with the key encoded into one segment. */ +function operationsOf (key: unknown): string { + return `/apis/${encodePathParam(String(key))}/operations` +} + +interface Field { path: string; type: string; location: string; description: string } + +function absUrl (url: string): string { + return url.startsWith('/') ? `https://www.elastic.co${url}` : url +} + +function opLine (o: Operation): string { + return `${o.method.padEnd(7)}${o.path} (${o.operationId})${o.deprecated === true ? ' [deprecated]' : ''}\n ${absUrl(o.url)}\n` +} + +function fieldLine (f: Field): string { + return ` ${f.location.padEnd(9)}${f.path} <${f.type}>${f.description !== '' ? ` ${f.description.split('\n')[0]!}` : ''}\n` +} + +interface ApiCommandConfig { + name: string + description: string + properties: Record + /** Further JSON Schema keywords on the input object, such as `required` or `oneOf`. */ + rules?: Record + positionalArg: { name: string; description: string } + /** Maps the positional value onto input fields; the factory applies it before validation. */ + fromArg: (arg: string) => Record + /** Sends the one request; `call` GETs a path under `/_api/v1`. */ + request: (params: Record, call: ApiDeps['docsApi']) => Promise + format: (reply: Record) => string +} + +function apiCommand (config: ApiCommandConfig, deps: ApiDeps): OpaqueCommandHandle { + return defineCommand({ + name: config.name, + description: config.description, + input: { type: 'object', properties: config.properties, additionalProperties: false, ...config.rules }, + positionalArg: { ...config.positionalArg, required: false, toInput: (arg) => config.fromArg(arg.trim()) }, + handler: async (parsed): Promise => { + const params: Record = { ...(parsed.input ?? {}) } + try { + return await config.request(params, deps.docsApi) as JsonValue + } catch (err) { + // encodePathParam refuses a dot segment with input_error, which only --no-validate lets through. + const code = (err as { code?: unknown }).code === 'input_error' ? 'input_error' : 'docs_error' + return { error: { code, message: err instanceof Error ? err.message : String(err) } } + } + }, + formatOutput: (result: JsonValue): string => { + // --output-fields can strip the keys format() reads; fall back to plain JSON then. + try { return config.format(result as Record) } catch { return JSON.stringify(result, null, 2) + '\n' } + }, + }) +} + +/** `elastic docs api search`: find REST API operations by words, route, or field path. */ +export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueCommandHandle { + return apiCommand({ + name: 'search', + description: 'Search the Elastic REST API reference for operations', + properties: { + query: { ...nonBlank, description: "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" }, + api, + api_version: apiVersion, + include_deprecated: { type: 'boolean', description: 'Include deprecated operations' }, + page: { type: 'integer', minimum: 1, description: 'Page number', default: 1 }, + size: { type: 'integer', minimum: 1, maximum: 50, description: 'Results per page', default: 10 }, + }, + rules: { required: ['query', 'api'] }, + positionalArg: { name: 'query', description: 'Words, an endpoint, or a field path' }, + fromArg: (query) => ({ query }), + request: async ({ query, api: key, api_version: version, ...params }, call) => call(operationsOf(key), { q: query, version, ...params }), + format: (reply) => { + const results = reply['results'] as Array<{ operation: Operation; matchedFields?: Field[] }> + if (results.length === 0) return 'No operations found.\n' + let out = '' + for (const r of results) { + out += opLine(r.operation) + for (const f of r.matchedFields ?? []) out += fieldLine(f) + out += '\n' + } + return out + `${results.length} of ${String(reply['totalHits'])} operations\n` + }, + }, deps) +} + +/** `elastic docs api get`: read one REST API operation with its fields. */ +export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommandHandle { + return apiCommand({ + name: 'get', + description: 'Get one operation from the Elastic REST API reference, with its parameters and fields', + properties: { + endpoint: { ...nonBlank, description: "A route as you would call it, e.g. 'GET /my-index/_search'" }, + operation_id: { ...pathSegment, description: "The OpenAPI operation id, e.g. 'cluster-health'" }, + api, + api_version: apiVersion, + include_body: { type: 'boolean', description: 'Include the page body' }, + }, + // Exactly one way to name the operation. + rules: { required: ['api'], oneOf: [{ required: ['endpoint'] }, { required: ['operation_id'] }] }, + positionalArg: { name: 'operation', description: "An endpoint such as 'GET /_cluster/health', or an operation id" }, + // Operation ids never contain '/', endpoints always do. + fromArg: (arg) => (arg.includes('/') ? { endpoint: arg } : { operation_id: arg }), + request: async ({ endpoint, operation_id: operationId, api: key, api_version: ver, include_body: includeBody }, call) => { + if (operationId != null) { + return call(`${operationsOf(key)}/${encodePathParam(String(operationId))}`, { version: ver, include_body: includeBody }) + } + // Inside one API, a route made only of parameters, such as /{index}, can still serve several operations: + // the full view returns them with their fields, best route first. + const { results } = await call(operationsOf(key), { + endpoint, version: ver, view: 'full', include_body: includeBody, + }) as { results: Array<{ operation: Operation; versions: string[]; fields: Field[]; body?: string | null }> } + const [best, ...rest] = results + if (best == null) throw new Error(`No API operation matches ${String(endpoint)} in ${String(key)}.`) + return { operation: best.operation, versions: best.versions, fields: best.fields, body: best.body ?? null, otherMatches: rest.map((r) => r.operation) } + }, + format: (reply) => { + const op = reply['operation'] as Operation & { description?: string } + let out = `# ${op.title}\n` + opLine(op) + if (op.description != null && op.description !== '') out += `\n${op.description}\n` + const fields = reply['fields'] as Field[] + if (fields.length > 0) out += '\nFields:\n' + fields.map(fieldLine).join('') + if (typeof reply['body'] === 'string') out += `\n${reply['body']}\n` + const others = reply['otherMatches'] as Operation[] | undefined + if (others != null && others.length > 0) out += '\nOther matches:\n' + others.map(opLine).join('') + return out + }, + }, deps) +} + +/** `elastic docs api list`: list the REST APIs, the groups of one API, or the operations of one group. */ +export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueCommandHandle { + return apiCommand({ + name: 'list', + description: 'List the Elastic REST APIs, the groups of one API, or the operations of one group', + properties: { + api: { ...pathSegment, description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, + api_version: apiVersion, + group: { ...nonBlank, description: "List the operations of this group, e.g. 'cluster'. Without it, the API's groups are counted." }, + page: { type: 'integer', minimum: 1, description: 'Page of a group listing' }, + size: { type: 'integer', minimum: 1, maximum: 50, description: 'Operations per page of a group listing (default 10)' }, + }, + rules: { dependencies: { api_version: ['api'], group: ['api'], page: ['group'], size: ['group'] } }, + positionalArg: { name: 'api', description: 'API key; omit to list every API' }, + fromArg: (key) => ({ api: key }), + request: async ({ api: key, group, api_version: ver, page, size }, call) => { + if (key == null) return call('/apis', {}) + if (group == null) return call(`/apis/${encodePathParam(String(key))}/groups`, { version: ver }) + return call(operationsOf(key), { version: ver, group, page, size }) + }, + format: (reply) => { + if (Array.isArray(reply['apis'])) { + const apis = reply['apis'] as Array<{ key: string; title: string; versions: string[] }> + const width = Math.max(0, ...apis.map((a) => a.key.length)) + 2 + return apis.map((a) => `${a.key.padEnd(width)}${a.title} [${a.versions.join(', ')}]\n`).join('') + } + if (Array.isArray(reply['results'])) { + const results = reply['results'] as Array<{ operation: Operation }> + return results.map((r) => opLine(r.operation)).join('') + `${results.length} of ${String(reply['totalHits'])} operations\n` + } + return (reply['groups'] as Array<{ name: string; count: number }>).map((g) => `${g.name} (${g.count})\n`).join('') + }, + }, deps) +} + +/** The `elastic docs api` group: the docs API's API Explorer lookups, which the docs MCP server also exposes. */ +export function createApiGroup (deps: ApiDeps = defaultDeps): OpaqueCommandHandle { + return defineGroup( + { name: 'api', description: 'Search, read, and list operations in the Elastic REST API reference' }, + createApiSearchCommand(deps), + createApiGetCommand(deps), + createApiListCommand(deps), + ) +} diff --git a/src/docs/client.ts b/src/docs/client.ts index 7951c86d..b7d9927e 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -3,6 +3,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +import { STATUS_CODES } from 'node:http' + const DOCS_BASE_URL = 'https://www.elastic.co/docs' export interface DocsProduct { id: string @@ -194,3 +196,41 @@ export function stripHtmlTags (s: string): string { export function newUuid (): string { return crypto.randomUUID() } + +/** + * GET a path of the docs API under `/_api/v1`, such as `/apis` or `/apis/{api}/operations`. + * `path` is appended as is, so callers encode any id in it; null and undefined params are dropped. + * Throws with the RFC 9457 problem's `detail` (or `title`) on a non-2xx reply. + */ +export async function docsApi (path: string, params: Record): Promise { + const qs = new URLSearchParams() + for (const [key, value] of Object.entries(params)) { + if (value != null) qs.set(key, String(value)) + } + const url = new URL(`${DOCS_BASE_URL}/_api/v1${path}`) + url.search = qs.toString() + const resp = await fetch(url.href, { + redirect: 'error', + headers: { Accept: 'application/json, application/problem+json' }, + }) + const text = await resp.text().catch(() => '') + if (!resp.ok) { + // The docs API answers RFC 9457 problems (application/problem+json): `detail` explains this occurrence, + // `title` names its type. A CDN or site error page is HTML and carries neither, and HTTP/2 has no status text. + let message = resp.statusText || STATUS_CODES[resp.status] || 'request failed' + try { + const problem = JSON.parse(text) as { detail?: unknown; title?: unknown } + if (typeof problem.detail === 'string' && problem.detail !== '') message = problem.detail + else if (typeof problem.title === 'string' && problem.title !== '') message = problem.title + } catch { + // keep the status text + } + throw new Error(`docs api error (${resp.status}): ${message}`) + } + try { + return JSON.parse(text) as unknown + } catch { + // A CDN or maintenance page can answer 200 with HTML. + throw new Error(`docs api error (${resp.status}): the reply is not JSON`) + } +} diff --git a/src/docs/register.ts b/src/docs/register.ts index ab1a50d8..21a83944 100644 --- a/src/docs/register.ts +++ b/src/docs/register.ts @@ -8,6 +8,7 @@ import type { OpaqueCommandHandle } from '../factory.ts' import { createSearchCommand } from './search.ts' import { createAskCommand } from './ask.ts' import { createReadCommand } from './read.ts' +import { createApiGroup } from './api.ts' export function registerDocsCommands (): OpaqueCommandHandle { return defineGroup( @@ -15,5 +16,6 @@ export function registerDocsCommands (): OpaqueCommandHandle { createSearchCommand(), createAskCommand(), createReadCommand(), + createApiGroup(), ) } diff --git a/src/factory-core.ts b/src/factory-core.ts index 40975929..08e6ece7 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -78,11 +78,23 @@ export interface CommandConfig { name: string description: string options?: OptionDefinition[] - /** - * Optional positional argument. With `inputKey`, its value fills that input schema - * field before validation, as an alternative to the field's flag. - */ - positionalArg?: { name: string; description: string; required?: boolean; inputKey?: string } + /** Optional positional argument; `inputKey` and `toInput` are two ways to turn its value into input. */ + positionalArg?: { + name: string + description: string + required?: boolean + /** + * Fills this input schema field with the positional value before validation, as an alternative to the + * field's flag. Giving both is an error. + */ + inputKey?: string + /** + * Maps the positional value onto schema input fields before validation, for a value that can fill + * different fields, so the schema can require them and `--dry-run` rejects what a real run would. + * Like `inputKey`, the fields win over JSON input, and also giving one of them as a flag is an error. + */ + toInput?: (value: string) => Record + } handler: (parsed: ParsedResult) => HandlerResult | Promise /** JSON Schema object for structured input (properties carry `x-found-in` routing). */ input?: Record diff --git a/src/factory.ts b/src/factory.ts index 834f04fe..9e494100 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -10,6 +10,7 @@ import { createInterface } from 'node:readline' import assert from 'node:assert/strict' import { getResolvedConfig } from './config/store.ts' import { extractSchemaArgs, validateSchemaArgs } from './lib/json-schema-args.ts' +import { isPlainObject } from './lib/type-guards.ts' import type { SchemaArgDefinition } from './lib/json-schema-args.ts' import { pickFields, parseFieldList, applyTemplate, TemplateAgainstPrimitiveError } from './lib/output-transform.ts' import { validateName, hasGlobalJsonFlag, configureErrorOutput, commandPath, isCommandAllowed, stripTransportMeta } from './factory-core.ts' @@ -452,6 +453,8 @@ interface MergedInput { input: unknown rawBodyValues: Record sortParsedKeys: Set + /** The command's positional fills input fields, so a JSON root that is not an object is rejected, null included. */ + strictRoot: boolean } /** Merges schema-derived CLI flag values over the JSON input; flags win. */ @@ -542,17 +545,27 @@ function mergeFlagsIntoInput ( } } - const positionalKey = positionalArg?.inputKey + // A positional that fills input fields (inputKey or toInput) stands in for their flags: it wins over JSON input + // like a flag, and giving it with the flag of a field it fills is an error rather than a silent precedence. const positionalInput = cmd.processedArgs[0] as string | undefined - if (positionalKey != null && positionalInput !== undefined) { - if (positionalKey in cliInput) { - const flag = schemaArgs.find((a) => a.schemaKey === positionalKey)?.cliFlag ?? positionalKey + const fromPositional = positionalInput === undefined + ? undefined + : positionalArg?.toInput != null + ? positionalArg.toInput(positionalInput) + : positionalArg?.inputKey != null ? { [positionalArg.inputKey]: positionalInput } : undefined + for (const key of Object.keys(fromPositional ?? {})) { + if (key in cliInput) { + const flag = schemaArgs.find((a) => a.schemaKey === key)?.cliFlag ?? key return cmd.error(`pass ${positionalArg!.name} either as an argument or as --${flag}, not both`) } - cliInput[positionalKey] = positionalInput } + Object.assign(cliInput, fromPositional) - if (Object.keys(cliInput).length > 0) { + // For those commands, a root that is not an object (null, 42, [], ...) stays as given so validation rejects it; + // merging would turn it into an object that passes and sends a request. Other commands keep merging into any + // root, as they always have. + const strictRoot = positionalArg?.toInput != null || positionalArg?.inputKey != null + if (Object.keys(cliInput).length > 0 && (!strictRoot || inputValue === undefined || isPlainObject(inputValue))) { inputValue = { ...(inputValue as Record ?? {}), ...cliInput } } @@ -560,7 +573,7 @@ function mergeFlagsIntoInput ( // so that missing required fields are caught by AJV if (inputValue === undefined) inputValue = {} - return { input: inputValue, rawBodyValues, sortParsedKeys } + return { input: inputValue, rawBodyValues, sortParsedKeys, strictRoot } } /** Fails the invocation when the config's command policy blocks this command. */ @@ -610,7 +623,11 @@ async function validateAgainstSchema ( validationSchema = { ...schema, properties: props } } - const result = validateWithJsonSchema(validationSchema, merged.input) + // validateWithJsonSchema reads null as "no input" (an empty config file parses to null), so a JSON null + // would pass a schema whose fields are all optional and silently drop the positional. + const result: ReturnType = merged.strictRoot && merged.input === null + ? { success: false, errors: [{ code: 'type', path: '(root)', path_array: [], message: 'must be object' }] } + : validateWithJsonSchema(validationSchema, merged.input) if (!result.success) { if (jsonFormat === true) { diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts new file mode 100644 index 00000000..e03e3c79 --- /dev/null +++ b/test/docs/api.test.ts @@ -0,0 +1,374 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, afterEach } from 'node:test' +import assert from 'node:assert/strict' +import { docsApi } from '../../src/docs/client.ts' +import { createApiGroup, createApiGetCommand, createApiListCommand, createApiSearchCommand } from '../../src/docs/api.ts' +import type { ApiDeps } from '../../src/docs/api.ts' +import { _testSetStdinReader } from '../../src/factory.ts' +import type { OpaqueCommandHandle } from '../../src/factory.ts' +import { captureDuring } from '../helpers/capture.ts' + +const realFetch = globalThis.fetch + +describe('docsApi', () => { + afterEach(() => { globalThis.fetch = realFetch }) + + function install (body: string, status = 200): Array<{ url: string; init: RequestInit }> { + const calls: Array<{ url: string; init: RequestInit }> = [] + globalThis.fetch = (async (url: string, init: RequestInit) => { + calls.push({ url, init }) + return new Response(body, { status }) + }) as typeof fetch + return calls + } + + it('adds no query string when there are no params', async () => { + const calls = install(JSON.stringify({ apis: [] })) + await docsApi('/apis', { version: undefined }) + assert.equal(calls[0]!.url, 'https://www.elastic.co/docs/_api/v1/apis') + }) + + it('GETs the path with encoded params, dropping null and undefined', async () => { + const calls = install(JSON.stringify({ totalHits: 1, results: [] })) + const reply = await docsApi('/apis/elasticsearch/operations', { q: 'GET /{index}/_search?x=1#y', version: undefined, include_deprecated: true, size: null }) + assert.deepEqual(reply, { totalHits: 1, results: [] }) + assert.equal(calls[0]!.url, 'https://www.elastic.co/docs/_api/v1/apis/elasticsearch/operations?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&include_deprecated=true') + assert.equal(calls[0]!.init.method, undefined) + assert.equal(calls[0]!.init.redirect, 'error') + assert.deepEqual(calls[0]!.init.headers, { Accept: 'application/json, application/problem+json' }) + }) + + const problem = { + type: 'https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#operation-not-found', + title: 'API operation not found', + status: 404, + detail: 'No API operation matches nope in elasticsearch.', + traceId: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01', + } + + it('throws the detail of an RFC 9457 problem', async () => { + install(JSON.stringify(problem), 404) + await assert.rejects(docsApi('/apis/elasticsearch/operations/nope', {}), /^Error: docs api error \(404\): No API operation matches nope in elasticsearch\.$/) + }) + + it('falls back to the title of a problem without a detail', async () => { + install(JSON.stringify({ ...problem, detail: undefined }), 404) + await assert.rejects(docsApi('/apis/elasticsearch/operations/nope', {}), /^Error: docs api error \(404\): API operation not found$/) + }) + + it('keeps the status text for JSON that is not a problem', async () => { + install(JSON.stringify({ errorType: 'operation_not_found', message: 'old shape' }), 404) + await assert.rejects(docsApi('/apis', {}), /^Error: docs api error \(404\): Not Found$/) + }) + + it('names a 2xx reply that is not JSON instead of throwing a SyntaxError', async () => { + install('maintenance', 200) + await assert.rejects(docsApi('/apis', {}), /^Error: docs api error \(200\): the reply is not JSON$/) + }) + + it('drops an HTML error page and keeps the status', async () => { + install('forbidden', 403) + await assert.rejects(docsApi('/apis', {}), /^Error: docs api error \(403\): Forbidden$/) + }) +}) + +async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promise<{ stdout: string; stderr: string; exitCode: number }> { + const restoreStdin = _testSetStdinReader(() => stdin) + cmd.exitOverride() + // Error output, such as the --json error object, goes through Commander's writeErr. + const errors: string[] = [] + cmd.configureOutput({ writeOut: () => {}, writeErr: (s) => { errors.push(s) } }) + let thrown = false + const captured = await captureDuring(async () => { + try { + await cmd.parseAsync(argv, { from: 'user' }) + } catch { + // exitOverride turns validation failures into a thrown CommanderError + thrown = true + } + }).finally(restoreStdin) + const exitCode = thrown ? 1 : Number(process.exitCode ?? 0) + process.exitCode = 0 + return { stdout: captured.stdout.join(''), stderr: captured.stderr.join('') + errors.join(''), exitCode } +} + +/** Answers each call with the next reply; the last one repeats. */ +function fake (...replies: unknown[]): { deps: ApiDeps; calls: Array<{ path: string; params: Record }> } { + const calls: Array<{ path: string; params: Record }> = [] + return { calls, deps: { docsApi: async (path, params) => { calls.push({ path, params }); return replies[Math.min(calls.length, replies.length) - 1] } } } +} + +const op = { api: 'elasticsearch', title: 'Get cluster health', url: '/docs/api/doc/elasticsearch/operation/operation-cluster-health', method: 'GET', path: '/_cluster/health', operationId: 'cluster-health', endpoints: [] } + +describe('docs api commands', () => { + it('groups search, get and list under api', () => { + assert.deepEqual(createApiGroup().commands.map((c) => c.name()), ['search', 'get', 'list']) + }) + + it('search sends the positional query as q with its flags to the API\'s operations', async () => { + const { deps, calls } = fake({ query: 'health', totalHits: 1, results: [{ operation: op, score: 1, matchedFields: [] }] }) + const { stdout, exitCode } = await run(createApiSearchCommand(deps), ['GET /_cluster/health', '--api', 'elasticsearch', '--include-deprecated', '--size', '5']) + assert.equal(exitCode, 0) + assert.deepEqual(calls, [{ path: '/apis/elasticsearch/operations', params: { q: 'GET /_cluster/health', version: undefined, include_deprecated: true, size: 5, page: 1 } }]) + assert.match(stdout, /GET {4}\/_cluster\/health {2}\(cluster-health\)/) + assert.match(stdout, /https:\/\/www\.elastic\.co\/docs\/api\/doc\/elasticsearch\/operation\/operation-cluster-health/) + }) + + it('search rejects an out-of-range page size before calling the server', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiSearchCommand(deps), ['x', '--api', 'elasticsearch', '--size', '0']) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + + it('search rejects an unknown key in JSON input', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiSearchCommand(deps), [], '{"query":"x","api":"elasticsearch","bogus":1}') + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + + it('get with an endpoint reads every match in the API with its fields in one request', async () => { + const other = { ...op, operationId: 'indices-get', path: '/{index}' } + const level = { name: 'level', path: 'level', type: 'string', location: 'query', description: 'Detail level' } + const { deps, calls } = fake({ totalHits: 2, results: [{ operation: op, versions: ['9'], fields: [level], body: 'Body' }, { operation: other, versions: [], fields: [] }] }) + const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--api', 'elasticsearch', '--include-body']) + assert.equal(exitCode, 0) + assert.deepEqual(calls, [{ path: '/apis/elasticsearch/operations', params: { endpoint: 'GET /_cluster/health', version: undefined, view: 'full', include_body: true } }]) + assert.match(stdout, /# Get cluster health/) + assert.match(stdout, /query {4}level Detail level/) + assert.match(stdout, /\nBody\n/) + assert.match(stdout, /Other matches:\nGET {4}\/\{index\} {2}\(indices-get\)/) + }) + + it('get --json returns one operation shape for an endpoint lookup', async () => { + const { deps } = fake({ totalHits: 1, results: [{ operation: op, versions: ['9'], fields: [] }] }) + const cmd = createApiGetCommand(deps) + cmd.option('--json') + const { stdout } = await run(cmd, ['GET /_cluster/health', '--api', 'elasticsearch', '--json']) + assert.deepEqual(JSON.parse(stdout), { operation: op, versions: ['9'], fields: [], body: null, otherMatches: [] }) + }) + + it('get with an endpoint that nothing serves fails', async () => { + const { deps, calls } = fake({ totalHits: 0, results: [] }) + const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /nope', '--api', 'elasticsearch']) + assert.equal(exitCode, 1) + assert.equal(stdout, '') + assert.equal(calls.length, 1) + }) + + it('get with an operation id and an api reads the operation by its id', async () => { + const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) + const { exitCode } = await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch', '--api-version', '9']) + assert.equal(exitCode, 0) + assert.deepEqual(calls, [{ path: '/apis/elasticsearch/operations/cluster-health', params: { version: '9', include_body: undefined } }]) + }) + + it('get encodes the api key and the operation id into one path segment each', async () => { + const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) + await run(createApiGetCommand(deps), ['--operation-id', '../x?y=1#z', '--api', 'a/b']) + assert.equal(calls[0]!.path, '/apis/a%2Fb/operations/..%2Fx%3Fy%3D1%23z') + }) + + it('get rejects both an operation id and an endpoint without calling the server', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiGetCommand(deps), ['--operation-id', 'a', '--endpoint', 'GET /b', '--api', 'elasticsearch']) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + + it('get reports a server error with exit code 1', async () => { + const cmd = createApiGetCommand({ docsApi: async () => { throw new Error('No API operation matches nope.') } }) + const { stdout, exitCode } = await run(cmd, ['nope', '--api', 'elasticsearch']) + assert.equal(exitCode, 1) + assert.equal(stdout, '') + }) + + it('search without a query fails without calling the server', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiSearchCommand(deps), []) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + + it('search reports no results', async () => { + const { deps } = fake({ query: 'x', totalHits: 0, results: [] }) + assert.equal((await run(createApiSearchCommand(deps), ['x', '--api', 'elasticsearch'])).stdout, 'No operations found.\n') + }) + + it('get prints the description, body, deprecation and other matches', async () => { + const { deps } = fake({ + operation: { ...op, description: 'Checks health.', deprecated: true }, + versions: [], + fields: [{ name: 'index', path: 'index', type: 'string', location: 'path', description: '' }], + body: 'Full body.', + otherMatches: [{ ...op, api: 'kibana', path: '/api/health' }], + }) + const { stdout } = await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch']) + assert.match(stdout, /\[deprecated\]/) + assert.match(stdout, /Checks health\./) + assert.match(stdout, /path {5}index \n/) + assert.match(stdout, /Full body\./) + assert.match(stdout, /Other matches:\nGET {4}\/api\/health/) + }) + + it('falls back to JSON when --output-fields strips what the formatter reads', async () => { + const { deps } = fake({ query: 'x', totalHits: 3, results: [] }) + const cmd = createApiSearchCommand(deps) + cmd.option('--output-fields ') + const { stdout } = await run(cmd, ['x', '--api', 'elasticsearch', '--output-fields', 'totalHits']) + assert.deepEqual(JSON.parse(stdout), { totalHits: 3 }) + }) + + it('list without a key lists the APIs', async () => { + const { deps, calls } = fake({ apis: [{ key: 'elasticsearch', title: 'Elasticsearch API', url: '/x', versions: ['main', '9'] }] }) + const { stdout } = await run(createApiListCommand(deps), []) + assert.deepEqual(calls[0], { path: '/apis', params: {} }) + assert.match(stdout, /elasticsearch\s+Elasticsearch API {2}\[main, 9\]/) + }) + + it('list keeps a space between an API key longer than the column and its title', async () => { + const { deps } = fake({ apis: [ + { key: 'es', title: 'Short', url: '/x', versions: ['main'] }, + { key: 'elasticsearch-serverless', title: 'Elasticsearch Serverless API', url: '/x', versions: ['main'] }, + ] }) + const { stdout } = await run(createApiListCommand(deps), []) + assert.equal(stdout, 'es Short [main]\nelasticsearch-serverless Elasticsearch Serverless API [main]\n') + }) + + it('list with a key counts the API\'s groups', async () => { + const { deps, calls } = fake({ api: 'kibana', totalOperations: 41, groups: [{ name: 'cluster', count: 1 }, { name: 'ml', count: 40 }] }) + const { stdout } = await run(createApiListCommand(deps), ['kibana']) + assert.deepEqual(calls[0], { path: '/apis/kibana/groups', params: { version: undefined } }) + assert.equal(stdout, 'cluster (1)\nml (40)\n') + }) + + it('list with a group lists its operations a page at a time', async () => { + const { deps, calls } = fake({ totalHits: 12, results: [{ operation: op }] }) + const { stdout } = await run(createApiListCommand(deps), ['elasticsearch', '--group', 'cluster', '--page', '2']) + assert.deepEqual(calls[0], { path: '/apis/elasticsearch/operations', params: { version: undefined, group: 'cluster', page: 2, size: undefined } }) + assert.match(stdout, /^GET {4}\/_cluster\/health {2}\(cluster-health\)\n.*\n1 of 12 operations\n$/) + }) + + it('list encodes the api key into one path segment', async () => { + const { deps, calls } = fake({ api: 'x', totalOperations: 0, groups: [] }) + await run(createApiListCommand(deps), ['../x']) + assert.equal(calls[0]!.path, '/apis/..%2Fx/groups') + }) + + it('search and list send --api-version as the version query parameter', async () => { + const search = fake({ totalHits: 0, results: [] }) + await run(createApiSearchCommand(search.deps), ['health', '--api', 'elasticsearch', '--api-version', '9']) + assert.equal(search.calls[0]!.params['version'], '9') + assert.equal('api_version' in search.calls[0]!.params, false) + const list = fake({ groups: [] }) + await run(createApiListCommand(list.deps), ['elasticsearch', '--api-version', '8']) + assert.deepEqual(list.calls[0], { path: '/apis/elasticsearch/groups', params: { version: '8' } }) + }) + + it('list rejects --api-version without an api key', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiListCommand(deps), ['--api-version', '9']) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + + // The schema enforces these before any handler runs, so --dry-run rejects what a real run would. + for (const dryRun of [[], ['--dry-run']]) { + const mode = dryRun.length > 0 ? ' under --dry-run' : '' + for (const [name, create, argv] of [ + ['search without a query', createApiSearchCommand, []], + ['search with a blank query', createApiSearchCommand, [' ']], + ['search without --api', createApiSearchCommand, ['x']], + ['search with a blank --api', createApiSearchCommand, ['x', '--api', ' ']], + ['get without an operation', createApiGetCommand, []], + ['get with a blank operation', createApiGetCommand, [' ']], + ['get with both an endpoint and an operation id', createApiGetCommand, ['GET /_cluster/health', '--operation-id', 'cluster-health', '--api', 'elasticsearch']], + ['get without --api', createApiGetCommand, ['cluster-health']], + ['list with --group but no api', createApiListCommand, ['--group', 'cluster']], + ['list with --page but no --group', createApiListCommand, ['elasticsearch', '--page', '2']], + ['list with a blank api', createApiListCommand, [' ']], + ['list with a blank --api', createApiListCommand, ['--api', '']], + ['list with a blank --group', createApiListCommand, ['elasticsearch', '--group', '']], + ['list with a whitespace --group', createApiListCommand, ['elasticsearch', '--group', ' ']], + ['list with a blank --api-version', createApiListCommand, ['elasticsearch', '--api-version', '']], + ['search with a blank --api-version', createApiSearchCommand, ['x', '--api', 'elasticsearch', '--api-version', ' ']], + ['get with a blank --api-version', createApiGetCommand, ['cluster-health', '--api', 'elasticsearch', '--api-version', '']], + ['get with --version, the CLI\'s own flag', createApiGetCommand, ['cluster-health', '--api', 'elasticsearch', '--version', '9']], + // `.` and `..` survive encodeURIComponent and URL parsing resolves them, leaving the intended route. + ['search with the query as an argument and as --query', createApiSearchCommand, ['foo', '--query', 'bar', '--api', 'elasticsearch']], + ['get with the operation as an argument and as --operation-id', createApiGetCommand, ['cluster-health', '--operation-id', 'nodes-info', '--api', 'elasticsearch']], + ['get with the operation as an argument and as --endpoint', createApiGetCommand, ['GET /_cluster/health', '--endpoint', 'GET /_nodes', '--api', 'elasticsearch']], + ['list with the api as an argument and as --api', createApiListCommand, ['elasticsearch', '--api', 'kibana']], + ['list with the api ..', createApiListCommand, ['..']], + ['list with the api .', createApiListCommand, ['.']], + ['list with --api ..', createApiListCommand, ['--api', '..']], + ['search with --api ..', createApiSearchCommand, ['x', '--api', '..']], + ['get with the operation id ..', createApiGetCommand, ['..', '--api', 'elasticsearch']], + ['get with --operation-id .', createApiGetCommand, ['--operation-id', '.', '--api', 'elasticsearch']], + ['get with --api ..', createApiGetCommand, ['cluster-health', '--api', '..']], + ] as const) { + it(`rejects ${name}${mode} without calling the server`, async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(create(deps), [...argv, ...dryRun]) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + } + } + + // A flag must not turn a JSON root that is not an object into a valid input. + for (const root of ['null', '42', 'true', '[]', '"x"']) { + for (const dryRun of [[], ['--dry-run']]) { + it(`rejects the JSON root ${root} given with --api${dryRun.length > 0 ? ' under --dry-run' : ''}`, async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch', ...dryRun], root) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + } + } + + it('still merges --api into a JSON object', async () => { + const { deps, calls } = fake({ operation: {}, versions: [], fields: [] }) + const { exitCode } = await run(createApiGetCommand(deps), ['--api', 'elasticsearch'], '{"operation_id":"cluster-health"}') + assert.equal(exitCode, 0) + assert.equal(calls[0]?.path, '/apis/elasticsearch/operations/cluster-health') + }) + + // --no-validate skips the schema; the path encoding still refuses a dot segment before any request. + for (const [name, create, argv] of [ + ['list', createApiListCommand, ['..']], + ['get', createApiGetCommand, ['..', '--api', 'elasticsearch']], + ] as const) { + it(`${name} with a dot segment and --no-validate fails with input_error without calling the server`, async () => { + const { deps, calls } = fake({}) + const cmd = create(deps) + cmd.option('--json') + const { stderr, exitCode } = await run(cmd, [...argv, '--no-validate', '--json']) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + assert.equal(JSON.parse(stderr).error.code, 'input_error') + }) + } + + it('accepts a valid query under --dry-run without calling the server', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--api', 'elasticsearch', '--dry-run']) + assert.equal(exitCode, 0) + assert.equal(calls.length, 0) + }) + + it('--json passes the server reply through unchanged', async () => { + const reply = { apis: [] } + const { deps } = fake(reply) + const cmd = createApiListCommand(deps) + cmd.option('--json') + const { stdout } = await run(cmd, ['--json']) + assert.deepEqual(JSON.parse(stdout), reply) + }) +}) diff --git a/test/factory.test.ts b/test/factory.test.ts index 65b1cb77..b42cbf24 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -248,6 +248,155 @@ describe('defineCommand', () => { assert.equal(received[0].arg, 'ingest pipelines') }) + describe('toInput', () => { + function searchCommand (received: ParsedResult[]): OpaqueCommandHandle { + const cmd = defineCommand({ + name: 'search', + description: 'Search docs', + input: { type: 'object', properties: { query: { type: 'string' }, topic: { type: 'string' } }, required: ['query'], additionalProperties: false }, + positionalArg: { name: 'query', description: 'Search query', required: false, toInput: (query) => ({ query }) }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + cmd.exitOverride() + cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} }) + return cmd + } + + async function run (argv: string[], stdin = ''): Promise<{ received: ParsedResult[]; failed: boolean }> { + const received: ParsedResult[] = [] + const restore = _testSetStdinReader(() => stdin) + let failed = false + try { + await searchCommand(received).parseAsync(argv, { from: 'user' }) + } catch { + failed = true + } finally { + restore() + process.exitCode = 0 + } + return { received, failed } + } + + it('maps the positional value into the input before validation', async () => { + const { received, failed } = await run(['ingest pipelines']) + assert.equal(failed, false) + assert.deepEqual(received[0]?.input, { query: 'ingest pipelines' }) + }) + + // Like inputKey: a silent precedence between the two is easy to miss. + it('errors when the positional and a flag fill the same field, also under --dry-run', async () => { + for (const extra of [[], ['--dry-run']]) { + const { received, failed } = await run(['positional', '--query', 'flag', ...extra]) + assert.equal(failed, true, extra.join(' ')) + assert.equal(received.length, 0) + } + }) + + it('merges the positional with flags for other fields', async () => { + const { received } = await run(['positional', '--topic', 'flag']) + assert.deepEqual(received[0]?.input, { query: 'positional', topic: 'flag' }) + }) + + it('lets the positional win over JSON input, like a flag', async () => { + const { received } = await run(['positional'], '{"query":"json","topic":"json"}') + assert.deepEqual(received[0]?.input, { query: 'positional', topic: 'json' }) + }) + + // Only an object can take the positional's fields; any other root is left for the schema to reject. + for (const root of ['null', '42', 'true', '[]', '["x"]', '"text"']) { + it(`rejects the JSON root ${root} instead of turning it into an object, also under --dry-run`, async () => { + // Flags must not rescue it either: they would otherwise merge into a fresh object. + for (const extra of [[], ['--dry-run'], ['--topic', 'flag'], ['--topic', 'flag', '--dry-run']]) { + const { received, failed } = await run(['positional', ...extra], root) + assert.equal(failed, true, `${root} ${extra.join(' ')}`) + assert.equal(received.length, 0) + } + }) + } + + // The schema has no required field, so a null root that reads as "no input" would pass and drop the positional. + it('rejects a null JSON root even when every input field is optional', async () => { + for (const extra of [[], ['--dry-run']]) { + const received: ParsedResult[] = [] + const restore = _testSetStdinReader(() => 'null') + let failed = false + try { + const cmd = defineCommand({ + name: 'list', + description: 'List', + input: { type: 'object', properties: { api: { type: 'string' } }, additionalProperties: false }, + positionalArg: { name: 'api', description: 'API', required: false, toInput: (api) => ({ api }) }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + cmd.exitOverride() + cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} }) + await cmd.parseAsync(['elasticsearch', ...extra], { from: 'user' }) + } catch { + failed = true + } finally { + restore() + process.exitCode = 0 + } + assert.equal(failed, true, extra.join(' ')) + assert.equal(received.length, 0) + } + }) + + it('still merges flags into a JSON object', async () => { + const { received, failed } = await run(['--query', 'flag'], '{"query":1}') + assert.equal(failed, false) + assert.deepEqual(received[0]?.input, { query: 'flag' }) + }) + + it('fails validation without the value, also under --dry-run, before the handler runs', async () => { + for (const argv of [[], ['--dry-run']]) { + const { received, failed } = await run(argv) + assert.equal(failed, true, argv.join(' ')) + assert.equal(received.length, 0) + } + }) + }) + + // Only commands whose positional fills input fields are strict about the JSON root (#825 review). + describe('without a positional that fills input', () => { + async function runPlain (argv: string[], stdin: string): Promise<{ received: ParsedResult[]; failed: boolean }> { + const received: ParsedResult[] = [] + const restore = _testSetStdinReader(() => stdin) + let failed = false + try { + const cmd = defineCommand({ + name: 'create', + description: 'Create', + input: { type: 'object', properties: { name: { type: 'string' } }, additionalProperties: false }, + handler: (parsed) => { received.push(parsed); return {} }, + }) + cmd.exitOverride() + cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} }) + await cmd.parseAsync(argv, { from: 'user' }) + } catch { + failed = true + } finally { + restore() + process.exitCode = 0 + } + return { received, failed } + } + + it('still reads a null JSON root as no input', async () => { + const { received, failed } = await runPlain([], 'null') + assert.equal(failed, false) + assert.deepEqual(received[0]?.input, {}) + }) + + for (const root of ['null', '42', 'true', '[]']) { + it(`still merges flags into the JSON root ${root}`, async () => { + const { received, failed } = await runPlain(['--name', 'x'], root) + assert.equal(failed, false) + assert.deepEqual(received[0]?.input, { name: 'x' }) + }) + } + }) + describe('with inputKey', () => { // Commands with an input schema read stdin when it is not a TTY; on Windows CI that read never ends. let origIsTTY: boolean | undefined