diff --git a/apps/docs/content/docs/cli/output.mdx b/apps/docs/content/docs/cli/output.mdx index f3885829874..245db5f034b 100644 --- a/apps/docs/content/docs/cli/output.mdx +++ b/apps/docs/content/docs/cli/output.mdx @@ -34,7 +34,7 @@ Machine formats preserve API values: a duration remains `1500`, rather than the Read rows with `jq '.data[]'` and check `.nextCursor` for continuation. A null cursor means pagination is finished; inspect any command-specific truncation flags or notices too. See [Pagination](/cli/scripting#pagination) for limits and memory behavior. -When the CLI adds a note to a single result, such as `sim blocks get table` reading as `table_v2`, JSON and YAML carry it in the result as `note`, so output captured with `2>&1` still parses. Tables and text print it on stderr. +What the CLI states about a successful result travels inside it in JSON and YAML, so output captured with `2>&1` still parses: a server-side clip as the response's truncation flag (`truncated`, `toolNamesTruncated`), a fact about a whole list as its envelope field beside `data` and `nextCursor` (`sim billing logs` carries `scope`), and the CLI's own notes as `note`, one per line, such as `sim blocks get table` reading as `table_v2` or a renamed command or flag. Tables and text print each on stderr. A result that is not an object, or a document such as `sim workflows export`, keeps them on stderr. ### Tables and text @@ -52,7 +52,7 @@ An absent value displays as an em dash in a table and an empty field in text. Us ## Separate results and diagnostics -Results go to stdout. Errors, progress, update notices, and operational notes go to stderr, so this pipe receives only the result: +Results go to stdout. Errors, progress, and update notices go to stderr, so this pipe receives only the result. In JSON and YAML output, a rate-limit retry notice is shown only when stderr is a terminal: ```bash sim logs list --output json | jq '.data[]' diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 7615c35d4a0..2514551eece 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -315,7 +315,7 @@ export const CLI_CONTRACT: CliContract = { // Which ledger answered: a user credential reports only the calling user's // events, a workspace key the whole workspace. The difference was silent — // same workspace, same window, same flags, a strictly smaller result. - pageNote: { path: 'scope', label: 'scope' }, + pageNote: { field: 'scope', label: 'scope' }, columns: [ { header: 'at', path: 'createdAt', format: 'timestamp' }, { header: 'workspace', path: 'workspaceId' }, diff --git a/packages/sim-cli/src/contract/types.ts b/packages/sim-cli/src/contract/types.ts index 3852bf69010..e2ecc71ad81 100644 --- a/packages/sim-cli/src/contract/types.ts +++ b/packages/sim-cli/src/contract/types.ts @@ -326,19 +326,17 @@ export interface CommandSpec { /** Dot path to a nested result array rendered as the command's human list. */ itemsPath?: string /** - * A page-envelope field that qualifies the whole list, stated once for the - * human formats. + * A top-level page-envelope field that qualifies the whole list. * * `billing logs` answers a different question depending on the credential — * an OAuth login or personal key sees the caller's own events, while a * workspace key sees the whole workspace ledger. The response says which. The value - * belongs to the query rather than to any row, so it is not a column; it goes - * to stderr so that a `--output text` consumer cutting tab-separated fields - * still reads only rows. `json` and `yaml` print the unwrapped `data` array - * and so drop the field too, which is why the note is not limited to the - * human formats — see `runtime/result`. + * belongs to the query rather than to any row, so it is not a column: `json` and + * `yaml` carry it beside `data` and `nextCursor` under its wire name, and the human + * formats state it once on stderr as `label`, so a `--output text` consumer cutting + * tab-separated fields still reads only rows — see `runtime/result`. */ - pageNote?: { path: string; label: string } + pageNote?: { field: string; label: string } /** Allow an optional workspaceId field to omit the configured workspace filter. */ allWorkspaces?: boolean /** diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index 8d563a9d067..6fc21a53c9e 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -15,7 +15,9 @@ afterEach(() => { // SIM_DEBUG set for one test would otherwise configure every test after it. }) -function client(options: { apiKey?: string } = { apiKey: 'key' }): SimClient { +function client( + options: { apiKey?: string; output?: 'json' | 'table' } = { apiKey: 'key' } +): SimClient { return new SimClient({ name: 'default', endpoint: 'https://sim.example', @@ -23,7 +25,7 @@ function client(options: { apiKey?: string } = { apiKey: 'key' }): SimClient { apiKey: options.apiKey ?? null, oauth: null, workspaceId: 'ws_1', - output: 'json', + output: options.output ?? 'json', sources: { endpoint: 'default', credential: 'env', @@ -33,7 +35,7 @@ function client(options: { apiKey?: string } = { apiKey: 'key' }): SimClient { }) } -function _stubStderr(isTTY: boolean): { writes: string[]; restore: () => void } { +function stubStderr(isTTY: boolean): { writes: string[]; restore: () => void } { const writes: string[] = [] const originalTTY = Object.getOwnPropertyDescriptor(process.stderr, 'isTTY') const originalWrite = process.stderr.write @@ -474,36 +476,35 @@ describe('rate limiting', () => { expect(fetch).toHaveBeenCalledTimes(2) }) - it('says on stderr how long it waits before resending a request answered 429', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const written: string[] = [] - const write = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { - written.push(String(chunk)) - return true - }) - vi.stubGlobal( - 'fetch', - vi - .fn() - .mockResolvedValueOnce(limited('7')) - .mockResolvedValueOnce(Response.json({ data: {} })) - ) + it.each([ + { output: 'json', said: false }, + { output: 'table', said: true }, + ] as const)( + 'off a terminal, says it waits on a 429 for $output output only when that is not a document a 2>&1 capture parses', + async ({ output, said }) => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const stderr = stubStderr(false) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValueOnce(limited('7')) + .mockResolvedValueOnce(Response.json({ data: {} })) + ) - await settle(client().request('/api/v2/tables/tbl_1')) - write.mockRestore() + await settle(client({ apiKey: 'key', output }).request('/api/v2/tables/tbl_1')) + stderr.restore() - expect(written.join('')).toMatch(/Rate limited \(HTTP 429\); retrying in 7s \(retry 1 of 6\)/) - }) + expect(fetch).toHaveBeenCalledTimes(2) + expect(stderr.writes.join('')).toBe( + said ? 'Rate limited (HTTP 429); retrying in 7s (retry 1 of 6).\n' : '' + ) + } + ) - it('clears a terminal progress line before saying it waits on a 429', async () => { + it('says at a terminal how long it waits on a 429, clearing a progress line first', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const written: string[] = [] - const tty = Object.getOwnPropertyDescriptor(process.stderr, 'isTTY') - Object.defineProperty(process.stderr, 'isTTY', { value: true, configurable: true }) - const write = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { - written.push(String(chunk)) - return true - }) + const stderr = stubStderr(true) vi.stubGlobal( 'fetch', vi @@ -513,11 +514,11 @@ describe('rate limiting', () => { ) await settle(client().request('/api/v2/tables/tbl_1')) - write.mockRestore() - if (tty) Object.defineProperty(process.stderr, 'isTTY', tty) - else Reflect.deleteProperty(process.stderr, 'isTTY') + stderr.restore() - expect(written.join('')).toMatch(/^\r\u001b\[K.*Rate limited \(HTTP 429\)/) + expect(stderr.writes.join('')).toMatch( + /^\r\u001b\[K.*Rate limited \(HTTP 429\); retrying in 7s \(retry 1 of 6\)/ + ) }) it('resends a GET answered 429 even when that response body is lost', async () => { diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 2ba577b7b68..dc0d8bcfb5a 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -786,10 +786,16 @@ export class SimClient { ) const backoffMs = backoffWithJitter(rateLimitResends + 1, null, RATE_LIMIT_BACKOFF) const waitMs = Math.max(retryAfterMs ?? 0, backoffMs) - // On a terminal, clear a `fetched N…` paging line first, so the notice starts its own line. - writeStderr( - `${hasProgressTerminal() ? '\r\u001b[K' : ''}${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n` - ) + // Explains a wait of up to minutes, at a terminal or in a CI log of human output. Not in a + // JSON or YAML run off a terminal: there it would land inside a `--output json 2>&1` + // capture of a request that then succeeds, and one whose retries run out is its error. + // On a terminal, a `fetched N…` paging line is cleared first. + const terminal = hasProgressTerminal() + if (terminal || (this.profile.output !== 'json' && this.profile.output !== 'yaml')) { + writeStderr( + `${terminal ? '\r\u001b[K' : ''}${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n` + ) + } await interruptibleSleep(waitMs, caller) if (caller?.aborted) throw new SimApiError('Request cancelled.', 0, REQUEST_CANCELLED) return this.send(path, options, retriedAfterRefresh, rateLimitResends + 1) diff --git a/packages/sim-cli/src/runtime/build.test.ts b/packages/sim-cli/src/runtime/build.test.ts index f01ee35e5dc..a6a68a6eb09 100644 --- a/packages/sim-cli/src/runtime/build.test.ts +++ b/packages/sim-cli/src/runtime/build.test.ts @@ -9,7 +9,6 @@ import { buildGeneratedCommands, } from './build' import { kebab } from './derive' -import { resetRenameWarnings } from './renamed' import type { OperationSpec } from './types' /** @@ -824,7 +823,10 @@ describe('bodies and fields the generator cannot flatten', () => { describe('spellings the CLI has retired', () => { beforeEach(() => { - resetRenameWarnings() + output.format = 'table' + return () => { + output.format = 'json' + } }) function warnings(): string[] { @@ -845,6 +847,14 @@ describe('spellings the CLI has retired', () => { expect(written.join('')).toContain('"--q" has been renamed to "--query"') }) + it('warns once when a successful answer cannot be printed after the warning was written', async () => { + const written = warnings() + await expect( + run(['tables', 'rows', 'find', 'tbl_1', '--q', 'needle'], { data: { matches: 'not a list' } }) + ).rejects.toThrow('expected an array') + expect(written.join('').match(/"--q" has been renamed/g)).toHaveLength(1) + }) + it('refuses both spellings of one flag rather than picking a winner', async () => { await expect( run([ @@ -1007,17 +1017,18 @@ describe('a list that is not the whole answer', () => { /** * The server clips an inventory itself and says so on the envelope, which the * CLI reports separately from data and nextCursor so a reconciling caller - * can distinguish a clipped inventory from a complete one. + * can distinguish a clipped inventory from a complete one. JSON carries the + * flag beside them (`result-notices.test.ts`); a person reads it on stderr. */ - it('carries a truncation the server stated on the envelope', async () => { - const paged = await noteFor('json', ['workflow-mcp-servers', 'list'], { + it('tells a person about a truncation the server stated on the envelope', async () => { + const paged = await noteFor('table', ['workflow-mcp-servers', 'list'], { data: [{ id: 'srv_1' }], nextCursor: null, toolNamesTruncated: true, }) expect(paged).toContain('tool names truncated') - const unpaged = await noteFor('json', ['workflow-mcp-servers', 'tools', 'list', 'srv_1'], { + const unpaged = await noteFor('table', ['workflow-mcp-servers', 'tools', 'list', 'srv_1'], { data: [{ toolName: 't' }], nextCursor: null, truncated: true, @@ -1026,7 +1037,7 @@ describe('a list that is not the whole answer', () => { }) /** A flag raised on a later page is the same fact, and used to be lost. */ - it('carries a truncation stated on a page after the first', async () => { + it('tells a person about a truncation stated on a page after the first', async () => { mockRequest.mockReset() mockRequest .mockResolvedValueOnce({ data: [{ id: 'a' }], nextCursor: 'c1', toolNamesTruncated: false }) @@ -1040,9 +1051,11 @@ describe('a list that is not the whole answer', () => { return true }) + output.format = 'table' try { await program().parseAsync(['node', 'sim', 'workflow-mcp-servers', 'list', '--limit', '0']) } finally { + output.format = 'json' written.mockRestore() } diff --git a/packages/sim-cli/src/runtime/build.ts b/packages/sim-cli/src/runtime/build.ts index 19f96a6a38c..d359a137b41 100644 --- a/packages/sim-cli/src/runtime/build.ts +++ b/packages/sim-cli/src/runtime/build.ts @@ -7,7 +7,7 @@ import { deriveCommandPath } from './derive' import { executeOperation } from './execute' import { retypeApiError } from './naming' import { addOperationOptions, JSON_PLACEHOLDER } from './options' -import { warnRenamedCommand } from './renamed' +import { warnRenamedCommand, writeRenameWarnings } from './renamed' import { flagNameFor, flagSpecFor, @@ -524,9 +524,14 @@ function configureOperation( // The last frame that still knows which operation ran, and so the only one // that can say `--include-job-runs` where the server said `includeJobRuns`. command.action((...invocation: unknown[]) => - executeOperation(operation, spec, operationSpec, invocation).catch((error) => { - throw retypeApiError(error, operation, spec, operationSpec) - }) + // A rename warning no result took (a failure, or a path that prints none) still reaches stderr. + executeOperation(operation, spec, operationSpec, invocation).then( + () => writeRenameWarnings(command), + (error) => { + writeRenameWarnings(command) + throw retypeApiError(error, operation, spec, operationSpec) + } + ) ) return command } @@ -562,7 +567,7 @@ function addRenamedCommand( } const leaf = configureOperation(new Command(rest[rest.length - 1]), operation, spec) - leaf.hook('preAction', () => warnRenamedCommand(from, to)) + leaf.hook('preAction', () => warnRenamedCommand(leaf, from, to)) addSubcommand(parent, leaf, { hidden: true }) } diff --git a/packages/sim-cli/src/runtime/execute.ts b/packages/sim-cli/src/runtime/execute.ts index 55f06c43092..bbfda844072 100644 --- a/packages/sim-cli/src/runtime/execute.ts +++ b/packages/sim-cli/src/runtime/execute.ts @@ -15,7 +15,7 @@ import { safeOneLine } from '../output/render' import { connect } from './called-operations' import { camel } from './derive' import { DEFAULT_PAGE_SIZE, defaultListLimit } from './options' -import { warnRenamedFlag } from './renamed' +import { deliveredRenameWarnings, owedRenameWarnings, warnRenamedFlag } from './renamed' import { type BuiltRequest, buildRequest, @@ -375,6 +375,7 @@ function assertSelectorIsUsable(operation: V2OperationName, flags: Record @@ -390,7 +391,7 @@ function foldOtherSpellings( 0 ) } - if (renamed) warnRenamedFlag(name, current) + if (renamed) warnRenamedFlag(host, name, current) flags[camel(current)] = supplied } } @@ -459,7 +460,7 @@ export async function executeOperation( requestFlags[camel(name)] = trailingValues } - foldOtherSpellings(operation, commandSpec, requestFlags) + foldOtherSpellings(host, operation, commandSpec, requestFlags) assertCapIsUsable(operation, requestFlags) assertSelectorIsUsable(operation, requestFlags) @@ -588,7 +589,10 @@ export async function executeOperation( } finally { progress.finish() } - renderPage(profile.output, { data: rows, nextCursor: cursor }, commandSpec, envelope) + renderPage(profile.output, { data: rows, nextCursor: cursor }, commandSpec, envelope, { + warnings: owedRenameWarnings(host), + warningsDelivered: () => deliveredRenameWarnings(host), + }) return } @@ -669,7 +673,10 @@ export async function executeOperation( report )) payload = report - renderResult(operation, profile.output, payload, commandSpec) + renderResult(operation, profile.output, payload, commandSpec, { + warnings: owedRenameWarnings(host), + warningsDelivered: () => deliveredRenameWarnings(host), + }) assertWorkspaceOperationOutcome(report, timedOut) return } @@ -681,6 +688,8 @@ export async function executeOperation( { expandedTrace: requestFlags.trace === true, note: resultNote(operation, payload, request), + warnings: owedRenameWarnings(host), + warningsDelivered: () => deliveredRenameWarnings(host), }, // The envelope, not just the payload: a list that does not paginate states // its own truncation there, and unwrapping `data` discarded it. diff --git a/packages/sim-cli/src/runtime/renamed.ts b/packages/sim-cli/src/runtime/renamed.ts index 1059d24842f..5b5c09b9f7b 100644 --- a/packages/sim-cli/src/runtime/renamed.ts +++ b/packages/sim-cli/src/runtime/renamed.ts @@ -1,3 +1,4 @@ +import type { Command } from 'commander' import { writeStderr } from '#sim-cli/output/io' /** @@ -6,36 +7,50 @@ import { writeStderr } from '#sim-cli/output/io' * A rename is not an alias. {@link CommandSpec.aliases} are ergonomic shorthands * — `ls`, `mv` — that the CLI wants people to use, so they appear in help. A * renamed spelling is kept only so a script written against the old name keeps - * working: it stays out of help and out of the generated docs, and says once, - * on stderr, what to write instead. + * working: it stays out of help and out of the generated docs, and says what to + * write instead. * - * Warnings go to stderr rather than stdout because the old name is most likely - * to survive inside exactly the kind of script that pipes stdout into `jq`, and - * a deprecation notice in the middle of a JSON document is a worse bug than the - * one it reports. + * The old name is most likely to survive inside exactly the kind of script that + * reads the result as JSON, often with stderr merged in (`2>&1`), so the warning + * is owed to the invocation and delivered with its result: inside a JSON or YAML + * result as its `note`, and on stderr for a person (`renderResult`). A command + * that ends without a result to carry it says it on stderr ({@link writeRenameWarnings}). */ -/** Reported spellings, so a loop over many rows warns once rather than per row. */ -const warned = new Set() +/** The warnings each invoked command owes, until its result or its failure delivers them. */ +const OWED = new WeakMap() -function warn(kind: string, from: string, to: string): void { - const key = `${kind}:${from}` - if (warned.has(key)) return - warned.add(key) - writeStderr(`warning: ${kind} "${from}" has been renamed to "${to}". The old name still works.\n`) +function owe(command: Command, kind: string, from: string, to: string): void { + const warnings = OWED.get(command) ?? [] + warnings.push(`${kind} "${from}" has been renamed to "${to}". The old name still works.`) + OWED.set(command, warnings) } -/** Announces a command path that has been renamed, naming its current spelling. */ -export function warnRenamedCommand(from: string, to: string): void { - warn('command', `sim ${from}`, `sim ${to}`) +/** Owes `command` the warning that it was invoked by a path it has been renamed from. */ +export function warnRenamedCommand(command: Command, from: string, to: string): void { + owe(command, 'command', `sim ${from}`, `sim ${to}`) } -/** Announces a flag that has been renamed, naming its current spelling. */ -export function warnRenamedFlag(from: string, to: string): void { - warn('flag', `--${from}`, `--${to}`) +/** Owes `command` the warning that it was passed a flag by a name it has been renamed from. */ +export function warnRenamedFlag(command: Command, from: string, to: string): void { + owe(command, 'flag', `--${from}`, `--${to}`) } -/** Test seam: renames warn once per process, and each test needs a clean slate. */ -export function resetRenameWarnings(): void { - warned.clear() +/** The rename warnings `command` owes, for its result to carry. */ +export function owedRenameWarnings(command: Command): readonly string[] { + return OWED.get(command) ?? [] +} + +/** + * Settles what `command` owed once its warnings have reached the reader: a render that throws + * first leaves them owed, for {@link writeRenameWarnings}. + */ +export function deliveredRenameWarnings(command: Command): void { + OWED.delete(command) +} + +/** Writes on stderr the rename warnings no printed result delivered. */ +export function writeRenameWarnings(command: Command): void { + for (const warning of owedRenameWarnings(command)) writeStderr(`warning: ${warning}\n`) + OWED.delete(command) } diff --git a/packages/sim-cli/src/runtime/result-notices.test.ts b/packages/sim-cli/src/runtime/result-notices.test.ts new file mode 100644 index 00000000000..3d923e039b8 --- /dev/null +++ b/packages/sim-cli/src/runtime/result-notices.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest' +import { runEmbeddedCli } from '../embed' + +/** + * What the CLI adds to a successful result, read the way an agent reads it: `--output json` with + * stderr merged into the capture (`2>&1`), which has to stay one parseable document. An embedded + * run always answers in JSON; a person's table is covered in `result.test.ts`. + */ + +const identity = { endpoint: 'https://sim.test', apiKey: 'fixture', workspaceId: 'workspace' } + +function run(argv: string[], body: unknown) { + return runEmbeddedCli(argv, { ...identity, transport: async () => Response.json(body) }) +} + +/** stdout and stderr as one capture, the way `2>&1` hands them to a parser. */ +function merged(result: { stdout: string; stderr: string }): unknown { + return JSON.parse(result.stdout + result.stderr) +} + +describe('a successful result the CLI states something about', () => { + it.each([ + { + what: 'a single result the server clipped', + argv: ['files', 'read', 'file_1'], + body: { data: { fileId: 'file_1', name: 'a.txt', text: 'abc', truncated: true } }, + shown: { fileId: 'file_1', name: 'a.txt', text: 'abc', truncated: true }, + }, + { + what: 'a page whose envelope scopes the whole list', + argv: ['billing', 'logs'], + body: { data: [{ id: 'log_1', creditCost: 2 }], nextCursor: null, scope: 'user' }, + }, + { + what: 'a page the server clipped', + argv: ['workflow-mcp-servers', 'list'], + body: { data: [{ id: 'mcp_1', toolCount: 40 }], nextCursor: null, toolNamesTruncated: true }, + }, + ])( + 'keeps $what one JSON document under 2>&1, carrying the fact', + async ({ argv, body, shown }) => { + const result = await run([...argv, '--output', 'json'], body) + expect(result.exitCode).toBe(0) + expect(merged(result)).toEqual(shown ?? body) + } + ) +}) + +describe('a command reached by its renamed spellings', () => { + const argv = ['tables', 'rows', 'find', 'tbl_1', '--q', 'needle'] + const answer = { data: { matches: [], truncated: false } } + const COMMAND_RENAMED = + 'command "sim tables rows find" has been renamed to "sim tables rows search". The old name still works.' + const FLAG_RENAMED = 'flag "--q" has been renamed to "--query". The old name still works.' + + it('carries both warnings in the JSON result as one note, so 2>&1 still parses', async () => { + const result = await run([...argv, '--output', 'json'], answer) + expect(result.exitCode).toBe(0) + expect(merged(result)).toEqual({ + matches: [], + truncated: false, + note: `${COMMAND_RENAMED}\n${FLAG_RENAMED}`, + }) + }) + + it('still warns on stderr when a successful answer cannot be printed', async () => { + const result = await run([...argv, '--output', 'json'], { data: { matches: 'not a list' } }) + expect(result.exitCode).not.toBe(0) + expect(result.stderr).toContain(`warning: ${COMMAND_RENAMED}\nwarning: ${FLAG_RENAMED}\n`) + }) + + it('still warns on stderr when the command fails before it has a result', async () => { + const result = await runEmbeddedCli([...argv, '--output', 'json'], { + ...identity, + transport: async () => + Response.json({ error: { code: 'NOT_FOUND', message: 'No such table' } }, { status: 404 }), + }) + expect(result.exitCode).not.toBe(0) + expect(result.stderr).toContain(`warning: ${COMMAND_RENAMED}\nwarning: ${FLAG_RENAMED}\n`) + }) +}) diff --git a/packages/sim-cli/src/runtime/result.test.ts b/packages/sim-cli/src/runtime/result.test.ts index e87ef3e1064..8807fc08f81 100644 --- a/packages/sim-cli/src/runtime/result.test.ts +++ b/packages/sim-cli/src/runtime/result.test.ts @@ -14,6 +14,12 @@ beforeEach(() => { }) }) +/** What a render wrote on stderr, where a person reads the CLI's notices. */ +function captureStderr(): () => string { + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + return () => stderr.mock.calls.map(([chunk]) => String(chunk)).join('') +} + /** The table arrives as one string; its first line is the header. */ function tableLines(): string[] { return logged.join('\n').split('\n') @@ -212,12 +218,6 @@ describe('paginated JSON output', () => { }) describe('a truncation the response states inside its payload', () => { - /** Every note goes to stderr; stdout is asserted to be untouched by it. */ - function captureStderr(): () => string { - const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) - return () => stderr.mock.calls.map(([chunk]) => String(chunk)).join('') - } - it.each(['readFileText', 'readFileVersionText'] as const)( 'preserves complete %s content in table output', (operation) => { @@ -237,14 +237,61 @@ describe('a truncation the response states inside its payload', () => { } ) - it('reports a clipped file body, which the envelope says nothing about', () => { + it('reports a clipped file body to a person, which the envelope says nothing about', () => { const read = captureStderr() const payload = { fileId: 'wf_probe', name: 'a.txt', text: 'abc', truncated: true } - renderResult('readFileText', 'json', payload, {}, {}, { data: payload }) + renderResult('readFileText', 'table', payload, {}, {}, { data: payload }) - expect(read()).toContain('the server clipped this result') - expect(JSON.parse(logged.join('\n'))).toEqual(payload) + expect(read()).toBe('truncated: the server clipped this result, so the answer is incomplete\n') + }) + + it('carries a clip stated on the envelope inside a JSON record, and says nothing on stderr', () => { + const read = captureStderr() + const payload = { id: 'src_1', tables: [] } + + renderResult('getSourceResources', 'json', payload, {}, {}, { data: payload, truncated: true }) + + expect(JSON.parse(logged.join('\n'))).toEqual({ ...payload, truncated: true }) + expect(read()).toBe('') + }) +}) + +describe('notes the CLI adds, read by a person', () => { + it('states a page envelope fact above the rows and keeps it out of them', () => { + const read = captureStderr() + const page = { data: [{ id: 'log_1' }], nextCursor: null } + + renderPage('text', page, CLI_CONTRACT.listBillingLogs ?? {}, { ...page, scope: 'user' }) + + expect(read()).toBe('scope: user\n') + expect(logged).toHaveLength(1) + expect(logged[0].split('\t')).not.toContain('user') + }) + + it('warns about a renamed spelling before the record and notes the result after it', () => { + const order: string[] = [] + vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + order.push(`stderr ${String(chunk)}`) + return true + }) + vi.spyOn(console, 'log').mockImplementation((line: string) => { + order.push(`stdout ${line}`) + }) + + renderResult( + 'getBlock', + 'text', + { id: 'table_v2' }, + {}, + { warnings: ['flag "--q" has been renamed to "--query".'], note: 'read as table_v2.' } + ) + + expect(order).toEqual([ + 'stderr warning: flag "--q" has been renamed to "--query".\n', + 'stdout id\ttable_v2', + 'stderr note: read as table_v2.\n', + ]) }) }) diff --git a/packages/sim-cli/src/runtime/result.ts b/packages/sim-cli/src/runtime/result.ts index 6e212becaf0..dc84eb3417e 100644 --- a/packages/sim-cli/src/runtime/result.ts +++ b/packages/sim-cli/src/runtime/result.ts @@ -1,4 +1,4 @@ -import { isRecordLike, omit } from '@sim/utils/object' +import { isRecordLike, omit, toRecord, toRecordOrNull } from '@sim/utils/object' import { writeStderr } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' import { truncationMetadata } from '#sim-cli/output/truncation' @@ -32,6 +32,93 @@ interface RenderResultOptions { expandedTrace?: boolean /** One line of context the CLI adds to a successful result (see {@link renderResult}). */ note?: string + /** What the invocation itself deserves a warning about, such as a renamed flag. */ + warnings?: readonly string[] + /** + * Called once `warnings` have reached the reader: written on stderr, or printed inside the + * result. A render that throws before then leaves them for the caller to write. + */ + warningsDelivered?: () => void +} + +/** + * A fact the CLI states about a result beyond the API's data, placed by {@link placeNotices}. + * + * A JSON or YAML result carries it as `field`, so `--output json 2>&1` stays one document; a + * person reads the lines `before` and `after` on stderr, around the printed result. + */ +interface ResultNotice { + field: string + value: unknown + before?: readonly string[] + after?: readonly string[] +} + +/** + * Places each notice: in a machine format, inside the result as its `field` (a result that + * already holds that value carries it as it is); otherwise, and wherever the field cannot be + * added — a display format, a document (its value is the deliverable), a result that is not a + * record, or one whose own `field` says something else — as its lines on stderr. + */ +function placeNotices( + format: OutputFormat, + result: unknown, + notices: readonly ResultNotice[], + document = false +): { result: unknown; before: string[]; after: string[]; carried: Set } { + const record = isMachineFormat(format) ? toRecordOrNull(result) : null + let carried: Record | null = null + const before: string[] = [] + const after: string[] = [] + const fields = new Set() + for (const notice of notices) { + const held: Record | null = carried ?? record + if (held && notice.field in held && held[notice.field] === notice.value) { + fields.add(notice.field) + continue + } + if (held && !document && !(notice.field in held)) { + carried = { ...held, [notice.field]: notice.value } + fields.add(notice.field) + continue + } + before.push(...(notice.before ?? [])) + after.push(...(notice.after ?? [])) + } + return { result: carried ?? result, before, after, carried: fields } +} + +/** + * Writes the lines placed before a result, and reports the invocation's warnings delivered once + * they are on stderr; carried in the result, they are delivered when it has printed. + */ +function writeLeadingNotices( + placed: ReturnType, + options: RenderResultOptions +): void { + writeNoticeLines(placed.before) + if (!placed.carried.has('note')) options.warningsDelivered?.() +} + +function writeNoticeLines(lines: readonly string[]): void { + for (const line of lines) writeStderr(`${line}\n`) +} + +/** + * The CLI's own notes on a result as one `note`: each warning about the invocation, then the + * result's note, one per line. + */ +function noteNotice({ warnings = [], note }: RenderResultOptions): ResultNotice[] { + const notes = note === undefined ? warnings : [...warnings, note] + if (notes.length === 0) return [] + return [ + { + field: 'note', + value: notes.join('\n'), + before: warnings.map((warning) => `warning: ${warning}`), + after: note === undefined ? [] : [styles().dim(`note: ${note}`)], + }, + ] } function countTraceSpans(value: unknown): number { @@ -336,45 +423,48 @@ function unwrapResource(data: unknown): unknown { return value && typeof value === 'object' && !Array.isArray(value) ? value : data } +/** + * Renders the rows a paginated operation walked, with what its envelope states about them + * ({@link placeNotices}): a JSON or YAML page carries its truncation flags, its + * {@link CommandSpec.pageNote} and the invocation's warnings beside `data` and `nextCursor`. + */ export function renderPage( format: OutputFormat, page: { data: unknown[]; nextCursor: string | null }, spec: CommandSpec, - envelope?: unknown + envelope?: unknown, + options: Pick = {} ): void { - writePageNote(spec, envelope) - writeEnvelopeTruncation(envelope) + const placed = placeNotices(format, page, [ + ...noteNotice(options), + ...pageNotice(spec, envelope), + ...truncationNotices(envelope), + ]) + writeLeadingNotices(placed, options) printList( format, page.data, spec.columns ? columnsFrom(spec.columns) : inferColumns(page.data, spec.expand), - { ...page, ...truncationMetadata(envelope) } + placed.result ) + options.warningsDelivered?.() } /** - * States a page-envelope fact once, above the rows, on stderr. - * - * `--output text` is positional and tab-separated, so this note cannot occupy - * a row. JSON and YAML expose the rows and continuation cursor; other envelope - * facts such as billing scope are reported here for every format. + * A page-envelope fact, stated once above the rows for a person: `--output text` is positional + * and tab-separated, so it cannot occupy a row. */ -function writePageNote(spec: CommandSpec, envelope: unknown): void { - if (!spec.pageNote) return - const value = at(envelope, spec.pageNote.path) - if (value === undefined || value === null) return - writeStderr(styles().dim(`${spec.pageNote.label}: ${String(value)}\n`)) -} - -/** The flags one object raised, in the spelling the wire used. */ -function truncationFlags(container: unknown): string[] { - return Object.entries(truncationMetadata(container)) - .filter(([, value]) => value) - .map(([key]) => key) +function pageNotice(spec: CommandSpec, envelope: unknown): ResultNotice[] { + if (!spec.pageNote) return [] + const { field, label } = spec.pageNote + const value = toRecord(envelope)[field] + if (value === undefined || value === null) return [] + return [{ field, value, before: [styles().dim(`${label}: ${String(value)}`)] }] } /** - * The flags a whole response raised, on its envelope or inside its payload. + * The truncation flags a whole response states, on its envelope or inside its payload, raised or + * not: a machine format carries each, and a person reads the raised ones. * * Two responses state their clip one level down: `files text`, whose file body * stops at `maxBytes`, and `tables rows search`, whose match list the server @@ -386,8 +476,17 @@ function truncationFlags(container: unknown): string[] { * the rows, and a row's keys are the user's rather than the API's, so a shape * match there is a guess about a name somebody else chose. */ -function responseTruncationFlags(envelope: unknown): string[] { - return [...truncationFlags(envelope), ...truncationFlags(at(envelope, 'data'))] +function truncationNotices(envelope: unknown): ResultNotice[] { + return [ + ...Object.entries(truncationMetadata(envelope)), + ...Object.entries(truncationMetadata(at(envelope, 'data'))), + ].map(([flag, value]) => ({ field: flag, value, before: value ? [truncationLine(flag)] : [] })) +} + +function truncationLine(flag: string): string { + return styles().dim( + `${spellOut(flag)}: the server clipped ${clippedSubject(flag)}, so the answer is incomplete` + ) } /** @@ -433,23 +532,6 @@ function clippedSubject(flag: string): string { return subject ? `the ${spellOut(subject)} it returned` : 'this result' } -/** - * States a server-side clip once, on stderr, in every format. - * - * The API answers a clipped inventory with a flag on the envelope. It is - * separate from pagination: a null nextCursor does not establish whether the - * server clipped fields within the returned rows. - */ -function writeEnvelopeTruncation(envelope: unknown): void { - for (const flag of responseTruncationFlags(envelope)) { - writeStderr( - styles().dim( - `${spellOut(flag)}: the server clipped ${clippedSubject(flag)}, so the answer is incomplete\n` - ) - ) - } -} - /** Whether `format` prints one parseable document rather than lines for a person. */ function isMachineFormat(format: OutputFormat): boolean { return format === 'json' || format === 'yaml' @@ -465,9 +547,9 @@ function withNextText(data: unknown): unknown { /** * Renders one non-paginated operation result according to its CLI contract. * - * `options.note` joins a machine-format result as `note`, so `--output json 2>&1` stays one - * document; a display format, a document, a non-record payload, or one with its own `note` gets - * it on stderr after the record. + * What the CLI states beside the API's data is placed by {@link placeNotices}: a truncation the + * response states (on the envelope `execute` unwraps, or in the payload; a null nextCursor says + * nothing about a clip), and `options.warnings` and `options.note` as one `note`. */ export function renderResult( operation: V2OperationName, @@ -477,20 +559,16 @@ export function renderResult( options: RenderResultOptions = {}, envelope?: unknown ): void { - // Before any branch: the flag lives on the envelope `execute` unwraps one - // line before rendering, and states a fact about the payload below it. - writeEnvelopeTruncation(envelope) - const { note } = options - const noted = - note !== undefined && - isMachineFormat(format) && - !spec.document && - isRecordLike(raw) && - !('note' in raw) - ? { ...raw, note } - : null - printResult(operation, format, noted ?? raw, spec, options) - if (note !== undefined && !noted) writeStderr(styles().dim(`note: ${note}\n`)) + const placed = placeNotices( + format, + raw, + [...noteNotice(options), ...truncationNotices(envelope)], + spec.document + ) + writeLeadingNotices(placed, options) + printResult(operation, format, placed.result, spec, options) + writeNoticeLines(placed.after) + options.warningsDelivered?.() } function printResult(