From 8f7a24052a79595ea16608adda35d5a806c86752 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 12:29:05 +0100 Subject: [PATCH 01/17] feat(docs): add elastic docs api commands Add `elastic docs api search`, `get` and `list` to look up operations in the Elastic REST API reference. They call the docs API's /_api/v1/api-reference endpoints, which serve the same lookups as the docs MCP server's API tools. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 183 +++++++++++++++++++++++++++++++++++++++++- src/docs/api.ts | 169 ++++++++++++++++++++++++++++++++++++++ src/docs/client.ts | 29 +++++++ src/docs/register.ts | 2 + test/docs/api.test.ts | 181 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 563 insertions(+), 1 deletion(-) create mode 100644 src/docs/api.ts create mode 100644 test/docs/api.test.ts diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 817b2fd8..4a111252 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -121163,7 +121163,188 @@ } } ], - "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": false, + "summary": "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" + }, + { + "role": "flag", + "name": "api", + "type": "string", + "required": false, + "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." + }, + { + "role": "flag", + "name": "version", + "type": "string", + "required": false, + "summary": "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." + }, + { + "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'" + }, + { + "role": "flag", + "name": "operation-id", + "type": "string", + "required": false, + "summary": "The OpenAPI operation id, e.g. 'cluster-health'" + }, + { + "role": "flag", + "name": "api", + "type": "string", + "required": false, + "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." + }, + { + "role": "flag", + "name": "version", + "type": "string", + "required": false, + "summary": "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." + }, + { + "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." + }, + { + "role": "flag", + "name": "version", + "type": "string", + "required": false, + "summary": "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." + }, + { + "role": "flag", + "name": "group", + "type": "string", + "required": false, + "summary": "Only the operations of this group, e.g. 'cluster'" + } + ], + "summary": "List the Elastic REST APIs, or the operations of one API by 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..a76e87db --- /dev/null +++ b/src/docs/api.ts @@ -0,0 +1,169 @@ +/* + * 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 { docsApiReference } from './client.ts' + +/** Injectable dependencies for the `docs api` commands. */ +export interface ApiDeps { + docsApiReference: typeof docsApiReference +} + +const defaultDeps: ApiDeps = { docsApiReference } + +// Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. +const api = { type: 'string', description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } +const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." } + +interface Operation { title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } +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 + /** Path under `/_api/v1/api-reference`. */ + path: string + properties: Record + positionalArg: { name: string; description: string } + /** Maps the positional value onto query parameters. */ + fromArg: (arg: string) => Record + 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 }, + positionalArg: { ...config.positionalArg, required: false }, + handler: async (parsed): Promise => { + const arg = parsed.arg?.trim() + const merged: Record = { ...(parsed.input ?? {}), ...(arg != null && arg !== '' ? config.fromArg(arg) : {}) } + const { query, ...params } = merged + try { + return await deps.docsApiReference(config.path, query === undefined ? params : { q: query, ...params }) as JsonValue + } catch (err) { + return { error: { code: 'docs_error', 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', + path: '/search', + properties: { + query: { type: 'string', description: "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" }, + api, + version, + 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 }, + }, + positionalArg: { name: 'query', description: 'Words, an endpoint, or a field path' }, + fromArg: (query) => ({ query }), + 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', + path: '/operation', + properties: { + endpoint: { type: 'string', description: "A route as you would call it, e.g. 'GET /my-index/_search'" }, + operation_id: { type: 'string', description: "The OpenAPI operation id, e.g. 'cluster-health'" }, + api, + version, + include_body: { type: 'boolean', description: 'Include the page body' }, + }, + 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 }), + 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, or the operations of one API by group. */ +export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueCommandHandle { + return apiCommand({ + name: 'list', + description: 'List the Elastic REST APIs, or the operations of one API by group', + path: '/', + properties: { + api: { type: 'string', description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, + version, + group: { type: 'string', description: "Only the operations of this group, e.g. 'cluster'" }, + }, + positionalArg: { name: 'api', description: 'API key; omit to list every API' }, + fromArg: (key) => ({ api: key }), + format: (reply) => { + if (Array.isArray(reply['apis'])) { + return (reply['apis'] as Array<{ key: string; title: string; versions: string[] }>) + .map((a) => `${a.key.padEnd(24)}${a.title} [${a.versions.join(', ')}]\n`).join('') + } + const groups = reply['groups'] as Array<{ name: string; count: number; operations?: Operation[] }> + let out = '' + for (const g of groups) { + out += `${g.name} (${g.count})\n` + if (g.operations != null) out += g.operations.map((o) => ' ' + opLine(o).replace('\n ', '\n ')).join('') + '\n' + } + if (typeof reply['note'] === 'string') out += `\n${reply['note']}\n` + return out + }, + }, 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 d670d176..40b0017b 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -197,3 +197,32 @@ export function stripHtmlTags (s: string): string { export function newUuid (): string { return crypto.randomUUID() } + +/** + * Query the API Explorer lookups of the docs API (`/_api/v1/api-reference`). + * `path` is `/search`, `/operation`, or `/` (list); null and undefined params are dropped. + * Throws with the server's `message` on a non-2xx reply. + */ +export async function docsApiReference (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 resp = await fetch(`${DOCS_BASE_URL}/_api/v1/api-reference${path}?${qs.toString()}`, { + redirect: 'error', + headers: { Accept: 'application/json', Cookie: DOCS_COOKIE }, + }) + const text = await resp.text().catch(() => '') + if (!resp.ok) { + // A CDN or site error page is HTML; only the docs API's JSON rejection carries a useful message. + let message = resp.statusText || 'request failed' + try { + const body = JSON.parse(text) as { message?: unknown } + if (typeof body.message === 'string') message = body.message + } catch { + // keep the status text + } + throw new Error(`docs api error (${resp.status}): ${message}`) + } + return JSON.parse(text) as unknown +} 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/test/docs/api.test.ts b/test/docs/api.test.ts new file mode 100644 index 00000000..49a1e01a --- /dev/null +++ b/test/docs/api.test.ts @@ -0,0 +1,181 @@ +/* + * 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 { docsApiReference } 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' + +const realFetch = globalThis.fetch + +describe('docsApiReference', () => { + 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('GETs the path with encoded params, dropping null and undefined', async () => { + const calls = install(JSON.stringify({ totalHits: 1, results: [] })) + const reply = await docsApiReference('/search', { q: 'GET /{index}/_search?x=1#y', api: 'elasticsearch', 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/api-reference/search?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&api=elasticsearch&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', Cookie: 'feature_search_or_askai_enabled=true' }) + }) + + it('throws the server message of a rejection', async () => { + install(JSON.stringify({ errorType: 'operation_not_found', message: 'No API operation matches nope.' }), 404) + await assert.rejects(docsApiReference('/operation', { operation_id: 'nope' }), /^Error: docs api error \(404\): No API operation matches nope\.$/) + }) + + it('drops an HTML error page and keeps the status', async () => { + install('forbidden', 403) + await assert.rejects(docsApiReference('/', {}), /^Error: docs api error \(403\): (Forbidden|request failed)$/) + }) +}) + +async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promise<{ stdout: string; exitCode: number }> { + let stdout = '' + const realWrite = process.stdout.write.bind(process.stdout) + process.stdout.write = ((s: string) => { stdout += s; return true }) as typeof process.stdout.write + const restoreStdin = _testSetStdinReader(() => stdin) + cmd.exitOverride() + cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} }) + let thrown = false + try { + await cmd.parseAsync(argv, { from: 'user' }) + } catch { + // exitOverride turns validation failures into a thrown CommanderError + thrown = true + } finally { + process.stdout.write = realWrite + restoreStdin() + } + const exitCode = thrown ? 1 : Number(process.exitCode ?? 0) + process.exitCode = 0 + return { stdout, exitCode } +} + +function fake (reply: unknown): { deps: ApiDeps; calls: Array<{ path: string; params: Record }> } { + const calls: Array<{ path: string; params: Record }> = [] + return { calls, deps: { docsApiReference: async (path, params) => { calls.push({ path, params }); return reply } } } +} + +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 /search', 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: '/search', params: { q: 'GET /_cluster/health', api: 'elasticsearch', 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', '--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","bogus":1}') + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + + it('get treats an argument with a slash as an endpoint', async () => { + const { deps, calls } = fake({ operation: op, versions: ['9'], fields: [{ name: 'level', path: 'level', type: 'string', location: 'query', description: 'Detail level' }], otherMatches: [] }) + const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--api', 'elasticsearch']) + assert.equal(exitCode, 0) + assert.deepEqual(calls[0], { path: '/operation', params: { api: 'elasticsearch', endpoint: 'GET /_cluster/health' } }) + assert.match(stdout, /# Get cluster health/) + assert.match(stdout, /query {4}level Detail level/) + }) + + it('get treats an argument without a slash as an operation id', async () => { + const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) + await run(createApiGetCommand(deps), ['cluster-health']) + assert.deepEqual(calls[0]!.params, { operation_id: 'cluster-health' }) + }) + + it('get reports a tool error with exit code 1', async () => { + const cmd = createApiGetCommand({ docsApiReference: async () => { throw new Error('No API operation matches nope.') } }) + const { stdout, exitCode } = await run(cmd, ['nope']) + assert.equal(exitCode, 1) + assert.equal(stdout, '') + }) + + it('search reports no results', async () => { + const { deps } = fake({ query: 'x', totalHits: 0, results: [] }) + assert.equal((await run(createApiSearchCommand(deps), ['x'])).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']) + 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', '--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: '/', params: {} }) + assert.match(stdout, /elasticsearch\s+Elasticsearch API {2}\[main, 9\]/) + }) + + it('list with a key prints groups, operations and the server note', async () => { + const { deps, calls } = fake({ api: 'kibana', totalOperations: 1, groups: [{ name: 'cluster', count: 1, operations: [op] }, { name: 'ml', count: 40 }], note: 'Pass group.' }) + const { stdout } = await run(createApiListCommand(deps), ['kibana', '--group', 'cluster']) + assert.deepEqual(calls[0]!.params, { group: 'cluster', api: 'kibana' }) + assert.match(stdout, /^cluster \(1\)\n {2}GET/) + assert.match(stdout, /ml \(40\)/) + assert.match(stdout, /Pass group\./) + }) + + 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) + }) +}) From d4ed0a5940624dc04a90e83adba0ee3691136691 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 12:58:24 +0100 Subject: [PATCH 02/17] test(docs): capture docs api output through the shared helper Patching process.stdout.write directly also swallowed the Node 22 test runner's serialized events, so the --json test parsed binary data. captureDuring forwards non-string chunks to the real stream. Co-Authored-By: Claude Opus 5.5 --- test/docs/api.test.ts | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 49a1e01a..b7a3a2d4 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -10,6 +10,7 @@ import { createApiGroup, createApiGetCommand, createApiListCommand, createApiSea 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 @@ -47,25 +48,21 @@ describe('docsApiReference', () => { }) async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promise<{ stdout: string; exitCode: number }> { - let stdout = '' - const realWrite = process.stdout.write.bind(process.stdout) - process.stdout.write = ((s: string) => { stdout += s; return true }) as typeof process.stdout.write const restoreStdin = _testSetStdinReader(() => stdin) cmd.exitOverride() cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} }) let thrown = false - try { - await cmd.parseAsync(argv, { from: 'user' }) - } catch { - // exitOverride turns validation failures into a thrown CommanderError - thrown = true - } finally { - process.stdout.write = realWrite - restoreStdin() - } + 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, exitCode } + return { stdout: captured.stdout.join(''), exitCode } } function fake (reply: unknown): { deps: ApiDeps; calls: Array<{ path: string; params: Record }> } { From 2f3cc0cf54491a6e8be6fe74304791cd852e24db Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 12:59:23 +0100 Subject: [PATCH 03/17] docs(docs): keep the version flag help from reading as a default The command reference turns 'Default:' in a description into a default value. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 6 +++--- src/docs/api.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 4a111252..ce5aa356 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -121200,7 +121200,7 @@ "name": "version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." + "summary": "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." }, { "role": "flag", @@ -121284,7 +121284,7 @@ "name": "version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." + "summary": "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." }, { "role": "flag", @@ -121325,7 +121325,7 @@ "name": "version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." + "summary": "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." }, { "role": "flag", diff --git a/src/docs/api.ts b/src/docs/api.ts index a76e87db..5abd943a 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -16,7 +16,7 @@ const defaultDeps: ApiDeps = { docsApiReference } // Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. const api = { type: 'string', description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } -const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Default: the current version." } +const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." } interface Operation { title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } interface Field { path: string; type: string; location: string; description: string } From 96010a6e46fa1eda49fc9e487a9f5167da7edf22 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 13:50:48 +0100 Subject: [PATCH 04/17] feat(docs): call the docs API's api-operations resource The docs API now serves the lookups as one resource: the collection filters by q or endpoint, one operation reads by id, and groups and apis are their own routes. `get` with an endpoint lists the matching operations, then reads the best one by id in its own API. Co-Authored-By: Claude Opus 5.5 --- src/docs/api.ts | 41 ++++++++++++++------- src/docs/client.ts | 8 ++--- test/docs/api.test.ts | 84 ++++++++++++++++++++++++++++++++----------- 3 files changed, 97 insertions(+), 36 deletions(-) diff --git a/src/docs/api.ts b/src/docs/api.ts index 5abd943a..5cf9aa88 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -5,20 +5,20 @@ import { defineCommand, defineGroup } from '../factory.ts' import type { OpaqueCommandHandle, JsonValue } from '../factory.ts' -import { docsApiReference } from './client.ts' +import { docsApiOperations } from './client.ts' /** Injectable dependencies for the `docs api` commands. */ export interface ApiDeps { - docsApiReference: typeof docsApiReference + docsApiOperations: typeof docsApiOperations } -const defaultDeps: ApiDeps = { docsApiReference } +const defaultDeps: ApiDeps = { docsApiOperations } // Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. const api = { type: 'string', description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." } -interface Operation { title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } +interface Operation { api: string; title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } interface Field { path: string; type: string; location: string; description: string } function absUrl (url: string): string { @@ -36,12 +36,12 @@ function fieldLine (f: Field): string { interface ApiCommandConfig { name: string description: string - /** Path under `/_api/v1/api-reference`. */ - path: string properties: Record positionalArg: { name: string; description: string } /** Maps the positional value onto query parameters. */ fromArg: (arg: string) => Record + /** Sends the request(s); `call` GETs a path under `/_api/v1/api-operations`. */ + request: (params: Record, call: ApiDeps['docsApiOperations']) => Promise format: (reply: Record) => string } @@ -53,10 +53,9 @@ function apiCommand (config: ApiCommandConfig, deps: ApiDeps): OpaqueCommandHand positionalArg: { ...config.positionalArg, required: false }, handler: async (parsed): Promise => { const arg = parsed.arg?.trim() - const merged: Record = { ...(parsed.input ?? {}), ...(arg != null && arg !== '' ? config.fromArg(arg) : {}) } - const { query, ...params } = merged + const params: Record = { ...(parsed.input ?? {}), ...(arg != null && arg !== '' ? config.fromArg(arg) : {}) } try { - return await deps.docsApiReference(config.path, query === undefined ? params : { q: query, ...params }) as JsonValue + return await config.request(params, deps.docsApiOperations) as JsonValue } catch (err) { return { error: { code: 'docs_error', message: err instanceof Error ? err.message : String(err) } } } @@ -73,7 +72,6 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm return apiCommand({ name: 'search', description: 'Search the Elastic REST API reference for operations', - path: '/search', properties: { query: { type: 'string', description: "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" }, api, @@ -84,6 +82,10 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm }, positionalArg: { name: 'query', description: 'Words, an endpoint, or a field path' }, fromArg: (query) => ({ query }), + request: async ({ query, ...params }, call) => { + if (typeof query !== 'string' || query.trim() === '') throw new Error('query is required') + return call('', { q: query, ...params }) + }, format: (reply) => { const results = reply['results'] as Array<{ operation: Operation; matchedFields?: Field[] }> if (results.length === 0) return 'No operations found.\n' @@ -103,7 +105,6 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand return apiCommand({ name: 'get', description: 'Get one operation from the Elastic REST API reference, with its parameters and fields', - path: '/operation', properties: { endpoint: { type: 'string', description: "A route as you would call it, e.g. 'GET /my-index/_search'" }, operation_id: { type: 'string', description: "The OpenAPI operation id, e.g. 'cluster-health'" }, @@ -114,6 +115,18 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand 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, version: ver, include_body: includeBody }, call) => { + if ((endpoint == null) === (operationId == null)) throw new Error('Pass exactly one of an operation id or an endpoint.') + if (operationId != null) { + return call(`/${encodeURIComponent(String(operationId))}`, { api: key, version: ver, include_body: includeBody }) + } + // The collection lists every operation that serves the request; read the best one with its fields. + const { results } = await call('', { endpoint, api: key, version: ver }) as { results: Operation[] } + const [best, ...rest] = results + if (best == null) throw new Error(`No API operation matches ${String(endpoint)}${key != null ? ` in ${String(key)}` : ''}.`) + const detail = await call(`/${encodeURIComponent(best.operationId)}`, { api: best.api, version: ver, include_body: includeBody }) + return { ...(detail as Record), otherMatches: rest } + }, format: (reply) => { const op = reply['operation'] as Operation & { description?: string } let out = `# ${op.title}\n` + opLine(op) @@ -133,7 +146,6 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman return apiCommand({ name: 'list', description: 'List the Elastic REST APIs, or the operations of one API by group', - path: '/', properties: { api: { type: 'string', description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, version, @@ -141,6 +153,11 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman }, positionalArg: { name: 'api', description: 'API key; omit to list every API' }, fromArg: (key) => ({ api: key }), + request: async ({ api: key, ...params }, call) => { + if (key != null) return call('/groups', { api: key, ...params }) + if (Object.keys(params).length > 0) throw new Error('--version and --group need --api.') + return call('/apis', {}) + }, format: (reply) => { if (Array.isArray(reply['apis'])) { return (reply['apis'] as Array<{ key: string; title: string; versions: string[] }>) diff --git a/src/docs/client.ts b/src/docs/client.ts index 40b0017b..ff062a9b 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -199,16 +199,16 @@ export function newUuid (): string { } /** - * Query the API Explorer lookups of the docs API (`/_api/v1/api-reference`). - * `path` is `/search`, `/operation`, or `/` (list); null and undefined params are dropped. + * GET the API operations resource of the docs API (`/_api/v1/api-operations`). + * `path` is appended as is, so callers encode any id in it; null and undefined params are dropped. * Throws with the server's `message` on a non-2xx reply. */ -export async function docsApiReference (path: string, params: Record): Promise { +export async function docsApiOperations (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 resp = await fetch(`${DOCS_BASE_URL}/_api/v1/api-reference${path}?${qs.toString()}`, { + const resp = await fetch(`${DOCS_BASE_URL}/_api/v1/api-operations${path}?${qs.toString()}`, { redirect: 'error', headers: { Accept: 'application/json', Cookie: DOCS_COOKIE }, }) diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index b7a3a2d4..984a3c6f 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -5,7 +5,7 @@ import { describe, it, afterEach } from 'node:test' import assert from 'node:assert/strict' -import { docsApiReference } from '../../src/docs/client.ts' +import { docsApiOperations } 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' @@ -14,7 +14,7 @@ import { captureDuring } from '../helpers/capture.ts' const realFetch = globalThis.fetch -describe('docsApiReference', () => { +describe('docsApiOperations', () => { afterEach(() => { globalThis.fetch = realFetch }) function install (body: string, status = 200): Array<{ url: string; init: RequestInit }> { @@ -28,9 +28,9 @@ describe('docsApiReference', () => { it('GETs the path with encoded params, dropping null and undefined', async () => { const calls = install(JSON.stringify({ totalHits: 1, results: [] })) - const reply = await docsApiReference('/search', { q: 'GET /{index}/_search?x=1#y', api: 'elasticsearch', version: undefined, include_deprecated: true, size: null }) + const reply = await docsApiOperations('', { q: 'GET /{index}/_search?x=1#y', api: 'elasticsearch', 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/api-reference/search?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&api=elasticsearch&include_deprecated=true') + assert.equal(calls[0]!.url, 'https://www.elastic.co/docs/_api/v1/api-operations?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&api=elasticsearch&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', Cookie: 'feature_search_or_askai_enabled=true' }) @@ -38,12 +38,12 @@ describe('docsApiReference', () => { it('throws the server message of a rejection', async () => { install(JSON.stringify({ errorType: 'operation_not_found', message: 'No API operation matches nope.' }), 404) - await assert.rejects(docsApiReference('/operation', { operation_id: 'nope' }), /^Error: docs api error \(404\): No API operation matches nope\.$/) + await assert.rejects(docsApiOperations('/nope', {}), /^Error: docs api error \(404\): No API operation matches nope\.$/) }) it('drops an HTML error page and keeps the status', async () => { install('forbidden', 403) - await assert.rejects(docsApiReference('/', {}), /^Error: docs api error \(403\): (Forbidden|request failed)$/) + await assert.rejects(docsApiOperations('/apis', {}), /^Error: docs api error \(403\): (Forbidden|request failed)$/) }) }) @@ -65,9 +65,10 @@ async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promi return { stdout: captured.stdout.join(''), exitCode } } -function fake (reply: unknown): { deps: ApiDeps; calls: Array<{ path: string; params: Record }> } { +/** 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: { docsApiReference: async (path, params) => { calls.push({ path, params }); return reply } } } + return { calls, deps: { docsApiOperations: 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: [] } @@ -77,11 +78,11 @@ describe('docs api commands', () => { assert.deepEqual(createApiGroup().commands.map((c) => c.name()), ['search', 'get', 'list']) }) - it('search sends the positional query as q with its flags to /search', async () => { + it('search sends the positional query as q with its flags to the collection', 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: '/search', params: { q: 'GET /_cluster/health', api: 'elasticsearch', include_deprecated: true, size: 5, page: 1 } }]) + assert.deepEqual(calls, [{ path: '', params: { q: 'GET /_cluster/health', api: 'elasticsearch', 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/) }) @@ -100,28 +101,64 @@ describe('docs api commands', () => { assert.equal(calls.length, 0) }) - it('get treats an argument with a slash as an endpoint', async () => { - const { deps, calls } = fake({ operation: op, versions: ['9'], fields: [{ name: 'level', path: 'level', type: 'string', location: 'query', description: 'Detail level' }], otherMatches: [] }) - const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--api', 'elasticsearch']) + it('get with an endpoint lists its matches, then reads the best one by id in its own API', async () => { + const other = { ...op, api: 'kibana', operationId: 'kibana-health', path: '/api/health' } + const { deps, calls } = fake( + { endpoint: 'GET /_cluster/health', results: [op, other] }, + { operation: op, versions: ['9'], fields: [{ name: 'level', path: 'level', type: 'string', location: 'query', description: 'Detail level' }], otherMatches: [] }, + ) + const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--version', '9', '--include-body']) assert.equal(exitCode, 0) - assert.deepEqual(calls[0], { path: '/operation', params: { api: 'elasticsearch', endpoint: 'GET /_cluster/health' } }) + assert.deepEqual(calls, [ + { path: '', params: { endpoint: 'GET /_cluster/health', api: undefined, version: '9' } }, + { path: '/cluster-health', params: { api: 'elasticsearch', version: '9', include_body: true } }, + ]) assert.match(stdout, /# Get cluster health/) assert.match(stdout, /query {4}level Detail level/) + assert.match(stdout, /Other matches:\nGET {4}\/api\/health {2}\(kibana-health\)/) + }) + + it('get with an endpoint that nothing serves fails without a second call', async () => { + const { deps, calls } = fake({ endpoint: 'GET /nope', 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 treats an argument without a slash as an operation id', async () => { const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) - await run(createApiGetCommand(deps), ['cluster-health']) - assert.deepEqual(calls[0]!.params, { operation_id: 'cluster-health' }) + await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch']) + assert.deepEqual(calls, [{ path: '/cluster-health', params: { api: 'elasticsearch', version: undefined, include_body: undefined } }]) + }) + + it('get encodes the operation id into one path segment', async () => { + const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) + await run(createApiGetCommand(deps), ['--operation-id', '..?x=1#y']) + assert.equal(calls[0]!.path, '/..%3Fx%3D1%23y') + }) + + 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']) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) }) - it('get reports a tool error with exit code 1', async () => { - const cmd = createApiGetCommand({ docsApiReference: async () => { throw new Error('No API operation matches nope.') } }) + it('get reports a server error with exit code 1', async () => { + const cmd = createApiGetCommand({ docsApiOperations: async () => { throw new Error('No API operation matches nope.') } }) const { stdout, exitCode } = await run(cmd, ['nope']) 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'])).stdout, 'No operations found.\n') @@ -154,19 +191,26 @@ describe('docs api commands', () => { 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: '/', params: {} }) + assert.deepEqual(calls[0], { path: '/apis', params: {} }) assert.match(stdout, /elasticsearch\s+Elasticsearch API {2}\[main, 9\]/) }) it('list with a key prints groups, operations and the server note', async () => { const { deps, calls } = fake({ api: 'kibana', totalOperations: 1, groups: [{ name: 'cluster', count: 1, operations: [op] }, { name: 'ml', count: 40 }], note: 'Pass group.' }) const { stdout } = await run(createApiListCommand(deps), ['kibana', '--group', 'cluster']) - assert.deepEqual(calls[0]!.params, { group: 'cluster', api: 'kibana' }) + assert.deepEqual(calls[0], { path: '/groups', params: { api: 'kibana', group: 'cluster' } }) assert.match(stdout, /^cluster \(1\)\n {2}GET/) assert.match(stdout, /ml \(40\)/) assert.match(stdout, /Pass group\./) }) + it('list rejects --version without an api key', async () => { + const { deps, calls } = fake({}) + const { exitCode } = await run(createApiListCommand(deps), ['--version', '9']) + assert.equal(exitCode, 1) + assert.equal(calls.length, 0) + }) + it('--json passes the server reply through unchanged', async () => { const reply = { apis: [] } const { deps } = fake(reply) From da78372ab929eba3e0eacab2d61a03babd3994cc Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 14:08:19 +0100 Subject: [PATCH 05/17] feat(docs): use the docs API's apis and api-operations resources Each command is now one request. `get` reads /api-operations/{api}:{id} with --api, and otherwise asks the collection for the full view of every match. `list ` counts its groups, and `list --group` pages through the group's operations with --page and --size. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 31 +++++++++++++- src/docs/api.ts | 61 +++++++++++++++------------- src/docs/client.ts | 6 +-- test/docs/api.test.ts | 94 ++++++++++++++++++++++++++----------------- 4 files changed, 122 insertions(+), 70 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index ce5aa356..a67b59cc 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -121332,10 +121332,37 @@ "name": "group", "type": "string", "required": false, - "summary": "Only the operations of this group, e.g. 'cluster'" + "summary": "List the operations of this group, e.g. 'cluster'. Without it, the API's groups are counted." + }, + { + "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, or the operations of one API by group", + "summary": "List the Elastic REST APIs, the groups of one API, or the operations of one group", "intent": { "requiresAuth": false } diff --git a/src/docs/api.ts b/src/docs/api.ts index 5cf9aa88..9698d1d8 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -5,20 +5,20 @@ import { defineCommand, defineGroup } from '../factory.ts' import type { OpaqueCommandHandle, JsonValue } from '../factory.ts' -import { docsApiOperations } from './client.ts' +import { docsApi } from './client.ts' /** Injectable dependencies for the `docs api` commands. */ export interface ApiDeps { - docsApiOperations: typeof docsApiOperations + docsApi: typeof docsApi } -const defaultDeps: ApiDeps = { docsApiOperations } +const defaultDeps: ApiDeps = { docsApi } // Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. const api = { type: 'string', description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." } -interface Operation { api: string; title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } +interface Operation { id: string; api: string; title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } interface Field { path: string; type: string; location: string; description: string } function absUrl (url: string): string { @@ -40,8 +40,8 @@ interface ApiCommandConfig { positionalArg: { name: string; description: string } /** Maps the positional value onto query parameters. */ fromArg: (arg: string) => Record - /** Sends the request(s); `call` GETs a path under `/_api/v1/api-operations`. */ - request: (params: Record, call: ApiDeps['docsApiOperations']) => Promise + /** Sends the one request; `call` GETs a path under `/_api/v1`. */ + request: (params: Record, call: ApiDeps['docsApi']) => Promise format: (reply: Record) => string } @@ -55,7 +55,7 @@ function apiCommand (config: ApiCommandConfig, deps: ApiDeps): OpaqueCommandHand const arg = parsed.arg?.trim() const params: Record = { ...(parsed.input ?? {}), ...(arg != null && arg !== '' ? config.fromArg(arg) : {}) } try { - return await config.request(params, deps.docsApiOperations) as JsonValue + return await config.request(params, deps.docsApi) as JsonValue } catch (err) { return { error: { code: 'docs_error', message: err instanceof Error ? err.message : String(err) } } } @@ -84,7 +84,7 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm fromArg: (query) => ({ query }), request: async ({ query, ...params }, call) => { if (typeof query !== 'string' || query.trim() === '') throw new Error('query is required') - return call('', { q: query, ...params }) + return call('/api-operations', { q: query, ...params }) }, format: (reply) => { const results = reply['results'] as Array<{ operation: Operation; matchedFields?: Field[] }> @@ -117,15 +117,16 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand fromArg: (arg) => (arg.includes('/') ? { endpoint: arg } : { operation_id: arg }), request: async ({ endpoint, operation_id: operationId, api: key, version: ver, include_body: includeBody }, call) => { if ((endpoint == null) === (operationId == null)) throw new Error('Pass exactly one of an operation id or an endpoint.') - if (operationId != null) { - return call(`/${encodeURIComponent(String(operationId))}`, { api: key, version: ver, include_body: includeBody }) + if (operationId != null && key != null) { + return call(`/api-operations/${encodeURIComponent(`${String(key)}:${String(operationId)}`)}`, { version: ver, include_body: includeBody }) } - // The collection lists every operation that serves the request; read the best one with its fields. - const { results } = await call('', { endpoint, api: key, version: ver }) as { results: Operation[] } + // Without an API key, or for an endpoint, the full view returns every match with its fields, best first. + const { results } = await call('/api-operations', { + endpoint, operation_id: operationId, api: key, 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)}${key != null ? ` in ${String(key)}` : ''}.`) - const detail = await call(`/${encodeURIComponent(best.operationId)}`, { api: best.api, version: ver, include_body: includeBody }) - return { ...(detail as Record), otherMatches: rest } + if (best == null) throw new Error(`No API operation matches ${String(endpoint ?? operationId)}${key != null ? ` 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 } @@ -141,36 +142,38 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand }, deps) } -/** `elastic docs api list`: list the REST APIs, or the operations of one API by group. */ +/** `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, or the operations of one API by group', + description: 'List the Elastic REST APIs, the groups of one API, or the operations of one group', properties: { api: { type: 'string', description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, version, - group: { type: 'string', description: "Only the operations of this group, e.g. 'cluster'" }, + group: { type: 'string', 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)' }, }, positionalArg: { name: 'api', description: 'API key; omit to list every API' }, fromArg: (key) => ({ api: key }), - request: async ({ api: key, ...params }, call) => { - if (key != null) return call('/groups', { api: key, ...params }) - if (Object.keys(params).length > 0) throw new Error('--version and --group need --api.') - return call('/apis', {}) + request: async ({ api: key, group, version: ver, page, size }, call) => { + if (key == null) { + if (group != null || ver != null || page != null || size != null) throw new Error('--version, --group, --page and --size need --api.') + return call('/apis', {}) + } + if (group == null) return call(`/apis/${encodeURIComponent(String(key))}/groups`, { version: ver }) + return call('/api-operations', { api: key, version: ver, group, page, size }) }, format: (reply) => { if (Array.isArray(reply['apis'])) { return (reply['apis'] as Array<{ key: string; title: string; versions: string[] }>) .map((a) => `${a.key.padEnd(24)}${a.title} [${a.versions.join(', ')}]\n`).join('') } - const groups = reply['groups'] as Array<{ name: string; count: number; operations?: Operation[] }> - let out = '' - for (const g of groups) { - out += `${g.name} (${g.count})\n` - if (g.operations != null) out += g.operations.map((o) => ' ' + opLine(o).replace('\n ', '\n ')).join('') + '\n' + 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` } - if (typeof reply['note'] === 'string') out += `\n${reply['note']}\n` - return out + return (reply['groups'] as Array<{ name: string; count: number }>).map((g) => `${g.name} (${g.count})\n`).join('') }, }, deps) } diff --git a/src/docs/client.ts b/src/docs/client.ts index ff062a9b..c32e0b9c 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -199,16 +199,16 @@ export function newUuid (): string { } /** - * GET the API operations resource of the docs API (`/_api/v1/api-operations`). + * GET a path of the docs API under `/_api/v1`, such as `/api-operations` or `/apis`. * `path` is appended as is, so callers encode any id in it; null and undefined params are dropped. * Throws with the server's `message` on a non-2xx reply. */ -export async function docsApiOperations (path: string, params: Record): Promise { +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 resp = await fetch(`${DOCS_BASE_URL}/_api/v1/api-operations${path}?${qs.toString()}`, { + const resp = await fetch(`${DOCS_BASE_URL}/_api/v1${path}?${qs.toString()}`, { redirect: 'error', headers: { Accept: 'application/json', Cookie: DOCS_COOKIE }, }) diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 984a3c6f..4c07bdc9 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -5,7 +5,7 @@ import { describe, it, afterEach } from 'node:test' import assert from 'node:assert/strict' -import { docsApiOperations } from '../../src/docs/client.ts' +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' @@ -14,7 +14,7 @@ import { captureDuring } from '../helpers/capture.ts' const realFetch = globalThis.fetch -describe('docsApiOperations', () => { +describe('docsApi', () => { afterEach(() => { globalThis.fetch = realFetch }) function install (body: string, status = 200): Array<{ url: string; init: RequestInit }> { @@ -28,7 +28,7 @@ describe('docsApiOperations', () => { it('GETs the path with encoded params, dropping null and undefined', async () => { const calls = install(JSON.stringify({ totalHits: 1, results: [] })) - const reply = await docsApiOperations('', { q: 'GET /{index}/_search?x=1#y', api: 'elasticsearch', version: undefined, include_deprecated: true, size: null }) + const reply = await docsApi('/api-operations', { q: 'GET /{index}/_search?x=1#y', api: 'elasticsearch', 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/api-operations?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&api=elasticsearch&include_deprecated=true') assert.equal(calls[0]!.init.method, undefined) @@ -38,12 +38,12 @@ describe('docsApiOperations', () => { it('throws the server message of a rejection', async () => { install(JSON.stringify({ errorType: 'operation_not_found', message: 'No API operation matches nope.' }), 404) - await assert.rejects(docsApiOperations('/nope', {}), /^Error: docs api error \(404\): No API operation matches nope\.$/) + await assert.rejects(docsApi('/api-operations/elasticsearch%3Anope', {}), /^Error: docs api error \(404\): No API operation matches nope\.$/) }) it('drops an HTML error page and keeps the status', async () => { install('forbidden', 403) - await assert.rejects(docsApiOperations('/apis', {}), /^Error: docs api error \(403\): (Forbidden|request failed)$/) + await assert.rejects(docsApi('/apis', {}), /^Error: docs api error \(403\): (Forbidden|request failed)$/) }) }) @@ -68,10 +68,10 @@ async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promi /** 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: { docsApiOperations: async (path, params) => { calls.push({ path, params }); return replies[Math.min(calls.length, replies.length) - 1] } } } + 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: [] } +const op = { id: 'elasticsearch:cluster-health', 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', () => { @@ -82,7 +82,7 @@ describe('docs api commands', () => { 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: '', params: { q: 'GET /_cluster/health', api: 'elasticsearch', include_deprecated: true, size: 5, page: 1 } }]) + assert.deepEqual(calls, [{ path: '/api-operations', params: { q: 'GET /_cluster/health', api: 'elasticsearch', 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/) }) @@ -101,41 +101,52 @@ describe('docs api commands', () => { assert.equal(calls.length, 0) }) - it('get with an endpoint lists its matches, then reads the best one by id in its own API', async () => { - const other = { ...op, api: 'kibana', operationId: 'kibana-health', path: '/api/health' } - const { deps, calls } = fake( - { endpoint: 'GET /_cluster/health', results: [op, other] }, - { operation: op, versions: ['9'], fields: [{ name: 'level', path: 'level', type: 'string', location: 'query', description: 'Detail level' }], otherMatches: [] }, - ) - const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--version', '9', '--include-body']) + it('get with an endpoint reads every match with its fields in one request', async () => { + const other = { ...op, id: 'kibana:kibana-health', api: 'kibana', operationId: 'kibana-health', path: '/api/health' } + 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', '--include-body']) assert.equal(exitCode, 0) - assert.deepEqual(calls, [ - { path: '', params: { endpoint: 'GET /_cluster/health', api: undefined, version: '9' } }, - { path: '/cluster-health', params: { api: 'elasticsearch', version: '9', include_body: true } }, - ]) + assert.deepEqual(calls, [{ path: '/api-operations', params: { endpoint: 'GET /_cluster/health', operation_id: undefined, api: undefined, 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}\/api\/health {2}\(kibana-health\)/) }) - it('get with an endpoint that nothing serves fails without a second call', async () => { - const { deps, calls } = fake({ endpoint: 'GET /nope', results: [] }) + it('get --json returns one operation shape for a lookup through the collection', async () => { + const { deps } = fake({ totalHits: 1, results: [{ operation: op, versions: ['9'], fields: [] }] }) + const cmd = createApiGetCommand(deps) + cmd.option('--json') + const { stdout } = await run(cmd, ['cluster-health', '--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 treats an argument without a slash as an operation id', async () => { + 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: [] }) - await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch']) - assert.deepEqual(calls, [{ path: '/cluster-health', params: { api: 'elasticsearch', version: undefined, include_body: undefined } }]) + const { exitCode } = await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch', '--version', '9']) + assert.equal(exitCode, 0) + assert.deepEqual(calls, [{ path: '/api-operations/elasticsearch%3Acluster-health', params: { version: '9', include_body: undefined } }]) + }) + + it('get without an api looks the operation id up across APIs', async () => { + const { deps, calls } = fake({ totalHits: 1, results: [{ operation: op, versions: [], fields: [] }] }) + await run(createApiGetCommand(deps), ['cluster-health']) + assert.deepEqual(calls[0], { path: '/api-operations', params: { endpoint: undefined, operation_id: 'cluster-health', api: undefined, version: undefined, view: 'full', include_body: undefined } }) }) - it('get encodes the operation id into one path segment', async () => { + it('get encodes the id into one path segment', async () => { const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) - await run(createApiGetCommand(deps), ['--operation-id', '..?x=1#y']) - assert.equal(calls[0]!.path, '/..%3Fx%3D1%23y') + await run(createApiGetCommand(deps), ['--operation-id', '../x?y=1#z', '--api', 'a/b']) + assert.equal(calls[0]!.path, '/api-operations/a%2Fb%3A..%2Fx%3Fy%3D1%23z') }) it('get rejects both an operation id and an endpoint without calling the server', async () => { @@ -146,7 +157,7 @@ describe('docs api commands', () => { }) it('get reports a server error with exit code 1', async () => { - const cmd = createApiGetCommand({ docsApiOperations: async () => { throw new Error('No API operation matches nope.') } }) + const cmd = createApiGetCommand({ docsApi: async () => { throw new Error('No API operation matches nope.') } }) const { stdout, exitCode } = await run(cmd, ['nope']) assert.equal(exitCode, 1) assert.equal(stdout, '') @@ -172,7 +183,7 @@ describe('docs api commands', () => { body: 'Full body.', otherMatches: [{ ...op, api: 'kibana', path: '/api/health' }], }) - const { stdout } = await run(createApiGetCommand(deps), ['cluster-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/) @@ -195,13 +206,24 @@ describe('docs api commands', () => { assert.match(stdout, /elasticsearch\s+Elasticsearch API {2}\[main, 9\]/) }) - it('list with a key prints groups, operations and the server note', async () => { - const { deps, calls } = fake({ api: 'kibana', totalOperations: 1, groups: [{ name: 'cluster', count: 1, operations: [op] }, { name: 'ml', count: 40 }], note: 'Pass group.' }) - const { stdout } = await run(createApiListCommand(deps), ['kibana', '--group', 'cluster']) - assert.deepEqual(calls[0], { path: '/groups', params: { api: 'kibana', group: 'cluster' } }) - assert.match(stdout, /^cluster \(1\)\n {2}GET/) - assert.match(stdout, /ml \(40\)/) - assert.match(stdout, /Pass group\./) + 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: '/api-operations', params: { api: 'elasticsearch', 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('list rejects --version without an api key', async () => { From 71ef7b70741ca28101da47a7447281af399626a8 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 16:16:11 +0100 Subject: [PATCH 06/17] fix(docs): read docs API errors as RFC 9457 problems The docs API answers every error as application/problem+json. The error message is now the problem's detail, or its title when there is none, and requests accept application/problem+json. Co-Authored-By: Claude Opus 5.5 --- src/docs/client.ts | 12 +++++++----- test/docs/api.test.ts | 26 ++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/docs/client.ts b/src/docs/client.ts index c32e0b9c..50f5b8e4 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -201,7 +201,7 @@ export function newUuid (): string { /** * GET a path of the docs API under `/_api/v1`, such as `/api-operations` or `/apis`. * `path` is appended as is, so callers encode any id in it; null and undefined params are dropped. - * Throws with the server's `message` on a non-2xx reply. + * 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() @@ -210,15 +210,17 @@ export async function docsApi (path: string, params: Record): P } const resp = await fetch(`${DOCS_BASE_URL}/_api/v1${path}?${qs.toString()}`, { redirect: 'error', - headers: { Accept: 'application/json', Cookie: DOCS_COOKIE }, + headers: { Accept: 'application/json, application/problem+json', Cookie: DOCS_COOKIE }, }) const text = await resp.text().catch(() => '') if (!resp.ok) { - // A CDN or site error page is HTML; only the docs API's JSON rejection carries a useful message. + // 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. let message = resp.statusText || 'request failed' try { - const body = JSON.parse(text) as { message?: unknown } - if (typeof body.message === 'string') message = body.message + 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 } diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 4c07bdc9..31d7a757 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -33,12 +33,30 @@ describe('docsApi', () => { assert.equal(calls[0]!.url, 'https://www.elastic.co/docs/_api/v1/api-operations?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&api=elasticsearch&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', Cookie: 'feature_search_or_askai_enabled=true' }) + assert.deepEqual(calls[0]!.init.headers, { Accept: 'application/json, application/problem+json', Cookie: 'feature_search_or_askai_enabled=true' }) }) - it('throws the server message of a rejection', async () => { - install(JSON.stringify({ errorType: 'operation_not_found', message: 'No API operation matches nope.' }), 404) - await assert.rejects(docsApi('/api-operations/elasticsearch%3Anope', {}), /^Error: docs api error \(404\): No API operation matches nope\.$/) + 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('/api-operations/elasticsearch%3Anope', {}), /^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('/api-operations/elasticsearch%3Anope', {}), /^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|request failed)$/) }) it('drops an HTML error page and keeps the status', async () => { From 057f895ff4f5bcbe82096b8cd2de4a158581d199 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 16:44:27 +0100 Subject: [PATCH 07/17] fix(docs): validate docs api arguments before any request or dry run A positional argument reached the handler only after schema validation, so the schema could not require it: `search` without a query and `get` with neither or both selectors passed validation, failed on the server, and reported success under --dry-run. positionalArg.toInput now maps the value into the input before validation, and the docs api schemas require a non-blank query, exactly one of endpoint or operation_id, and api for version, group, page and size. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 26 +++++++++++++++++++---- src/docs/api.ts | 34 +++++++++++++++--------------- src/factory-core.ts | 11 +++++++++- src/factory.ts | 5 +++++ test/docs/api.test.ts | 29 +++++++++++++++++++++++++ test/factory.test.ts | 49 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 132 insertions(+), 22 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index a67b59cc..f39f8851 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -121185,8 +121185,14 @@ "role": "flag", "name": "query", "type": "string", - "required": false, - "summary": "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" + "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", @@ -121263,14 +121269,26 @@ "name": "endpoint", "type": "string", "required": false, - "summary": "A route as you would call it, e.g. 'GET /my-index/_search'" + "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'" + "summary": "The OpenAPI operation id, e.g. 'cluster-health'", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] }, { "role": "flag", diff --git a/src/docs/api.ts b/src/docs/api.ts index 9698d1d8..f14e38ca 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -16,6 +16,8 @@ const defaultDeps: ApiDeps = { docsApi } // Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. const api = { type: 'string', description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } +// A value that is more than whitespace. +const nonBlank = { type: 'string', pattern: '\\S' } const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." } interface Operation { id: string; api: string; title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } @@ -37,8 +39,10 @@ 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 query parameters. */ + /** 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 @@ -49,11 +53,10 @@ function apiCommand (config: ApiCommandConfig, deps: ApiDeps): OpaqueCommandHand return defineCommand({ name: config.name, description: config.description, - input: { type: 'object', properties: config.properties, additionalProperties: false }, - positionalArg: { ...config.positionalArg, required: false }, + 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 arg = parsed.arg?.trim() - const params: Record = { ...(parsed.input ?? {}), ...(arg != null && arg !== '' ? config.fromArg(arg) : {}) } + const params: Record = { ...(parsed.input ?? {}) } try { return await config.request(params, deps.docsApi) as JsonValue } catch (err) { @@ -73,19 +76,17 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm name: 'search', description: 'Search the Elastic REST API reference for operations', properties: { - query: { type: 'string', description: "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" }, + query: { ...nonBlank, description: "Words, an endpoint such as 'GET /_cluster/health', or a field path; end a field with '.' to list its children" }, api, version, 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'], dependencies: { version: ['api'] } }, positionalArg: { name: 'query', description: 'Words, an endpoint, or a field path' }, fromArg: (query) => ({ query }), - request: async ({ query, ...params }, call) => { - if (typeof query !== 'string' || query.trim() === '') throw new Error('query is required') - return call('/api-operations', { q: query, ...params }) - }, + request: async ({ query, ...params }, call) => call('/api-operations', { q: query, ...params }), format: (reply) => { const results = reply['results'] as Array<{ operation: Operation; matchedFields?: Field[] }> if (results.length === 0) return 'No operations found.\n' @@ -106,17 +107,18 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand name: 'get', description: 'Get one operation from the Elastic REST API reference, with its parameters and fields', properties: { - endpoint: { type: 'string', description: "A route as you would call it, e.g. 'GET /my-index/_search'" }, - operation_id: { type: 'string', description: "The OpenAPI operation id, e.g. 'cluster-health'" }, + endpoint: { ...nonBlank, description: "A route as you would call it, e.g. 'GET /my-index/_search'" }, + operation_id: { ...nonBlank, description: "The OpenAPI operation id, e.g. 'cluster-health'" }, api, version, include_body: { type: 'boolean', description: 'Include the page body' }, }, + // Exactly one way to name the operation. + rules: { oneOf: [{ required: ['endpoint'] }, { required: ['operation_id'] }], dependencies: { version: ['api'] } }, 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, version: ver, include_body: includeBody }, call) => { - if ((endpoint == null) === (operationId == null)) throw new Error('Pass exactly one of an operation id or an endpoint.') if (operationId != null && key != null) { return call(`/api-operations/${encodeURIComponent(`${String(key)}:${String(operationId)}`)}`, { version: ver, include_body: includeBody }) } @@ -154,13 +156,11 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman 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: { 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, version: ver, page, size }, call) => { - if (key == null) { - if (group != null || ver != null || page != null || size != null) throw new Error('--version, --group, --page and --size need --api.') - return call('/apis', {}) - } + if (key == null) return call('/apis', {}) if (group == null) return call(`/apis/${encodeURIComponent(String(key))}/groups`, { version: ver }) return call('/api-operations', { api: key, version: ver, group, page, size }) }, diff --git a/src/factory-core.ts b/src/factory-core.ts index ecc5203e..4b22947a 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -78,7 +78,16 @@ export interface CommandConfig { name: string description: string options?: OptionDefinition[] - positionalArg?: { name: string; description: string; required?: boolean } + positionalArg?: { + name: string + description: string + required?: boolean + /** + * Maps the positional value onto schema input fields before validation, so the schema can require them and + * `--dry-run` rejects what a real run would. Flags and JSON input win over the fields it sets. + */ + 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 e683eb2c..5b32d838 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -857,6 +857,11 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { const positionalValue = config.positionalArg != null ? (cmd.processedArgs[0] as string | undefined) : undefined + const toInput = config.positionalArg?.toInput + if (merged !== undefined && positionalValue !== undefined && toInput != null) { + const given = typeof merged.input === 'object' && merged.input !== null ? merged.input : {} + merged.input = { ...toInput(positionalValue), ...given } + } const resolvedConfig = getResolvedConfig() enforceCommandPolicy(cmd, resolvedConfig?.commands, jsonFormat) diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 31d7a757..61a65c7a 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -251,6 +251,35 @@ describe('docs api commands', () => { 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 with --version but no --api', createApiSearchCommand, ['x', '--version', '9']], + ['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']], + ['list with --group but no api', createApiListCommand, ['--group', 'cluster']], + ['list with --page but no --group', createApiListCommand, ['elasticsearch', '--page', '2']], + ] 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) + }) + } + } + + 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) diff --git a/test/factory.test.ts b/test/factory.test.ts index 2a0adfb8..f456f682 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -248,6 +248,55 @@ 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' } }, 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[]): Promise<{ received: ParsedResult[]; failed: boolean }> { + const received: ParsedResult[] = [] + const restore = _testSetStdinReader(() => '') + 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' }) + }) + + it('lets an explicit flag win over the positional value', async () => { + const { received } = await run(['positional', '--query', 'flag']) + 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) + } + }) + }) + it('sets parsed.arg to undefined when no positionalArg is declared', async () => { const received: ParsedResult[] = [] const cmd = defineCommand({ From bee18dbc2761f2733855b338b2e0ecbff94482de Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 17:29:27 +0100 Subject: [PATCH 08/17] feat(docs): address docs api operations inside their API The docs API dropped lookups across APIs: most operation ids and many routes exist in several APIs, so such a lookup could only guess. `search` and `get` now require --api and call /apis/{api}/operations, and `get ` reads /apis/{api}/operations/{operationId}. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 26 ++++++++++++++----- src/docs/api.ts | 34 ++++++++++++++---------- src/docs/client.ts | 2 +- test/docs/api.test.ts | 60 ++++++++++++++++++++----------------------- 4 files changed, 69 insertions(+), 53 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index f39f8851..99949091 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -121198,15 +121198,21 @@ "role": "flag", "name": "api", "type": "string", - "required": false, - "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." + "required": true, + "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] }, { "role": "flag", "name": "version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." }, { "role": "flag", @@ -121294,15 +121300,21 @@ "role": "flag", "name": "api", "type": "string", - "required": false, - "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." + "required": true, + "summary": "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] }, { "role": "flag", "name": "version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." }, { "role": "flag", @@ -121343,7 +121355,7 @@ "name": "version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." }, { "role": "flag", diff --git a/src/docs/api.ts b/src/docs/api.ts index f14e38ca..c052ba73 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -15,12 +15,19 @@ export interface ApiDeps { const defaultDeps: ApiDeps = { docsApi } // Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. -const api = { type: 'string', description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } // A value that is more than whitespace. const nonBlank = { type: 'string', pattern: '\\S' } -const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Needs --api. Without it, the current version is used." } +// 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 = { ...nonBlank, description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } +const version = { type: 'string', 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/${encodeURIComponent(String(key))}/operations` +} -interface Operation { id: string; api: string; title: string; url: string; method: string; path: string; operationId: string; deprecated?: boolean } interface Field { path: string; type: string; location: string; description: string } function absUrl (url: string): string { @@ -83,10 +90,10 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm 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'], dependencies: { version: ['api'] } }, + rules: { required: ['query', 'api'] }, positionalArg: { name: 'query', description: 'Words, an endpoint, or a field path' }, fromArg: (query) => ({ query }), - request: async ({ query, ...params }, call) => call('/api-operations', { q: query, ...params }), + request: async ({ query, api: key, ...params }, call) => call(operationsOf(key), { q: query, ...params }), format: (reply) => { const results = reply['results'] as Array<{ operation: Operation; matchedFields?: Field[] }> if (results.length === 0) return 'No operations found.\n' @@ -114,20 +121,21 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand include_body: { type: 'boolean', description: 'Include the page body' }, }, // Exactly one way to name the operation. - rules: { oneOf: [{ required: ['endpoint'] }, { required: ['operation_id'] }], dependencies: { version: ['api'] } }, + 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, version: ver, include_body: includeBody }, call) => { - if (operationId != null && key != null) { - return call(`/api-operations/${encodeURIComponent(`${String(key)}:${String(operationId)}`)}`, { version: ver, include_body: includeBody }) + if (operationId != null) { + return call(`${operationsOf(key)}/${encodeURIComponent(String(operationId))}`, { version: ver, include_body: includeBody }) } - // Without an API key, or for an endpoint, the full view returns every match with its fields, best first. - const { results } = await call('/api-operations', { - endpoint, operation_id: operationId, api: key, version: ver, view: 'full', 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 ?? operationId)}${key != null ? ` in ${String(key)}` : ''}.`) + 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) => { @@ -162,7 +170,7 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman request: async ({ api: key, group, version: ver, page, size }, call) => { if (key == null) return call('/apis', {}) if (group == null) return call(`/apis/${encodeURIComponent(String(key))}/groups`, { version: ver }) - return call('/api-operations', { api: key, version: ver, group, page, size }) + return call(operationsOf(key), { version: ver, group, page, size }) }, format: (reply) => { if (Array.isArray(reply['apis'])) { diff --git a/src/docs/client.ts b/src/docs/client.ts index 50f5b8e4..6af6f0cb 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -199,7 +199,7 @@ export function newUuid (): string { } /** - * GET a path of the docs API under `/_api/v1`, such as `/api-operations` or `/apis`. + * 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. */ diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 61a65c7a..3fa99e04 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -28,9 +28,9 @@ describe('docsApi', () => { it('GETs the path with encoded params, dropping null and undefined', async () => { const calls = install(JSON.stringify({ totalHits: 1, results: [] })) - const reply = await docsApi('/api-operations', { q: 'GET /{index}/_search?x=1#y', api: 'elasticsearch', version: undefined, include_deprecated: true, size: null }) + 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/api-operations?q=GET+%2F%7Bindex%7D%2F_search%3Fx%3D1%23y&api=elasticsearch&include_deprecated=true') + 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', Cookie: 'feature_search_or_askai_enabled=true' }) @@ -46,12 +46,12 @@ describe('docsApi', () => { it('throws the detail of an RFC 9457 problem', async () => { install(JSON.stringify(problem), 404) - await assert.rejects(docsApi('/api-operations/elasticsearch%3Anope', {}), /^Error: docs api error \(404\): No API operation matches nope in elasticsearch\.$/) + 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('/api-operations/elasticsearch%3Anope', {}), /^Error: docs api error \(404\): API operation not found$/) + 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 () => { @@ -89,54 +89,54 @@ function fake (...replies: unknown[]): { deps: ApiDeps; calls: Array<{ path: str return { calls, deps: { docsApi: async (path, params) => { calls.push({ path, params }); return replies[Math.min(calls.length, replies.length) - 1] } } } } -const op = { id: 'elasticsearch:cluster-health', api: 'elasticsearch', title: 'Get cluster health', url: '/docs/api/doc/elasticsearch/operation/operation-cluster-health', method: 'GET', path: '/_cluster/health', operationId: 'cluster-health', endpoints: [] } +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 collection', async () => { + 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: '/api-operations', params: { q: 'GET /_cluster/health', api: 'elasticsearch', include_deprecated: true, size: 5, page: 1 } }]) + assert.deepEqual(calls, [{ path: '/apis/elasticsearch/operations', params: { q: 'GET /_cluster/health', 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', '--size', '0']) + 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","bogus":1}') + 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 with its fields in one request', async () => { - const other = { ...op, id: 'kibana:kibana-health', api: 'kibana', operationId: 'kibana-health', path: '/api/health' } + 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', '--include-body']) + const { stdout, exitCode } = await run(createApiGetCommand(deps), ['GET /_cluster/health', '--api', 'elasticsearch', '--include-body']) assert.equal(exitCode, 0) - assert.deepEqual(calls, [{ path: '/api-operations', params: { endpoint: 'GET /_cluster/health', operation_id: undefined, api: undefined, version: undefined, view: 'full', include_body: true } }]) + 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}\/api\/health {2}\(kibana-health\)/) + assert.match(stdout, /Other matches:\nGET {4}\/\{index\} {2}\(indices-get\)/) }) - it('get --json returns one operation shape for a lookup through the collection', async () => { + 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, ['cluster-health', '--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: [] }) }) @@ -152,31 +152,25 @@ describe('docs api commands', () => { const { deps, calls } = fake({ operation: op, versions: [], fields: [], otherMatches: [] }) const { exitCode } = await run(createApiGetCommand(deps), ['cluster-health', '--api', 'elasticsearch', '--version', '9']) assert.equal(exitCode, 0) - assert.deepEqual(calls, [{ path: '/api-operations/elasticsearch%3Acluster-health', params: { version: '9', include_body: undefined } }]) + assert.deepEqual(calls, [{ path: '/apis/elasticsearch/operations/cluster-health', params: { version: '9', include_body: undefined } }]) }) - it('get without an api looks the operation id up across APIs', async () => { - const { deps, calls } = fake({ totalHits: 1, results: [{ operation: op, versions: [], fields: [] }] }) - await run(createApiGetCommand(deps), ['cluster-health']) - assert.deepEqual(calls[0], { path: '/api-operations', params: { endpoint: undefined, operation_id: 'cluster-health', api: undefined, version: undefined, view: 'full', include_body: undefined } }) - }) - - it('get encodes the id into one path segment', async () => { + 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, '/api-operations/a%2Fb%3A..%2Fx%3Fy%3D1%23z') + 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']) + 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']) + const { stdout, exitCode } = await run(cmd, ['nope', '--api', 'elasticsearch']) assert.equal(exitCode, 1) assert.equal(stdout, '') }) @@ -190,7 +184,7 @@ describe('docs api commands', () => { it('search reports no results', async () => { const { deps } = fake({ query: 'x', totalHits: 0, results: [] }) - assert.equal((await run(createApiSearchCommand(deps), ['x'])).stdout, 'No operations found.\n') + 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 () => { @@ -213,7 +207,7 @@ describe('docs api commands', () => { const { deps } = fake({ query: 'x', totalHits: 3, results: [] }) const cmd = createApiSearchCommand(deps) cmd.option('--output-fields ') - const { stdout } = await run(cmd, ['x', '--output-fields', 'totalHits']) + const { stdout } = await run(cmd, ['x', '--api', 'elasticsearch', '--output-fields', 'totalHits']) assert.deepEqual(JSON.parse(stdout), { totalHits: 3 }) }) @@ -234,7 +228,7 @@ describe('docs api commands', () => { 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: '/api-operations', params: { api: 'elasticsearch', version: undefined, group: 'cluster', page: 2, size: undefined } }) + 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$/) }) @@ -257,10 +251,12 @@ describe('docs api commands', () => { for (const [name, create, argv] of [ ['search without a query', createApiSearchCommand, []], ['search with a blank query', createApiSearchCommand, [' ']], - ['search with --version but no --api', createApiSearchCommand, ['x', '--version', '9']], + ['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']], + ['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']], ] as const) { From 0e7d11cacc4fa9ad9fc4c688798218688506df1c Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Wed, 18 Nov 2026 12:45:43 +0100 Subject: [PATCH 09/17] fix(docs): send no cookie on docs api requests elastic/docs-infra#523 removed the CDN's cookie gate. #829 drops it from search and ask on main. Co-Authored-By: Claude Opus 5.5 --- src/docs/client.ts | 2 +- test/docs/api.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/docs/client.ts b/src/docs/client.ts index 6af6f0cb..7e26f219 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -210,7 +210,7 @@ export async function docsApi (path: string, params: Record): P } const resp = await fetch(`${DOCS_BASE_URL}/_api/v1${path}?${qs.toString()}`, { redirect: 'error', - headers: { Accept: 'application/json, application/problem+json', Cookie: DOCS_COOKIE }, + headers: { Accept: 'application/json, application/problem+json' }, }) const text = await resp.text().catch(() => '') if (!resp.ok) { diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 3fa99e04..1336ed43 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -33,7 +33,7 @@ describe('docsApi', () => { 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', Cookie: 'feature_search_or_askai_enabled=true' }) + assert.deepEqual(calls[0]!.init.headers, { Accept: 'application/json, application/problem+json' }) }) const problem = { From 559848ae4c25ea9682f4f78d7899f6f707237903 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Fri, 20 Nov 2026 16:21:55 +0100 Subject: [PATCH 10/17] fix(docs): align long api keys and name the status of a non-problem error elastic docs api list padded keys to 24 columns, so elasticsearch-serverless ran into its title. Over HTTP/2 a reply has no status text, and www.elastic.co's CDN answers an API 404 with its HTML page, so the error read "request failed"; it now names the status. Co-Authored-By: Claude Opus 5.5 --- src/docs/api.ts | 5 +++-- src/docs/client.ts | 6 ++++-- test/docs/api.test.ts | 13 +++++++++++-- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/docs/api.ts b/src/docs/api.ts index c052ba73..eb984f97 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -174,8 +174,9 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman }, format: (reply) => { if (Array.isArray(reply['apis'])) { - return (reply['apis'] as Array<{ key: string; title: string; versions: string[] }>) - .map((a) => `${a.key.padEnd(24)}${a.title} [${a.versions.join(', ')}]\n`).join('') + 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 }> diff --git a/src/docs/client.ts b/src/docs/client.ts index a18f4f22..536dfd0e 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 @@ -212,8 +214,8 @@ export async function docsApi (path: string, params: Record): P 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. - let message = resp.statusText || 'request failed' + // `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 diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 1336ed43..82fcaca0 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -56,12 +56,12 @@ describe('docsApi', () => { 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|request failed)$/) + await assert.rejects(docsApi('/apis', {}), /^Error: docs api error \(404\): Not Found$/) }) 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|request failed)$/) + await assert.rejects(docsApi('/apis', {}), /^Error: docs api error \(403\): Forbidden$/) }) }) @@ -218,6 +218,15 @@ describe('docs api commands', () => { 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']) From 7661ceffc0e919e31d6228117b649d55d4036cde Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Mon, 23 Nov 2026 10:40:32 +0100 Subject: [PATCH 11/17] fix(docs): rename --version to --api-version and reject a blank list api - `elastic --version` prints the CLI version, so `docs api` names the API version `--api-version` and still sends it as the `version` query parameter. - `docs api list` rejects a blank API key instead of requesting `/apis//groups`. - A 2xx reply that is not JSON, such as a CDN maintenance page, reports `the reply is not JSON` instead of a SyntaxError. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 14 ++++++++++---- src/docs/api.ts | 22 ++++++++++++---------- src/docs/client.ts | 7 ++++++- test/docs/api.test.ts | 26 ++++++++++++++++++++++---- 4 files changed, 50 insertions(+), 19 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 9a8c432c..50cd8f4a 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -123263,7 +123263,7 @@ }, { "role": "flag", - "name": "version", + "name": "api-version", "type": "string", "required": false, "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." @@ -123365,7 +123365,7 @@ }, { "role": "flag", - "name": "version", + "name": "api-version", "type": "string", "required": false, "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." @@ -123402,11 +123402,17 @@ "name": "api", "type": "string", "required": false, - "summary": "API key, e.g. 'elasticsearch'. Omit to list every API." + "summary": "API key, e.g. 'elasticsearch'. Omit to list every API.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] }, { "role": "flag", - "name": "version", + "name": "api-version", "type": "string", "required": false, "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." diff --git a/src/docs/api.ts b/src/docs/api.ts index eb984f97..67cda043 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -14,13 +14,15 @@ export interface ApiDeps { const defaultDeps: ApiDeps = { docsApi } -// Schema keys are the docs API query parameters (`query` is sent as `q`); toKebabCase turns them into flags. +// 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' } // 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 = { ...nonBlank, description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } -const version = { type: 'string', description: "API version: 'main' or a major such as '9'. Without it, the current version is used." } +// Not --version: `elastic --version` prints the CLI's own version. +const apiVersion = { type: 'string', 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. */ @@ -85,7 +87,7 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm 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, - version, + 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 }, @@ -93,7 +95,7 @@ export function createApiSearchCommand (deps: ApiDeps = defaultDeps): OpaqueComm rules: { required: ['query', 'api'] }, positionalArg: { name: 'query', description: 'Words, an endpoint, or a field path' }, fromArg: (query) => ({ query }), - request: async ({ query, api: key, ...params }, call) => call(operationsOf(key), { q: query, ...params }), + 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' @@ -117,7 +119,7 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand endpoint: { ...nonBlank, description: "A route as you would call it, e.g. 'GET /my-index/_search'" }, operation_id: { ...nonBlank, description: "The OpenAPI operation id, e.g. 'cluster-health'" }, api, - version, + api_version: apiVersion, include_body: { type: 'boolean', description: 'Include the page body' }, }, // Exactly one way to name the operation. @@ -125,7 +127,7 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand 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, version: ver, include_body: includeBody }, call) => { + request: async ({ endpoint, operation_id: operationId, api: key, api_version: ver, include_body: includeBody }, call) => { if (operationId != null) { return call(`${operationsOf(key)}/${encodeURIComponent(String(operationId))}`, { version: ver, include_body: includeBody }) } @@ -158,16 +160,16 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman name: 'list', description: 'List the Elastic REST APIs, the groups of one API, or the operations of one group', properties: { - api: { type: 'string', description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, - version, + api: { ...nonBlank, description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, + api_version: apiVersion, group: { type: 'string', 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: { version: ['api'], group: ['api'], page: ['group'], size: ['group'] } }, + 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, version: ver, page, size }, call) => { + request: async ({ api: key, group, api_version: ver, page, size }, call) => { if (key == null) return call('/apis', {}) if (group == null) return call(`/apis/${encodeURIComponent(String(key))}/groups`, { version: ver }) return call(operationsOf(key), { version: ver, group, page, size }) diff --git a/src/docs/client.ts b/src/docs/client.ts index 536dfd0e..8e4c211f 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -225,5 +225,10 @@ export async function docsApi (path: string, params: Record): P } throw new Error(`docs api error (${resp.status}): ${message}`) } - return JSON.parse(text) as unknown + 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/test/docs/api.test.ts b/test/docs/api.test.ts index 82fcaca0..ed5d887d 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -59,6 +59,11 @@ describe('docsApi', () => { 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$/) @@ -100,7 +105,7 @@ describe('docs api commands', () => { 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', include_deprecated: true, size: 5, page: 1 } }]) + 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/) }) @@ -150,7 +155,7 @@ describe('docs api commands', () => { 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', '--version', '9']) + 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 } }]) }) @@ -247,9 +252,19 @@ describe('docs api commands', () => { assert.equal(calls[0]!.path, '/apis/..%2Fx/groups') }) - it('list rejects --version without an api key', async () => { + 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), ['--version', '9']) + const { exitCode } = await run(createApiListCommand(deps), ['--api-version', '9']) assert.equal(exitCode, 1) assert.equal(calls.length, 0) }) @@ -268,6 +283,9 @@ describe('docs api commands', () => { ['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', '']], + ['get with --version, the CLI\'s own flag', createApiGetCommand, ['cluster-health', '--api', 'elasticsearch', '--version', '9']], ] as const) { it(`rejects ${name}${mode} without calling the server`, async () => { const { deps, calls } = fake({}) From cafb60b209478a766fc882fea6eef991235e0c2d Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Mon, 23 Nov 2026 11:54:47 +0100 Subject: [PATCH 12/17] ci: retrigger checks Co-Authored-By: Claude Opus 5.5 From 8d854277ff5f47d7adb5fe9fcee7805c0d6761ef Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 1 Dec 2026 10:53:56 +0100 Subject: [PATCH 13/17] fix(docs): reject non-object JSON roots and blank group and api-version - A positional is merged into the JSON input only when that input is absent or an object. Any other root (null, 42, [], a string) stays as given so the schema rejects it, instead of becoming valid input that sends a request and passes --dry-run. - A JSON null root now fails command input validation. The validator reads null as no input, which passed schemas whose fields are all optional, such as elastic docs api list, and dropped the positional. - group and api_version reject a blank value like the other string parameters, so --group '' no longer sends group=. Co-Authored-By: Claude Sonnet 5.5 --- docs/cli/schema.json | 32 +++++++++++++++++++++++++---- src/docs/api.ts | 4 ++-- src/factory.ts | 15 ++++++++++---- test/docs/api.test.ts | 5 +++++ test/factory.test.ts | 48 +++++++++++++++++++++++++++++++++++++++++-- 5 files changed, 92 insertions(+), 12 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index a7fc9377..a394185f 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -123266,7 +123266,13 @@ "name": "api-version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] }, { "role": "flag", @@ -123368,7 +123374,13 @@ "name": "api-version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." + "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used.", + "validations": [ + { + "kind": "regex", + "pattern": "\\S" + } + ] }, { "role": "flag", @@ -123415,14 +123427,26 @@ "name": "api-version", "type": "string", "required": false, - "summary": "API version: 'main' or a major such as '9'. Without it, the current version is used." + "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." + "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", diff --git a/src/docs/api.ts b/src/docs/api.ts index 67cda043..41ee3ed2 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -22,7 +22,7 @@ const nonBlank = { type: 'string', pattern: '\\S' } // (elasticsearch and elasticsearch-serverless share most of theirs), so a lookup across APIs could only guess. const api = { ...nonBlank, 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 = { type: 'string', description: "API version: 'main' or a major such as '9'. Without it, the current version is used." } +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. */ @@ -162,7 +162,7 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman properties: { api: { ...nonBlank, description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, api_version: apiVersion, - group: { type: 'string', description: "List the operations of this group, e.g. 'cluster'. Without it, the API's groups are counted." }, + 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)' }, }, diff --git a/src/factory.ts b/src/factory.ts index 5a3c4c33..e006af86 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -610,7 +610,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 what else the user gave. + const result: ReturnType = 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) { @@ -884,9 +888,12 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { ? (cmd.processedArgs[0] as string | undefined) : undefined const toInput = config.positionalArg?.toInput - if (merged !== undefined && positionalValue !== undefined && toInput != null) { - const given = typeof merged.input === 'object' && merged.input !== null ? merged.input : {} - merged.input = { ...toInput(positionalValue), ...given } + // Only an absent or object input takes the positional's fields; any other root (null, 42, [], ...) stays + // as given so the schema rejects it rather than a request going out for something the user never wrote. + const root = merged?.input + if (merged !== undefined && positionalValue !== undefined && toInput != null && + (root === undefined || (typeof root === 'object' && root !== null && !Array.isArray(root)))) { + merged.input = { ...toInput(positionalValue), ...root } } const resolvedConfig = getResolvedConfig() diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index ed5d887d..ae7a070a 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -285,6 +285,11 @@ describe('docs api commands', () => { ['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']], ] as const) { it(`rejects ${name}${mode} without calling the server`, async () => { diff --git a/test/factory.test.ts b/test/factory.test.ts index 76258e09..27a5699b 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -262,9 +262,9 @@ describe('defineCommand', () => { return cmd } - async function run (argv: string[]): Promise<{ received: ParsedResult[]; failed: boolean }> { + async function run (argv: string[], stdin = ''): Promise<{ received: ParsedResult[]; failed: boolean }> { const received: ParsedResult[] = [] - const restore = _testSetStdinReader(() => '') + const restore = _testSetStdinReader(() => stdin) let failed = false try { await searchCommand(received).parseAsync(argv, { from: 'user' }) @@ -288,6 +288,50 @@ describe('defineCommand', () => { assert.deepEqual(received[0]?.input, { query: 'flag' }) }) + it('lets JSON input win over the positional value', async () => { + const { received } = await run(['positional'], '{"query":"json"}') + assert.deepEqual(received[0]?.input, { query: '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 () => { + for (const extra of [[], ['--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('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) From b02207200601d24c10d7444b172355b986b7fe7c Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 1 Dec 2026 12:12:37 +0100 Subject: [PATCH 14/17] fix: keep non-object JSON roots when merging flags mergeFlagsIntoInput spread any root into a new object when a schema flag was given, so echo 42 | elastic docs api get cluster-health --api elasticsearch passed validation and sent a request. null, true and [] did the same, also under --dry-run. Flags now merge into an absent or object root only; any other root stays as given and validation rejects it. This applies to every command with JSON input. ES body-root commands already rejected an array root with flags; only their message changes, to must be object. The toInput guard now checks isPlainObject alone, since mergeFlagsIntoInput already turns no input into {}. Co-Authored-By: Claude Opus 5.5 --- src/factory.ts | 18 ++++++++++-------- test/docs/api.test.ts | 19 +++++++++++++++++++ test/factory.test.ts | 9 ++++++++- 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/factory.ts b/src/factory.ts index e006af86..e7e51511 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' @@ -552,8 +553,10 @@ function mergeFlagsIntoInput ( cliInput[positionalKey] = positionalInput } - if (Object.keys(cliInput).length > 0) { - inputValue = { ...(inputValue as Record ?? {}), ...cliInput } + // Flags merge into an absent or object root only. Any other root (null, 42, [], ...) stays as given so + // validation rejects it; merging would turn it into an object that passes and sends a request. + if (Object.keys(cliInput).length > 0 && (inputValue === undefined || isPlainObject(inputValue))) { + inputValue = { ...inputValue, ...cliInput } } // always validate against the schema, even when no input was provided, @@ -888,12 +891,11 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { ? (cmd.processedArgs[0] as string | undefined) : undefined const toInput = config.positionalArg?.toInput - // Only an absent or object input takes the positional's fields; any other root (null, 42, [], ...) stays - // as given so the schema rejects it rather than a request going out for something the user never wrote. - const root = merged?.input - if (merged !== undefined && positionalValue !== undefined && toInput != null && - (root === undefined || (typeof root === 'object' && root !== null && !Array.isArray(root)))) { - merged.input = { ...toInput(positionalValue), ...root } + // Only an object input takes the positional's fields (mergeFlagsIntoInput turns no input into {}); any other + // root (null, 42, [], ...) stays as given so the schema rejects it rather than a request going out for + // something the user never wrote. + if (merged !== undefined && positionalValue !== undefined && toInput != null && isPlainObject(merged.input)) { + merged.input = { ...toInput(positionalValue), ...merged.input } } const resolvedConfig = getResolvedConfig() diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index ae7a070a..60b041f5 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -301,6 +301,25 @@ describe('docs api commands', () => { } } + // 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') + }) + 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']) diff --git a/test/factory.test.ts b/test/factory.test.ts index 27a5699b..862dfa13 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -296,7 +296,8 @@ describe('defineCommand', () => { // 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 () => { - for (const extra of [[], ['--dry-run']]) { + // Flags must not rescue it either: they would otherwise merge into a fresh object. + for (const extra of [[], ['--dry-run'], ['--query', 'flag'], ['--query', 'flag', '--dry-run']]) { const { received, failed } = await run(['positional', ...extra], root) assert.equal(failed, true, `${root} ${extra.join(' ')}`) assert.equal(received.length, 0) @@ -332,6 +333,12 @@ describe('defineCommand', () => { } }) + 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) From b1780918e85247f678b814a02b9cd270e8d18744 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 1 Dec 2026 12:41:11 +0100 Subject: [PATCH 15/17] fix(docs): reject . and .. as an api key or operation id encodeURIComponent keeps . and .., and URL parsing resolves them out of the path, so elastic docs api list .. requested /docs/_api/v1/groups and get .. --api elasticsearch requested the API itself. api and operation_id, the values sent as path segments, now use one pattern that is non-blank and not . or .., so --dry-run fails as a real run would and the rule shows in the CLI schema. The paths are built with the existing encodePathParam, which covers --no-validate; its input_error code is kept instead of becoming docs_error. Co-Authored-By: Claude Opus 5.5 --- docs/cli/schema.json | 8 ++++---- src/docs/api.ts | 21 ++++++++++++++------- test/docs/api.test.ts | 32 +++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 14 deletions(-) diff --git a/docs/cli/schema.json b/docs/cli/schema.json index a394185f..8eb83b5a 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -123257,7 +123257,7 @@ "validations": [ { "kind": "regex", - "pattern": "\\S" + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" } ] }, @@ -123352,7 +123352,7 @@ "validations": [ { "kind": "regex", - "pattern": "\\S" + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" } ] }, @@ -123365,7 +123365,7 @@ "validations": [ { "kind": "regex", - "pattern": "\\S" + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" } ] }, @@ -123418,7 +123418,7 @@ "validations": [ { "kind": "regex", - "pattern": "\\S" + "pattern": "^(?!\\.\\.?$)[\\s\\S]*\\S" } ] }, diff --git a/src/docs/api.ts b/src/docs/api.ts index 41ee3ed2..3906fd95 100644 --- a/src/docs/api.ts +++ b/src/docs/api.ts @@ -6,6 +6,7 @@ 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 { @@ -18,16 +19,20 @@ const defaultDeps: ApiDeps = { docsApi } // 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 = { ...nonBlank, description: "API key, e.g. 'elasticsearch' or 'kibana'. `elastic docs api list` lists the keys." } +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/${encodeURIComponent(String(key))}/operations` + return `/apis/${encodePathParam(String(key))}/operations` } interface Field { path: string; type: string; location: string; description: string } @@ -69,7 +74,9 @@ function apiCommand (config: ApiCommandConfig, deps: ApiDeps): OpaqueCommandHand try { return await config.request(params, deps.docsApi) as JsonValue } catch (err) { - return { error: { code: 'docs_error', message: err instanceof Error ? err.message : String(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 => { @@ -117,7 +124,7 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand 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: { ...nonBlank, description: "The OpenAPI operation id, e.g. 'cluster-health'" }, + 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' }, @@ -129,7 +136,7 @@ export function createApiGetCommand (deps: ApiDeps = defaultDeps): OpaqueCommand 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)}/${encodeURIComponent(String(operationId))}`, { version: ver, include_body: includeBody }) + 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. @@ -160,7 +167,7 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman name: 'list', description: 'List the Elastic REST APIs, the groups of one API, or the operations of one group', properties: { - api: { ...nonBlank, description: "API key, e.g. 'elasticsearch'. Omit to list every API." }, + 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' }, @@ -171,7 +178,7 @@ export function createApiListCommand (deps: ApiDeps = defaultDeps): OpaqueComman 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/${encodeURIComponent(String(key))}/groups`, { version: ver }) + if (group == null) return call(`/apis/${encodePathParam(String(key))}/groups`, { version: ver }) return call(operationsOf(key), { version: ver, group, page, size }) }, format: (reply) => { diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 60b041f5..301d6d90 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -70,10 +70,12 @@ describe('docsApi', () => { }) }) -async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promise<{ stdout: string; exitCode: number }> { +async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promise<{ stdout: string; stderr: string; exitCode: number }> { const restoreStdin = _testSetStdinReader(() => stdin) cmd.exitOverride() - cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} }) + // 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 { @@ -85,7 +87,7 @@ async function run (cmd: OpaqueCommandHandle, argv: string[], stdin = ''): Promi }).finally(restoreStdin) const exitCode = thrown ? 1 : Number(process.exitCode ?? 0) process.exitCode = 0 - return { stdout: captured.stdout.join(''), exitCode } + return { stdout: captured.stdout.join(''), stderr: captured.stderr.join('') + errors.join(''), exitCode } } /** Answers each call with the next reply; the last one repeats. */ @@ -291,6 +293,14 @@ describe('docs api commands', () => { ['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. + ['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({}) @@ -320,6 +330,22 @@ describe('docs api commands', () => { 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']) From 11b205201b8ded308ca2000d033cd1273b84f2de Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Wed, 2 Dec 2026 09:27:14 +0100 Subject: [PATCH 16/17] fix: error on a positional and its flag, and scope strict JSON roots - toInput now works like inputKey: both are applied in mergeFlagsIntoInput, the positional's fields win over JSON input like a flag, and also giving one of them as a flag errors with "pass X either as an argument or as --flag, not both" instead of the flag silently winning. - Only commands whose positional fills input fields (toInput or inputKey) keep a JSON root that is not an object for validation to reject, null included. Every other command merges flags into any root and reads null as no input, as before. - docsApi builds the request URL with new URL, so no params means no trailing ?. Co-Authored-By: Claude Opus 5.5 --- src/docs/client.ts | 4 ++- src/factory-core.ts | 2 +- src/factory.ts | 41 ++++++++++++++------------- test/docs/api.test.ts | 10 +++++++ test/factory.test.ts | 65 +++++++++++++++++++++++++++++++++++++------ 5 files changed, 93 insertions(+), 29 deletions(-) diff --git a/src/docs/client.ts b/src/docs/client.ts index 8e4c211f..b7d9927e 100644 --- a/src/docs/client.ts +++ b/src/docs/client.ts @@ -207,7 +207,9 @@ export async function docsApi (path: string, params: Record): P for (const [key, value] of Object.entries(params)) { if (value != null) qs.set(key, String(value)) } - const resp = await fetch(`${DOCS_BASE_URL}/_api/v1${path}?${qs.toString()}`, { + 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' }, }) diff --git a/src/factory-core.ts b/src/factory-core.ts index 43aaa88b..08e6ece7 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -91,7 +91,7 @@ export interface CommandConfig { /** * 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. - * Flags and JSON input win over the fields it sets. + * Like `inputKey`, the fields win over JSON input, and also giving one of them as a flag is an error. */ toInput?: (value: string) => Record } diff --git a/src/factory.ts b/src/factory.ts index e7e51511..9e494100 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -453,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. */ @@ -543,27 +545,35 @@ 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) - // Flags merge into an absent or object root only. Any other root (null, 42, [], ...) stays as given so - // validation rejects it; merging would turn it into an object that passes and sends a request. - if (Object.keys(cliInput).length > 0 && (inputValue === undefined || isPlainObject(inputValue))) { - inputValue = { ...inputValue, ...cliInput } + // 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 } } // always validate against the schema, even when no input was provided, // 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. */ @@ -614,8 +624,8 @@ async function validateAgainstSchema ( } // 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 what else the user gave. - const result: ReturnType = merged.input === 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) @@ -890,13 +900,6 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { const positionalValue = config.positionalArg != null ? (cmd.processedArgs[0] as string | undefined) : undefined - const toInput = config.positionalArg?.toInput - // Only an object input takes the positional's fields (mergeFlagsIntoInput turns no input into {}); any other - // root (null, 42, [], ...) stays as given so the schema rejects it rather than a request going out for - // something the user never wrote. - if (merged !== undefined && positionalValue !== undefined && toInput != null && isPlainObject(merged.input)) { - merged.input = { ...toInput(positionalValue), ...merged.input } - } const resolvedConfig = getResolvedConfig() enforceCommandPolicy(cmd, resolvedConfig?.commands, jsonFormat) diff --git a/test/docs/api.test.ts b/test/docs/api.test.ts index 301d6d90..e03e3c79 100644 --- a/test/docs/api.test.ts +++ b/test/docs/api.test.ts @@ -26,6 +26,12 @@ describe('docsApi', () => { 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 }) @@ -294,6 +300,10 @@ describe('docs api commands', () => { ['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', '..']], diff --git a/test/factory.test.ts b/test/factory.test.ts index 862dfa13..b42cbf24 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -253,7 +253,7 @@ describe('defineCommand', () => { const cmd = defineCommand({ name: 'search', description: 'Search docs', - input: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'], additionalProperties: false }, + 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 {} }, }) @@ -283,21 +283,30 @@ describe('defineCommand', () => { assert.deepEqual(received[0]?.input, { query: 'ingest pipelines' }) }) - it('lets an explicit flag win over the positional value', async () => { - const { received } = await run(['positional', '--query', 'flag']) - assert.deepEqual(received[0]?.input, { query: 'flag' }) + // 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 JSON input win over the positional value', async () => { - const { received } = await run(['positional'], '{"query":"json"}') - assert.deepEqual(received[0]?.input, { query: 'json' }) + 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'], ['--query', 'flag'], ['--query', 'flag', '--dry-run']]) { + 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) @@ -348,6 +357,46 @@ describe('defineCommand', () => { }) }) + // 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 From b4453122a3e48a1ab5cdf070612e94c815eed659 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Wed, 2 Dec 2026 09:36:32 +0100 Subject: [PATCH 17/17] ci: retrigger checks Co-Authored-By: Claude Opus 5.5