From 55ccf863d4a80b1dae63ed34569ddb1d8c70ae4e Mon Sep 17 00:00:00 2001 From: root Date: Fri, 4 Dec 2026 05:37:47 +0000 Subject: [PATCH] io.sh: print API errors in the CLI's error shape when jq is present (#29) call() printed the API's error body as it came, so a WordPress error such as {code, message, data: {status}} reached stderr in that shape while io.sh's own errors and the CLI's used {ok: false, error, message}. With jq, call() now builds the same object as the CLI's api(): error from .error or .code (http_ for a body that is not JSON), message, status, and the extra fields the CLI copies. Without jq the body is still passed through unchanged, as documented. Test: test/api-error-shape.test.mjs compares io.sh and the CLI on eight kinds of API error from the REST stub. --- CHANGELOG.md | 6 +++ README.md | 3 +- io.sh | 20 +++++++- test/api-error-shape.test.mjs | 90 +++++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 test/api-error-shape.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 63a97e8..d8a39f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to the `indianopinion` npm package. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Fixed + +- `io.sh` with jq prints an error from the API in the CLI's shape, `{"ok":false,"error":...,"message":...,"status":...}` plus `field`, `allowed`, `attempts_left`, `suggestion`, `options`, `scope` and `retry_after` when the API sends them, instead of the API's own body (WordPress's `{code, message, data}`). A body that is not JSON gives `http_`, as in the CLI. Without jq the body is still passed through unchanged (#29). + ## [0.2.2] - 2026-10-22 ### Fixed diff --git a/README.md b/README.md index 8d01474..f429587 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,8 @@ mkdir -p ~/bin && curl -fsSL https://indianopinion.org/agents/cli/io.sh -o ~/bin ~/bin/io briefs --q monsoon --limit 3 # or add ~/bin to PATH and run io ``` -With jq installed, `io.sh` prints the same JSON as the CLI; without jq it prints the API's JSON +With jq installed, `io.sh` prints the same JSON as the CLI, errors from the API included +(`{"ok":false,"error":...,"message":...,"status":...}` on stderr); without jq it prints the API's JSON unchanged, and the few flags that need reshaping (`digest --limit`, `breaking recent --limit` or `--would-send`, `brief --include`) say they need jq. A flag a command does not take is a usage error (exit 2) in both. diff --git a/io.sh b/io.sh index ca1dc80..74eddc6 100644 --- a/io.sh +++ b/io.sh @@ -7,7 +7,8 @@ # ~/bin/io login verify --email you@yourdomain.example --code 123456 # ~/bin/io digest | jq '.stories[] | {title, url}' # Output: with jq installed, the same JSON as the indianopinion CLI (briefs as -# {ok, count, items, next_cursor} with post_id, summary and so on); without jq, +# {ok, count, items, next_cursor} with post_id, summary and so on, and API errors as +# {ok: false, error, message, status} on stderr); without jq, # the API's JSON unchanged. Flags that need reshaping (digest --limit, breaking # recent --limit or --would-send, brief --include) need jq and say so. # A flag a command does not take is a usage error (exit 2), never ignored. @@ -79,9 +80,24 @@ call() { out=$(curl "${args[@]}" "$API$path" 2>/dev/null) || die 7 network "could not reach $API" status=${out##*$'\n'}; out=${out%$'\n'*} code=$(exit_for "$status" "$out") - if [ "$code" != 0 ]; then printf '%s\n' "$out" >&2; exit "$code"; fi + if [ "$code" != 0 ]; then + # With jq, an error from the API gets the CLI's shape (#29); without jq it stays as sent. + if [ "$HAVE_JQ" = 1 ]; then printf '%s' "$out" | jq -cRs --arg s "$status" "$JQ_APIERR" >&2 || printf '%s\n' "$out" >&2 + else printf '%s\n' "$out" >&2; fi + exit "$code" + fi OUT=$out } +# The CLI's error object for an API error body (WordPress {code, message, data} or the agent API's +# {ok: false, error, message, ...}), as bin/indianopinion.mjs api() builds it. A body that is not +# JSON gives http_. Retry-After is taken from the body only; io.sh does not read headers. +JQ_APIERR='($s | tonumber) as $st | ((try fromjson catch null) | if type == "object" then . else {} end) as $d + | ($d.error // $d.code // "http_\($st)") as $c + | {ok: false, error: $c, + message: (if $c == "rest_no_route" then "The Indian Opinion agent API is not answering yet (rest_no_route); try again later." else ($d.message // "HTTP \($st)") end), + status: $st} + + ($d | with_entries(select(.key | IN("field", "allowed", "attempts_left", "suggestion", "options", "scope")))) + + (if $d.retry_after != null then {retry_after: ($d.retry_after | tonumber? // $d.retry_after)} else {} end)' emit() { # print JSON (pretty on a terminal when jq is there) if [ -t 1 ] && [ "$HAVE_JQ" = 1 ]; then printf '%s\n' "$1" | jq .; else printf '%s\n' "$1"; fi diff --git a/test/api-error-shape.test.mjs b/test/api-error-shape.test.mjs new file mode 100644 index 0000000..e6051a4 --- /dev/null +++ b/test/api-error-shape.test.mjs @@ -0,0 +1,90 @@ +// #29: with jq, io.sh prints an error that came from the API in the CLI's shape, +// {ok: false, error, message, status, ...}, instead of the API's own body. +// The error bodies are the REST stub's (test/stub-rest.mjs): WordPress's {code, message, +// data: {status}} for /brief/{id} and rest_no_route, the agent API's {ok: false, error, +// message, ...} elsewhere, and an HTML 404 for a path outside the API. No network. + +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { startStub, GOOD_TOKEN, EMAIL } from './stub-rest.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.join(HERE, '..'); +const BIN = path.join(ROOT, 'bin', 'indianopinion.mjs'); +const IOSH = path.join(ROOT, 'io.sh'); +const HAVE_CURL = spawnSync('bash', ['-c', 'command -v curl']).status === 0; +const HAVE_JQ = spawnSync('bash', ['-c', 'command -v jq']).status === 0; +let stub; let dark; let home; + +function run(args, { env = {}, bin = 'node' } = {}) { + const [cmd, argv] = bin === 'node' ? [process.execPath, [BIN, ...args]] : ['bash', [IOSH, ...args]]; + return new Promise((resolve) => { + const child = spawn(cmd, argv, { env: { PATH: process.env.PATH, HOME: home, XDG_CONFIG_HOME: path.join(home, '.config'), IO_API: stub.api, IO_TOKEN: GOOD_TOKEN, ...env } }); + let out = ''; let errs = ''; + child.stdout.on('data', (d) => { out += d; }); + child.stderr.on('data', (d) => { errs += d; }); + child.stdin.end(); + child.on('close', (code) => { + let errJson = null; + try { errJson = JSON.parse(errs.trim().split('\n').pop()); } catch { /* text */ } + resolve({ code, out, err: errs, errJson }); + }); + }); +} + +before(async () => { + stub = await startStub(); + dark = await startStub({ agentLive: false }); + home = fs.mkdtempSync(path.join(os.tmpdir(), 'io-errshape-')); +}); +after(async () => { await stub.close(); await dark.close(); }); + +test('#29: io.sh with jq prints the CLI error shape for a WordPress-style 404', { skip: !HAVE_CURL || !HAVE_JQ }, async () => { + const sh = await run(['brief', '99999999999'], { bin: 'bash' }); + assert.equal(sh.code, 4); + assert.equal(sh.out, ''); + assert.deepEqual(Object.keys(sh.errJson), ['ok', 'error', 'message', 'status']); + assert.equal(sh.errJson.ok, false); + assert.equal(sh.errJson.message, 'No such article.'); + assert.equal(sh.errJson.status, 404); + const node = await run(['brief', '99999999999']); + assert.equal(node.code, 4); + assert.deepEqual(sh.errJson, node.errJson); +}); + +test('#29: io.sh and the CLI print the same error object for every kind of API error', { skip: !HAVE_CURL || !HAVE_JQ }, async () => { + const cases = [ + { name: 'agent API 400 with attempts_left', args: ['login', 'verify', '--email', EMAIL, '--code', '000000'], exit: 6 }, + { name: 'agent API 400 with field', args: ['login', 'start', '--email', 'not-an-address@x'], exit: 6 }, + { name: '429 with retry_after and scope', args: ['login', 'start', '--email', 'slow@agents.example.org'], exit: 5 }, + { name: '409 ambiguous with options', args: ['topics', 'follow', 'metro'], exit: 8 }, + { name: '401 refused token', args: ['me'], env: { IO_TOKEN: 'ioa_000000000000_revokedrevokedrevoked' }, exit: 3 }, + { name: 'agent API 404', args: ['digest', '--date', '1999-01-01'], exit: 4 }, + { name: 'rest_no_route before the agent API is deployed', args: ['me'], env: { IO_API: '' }, dark: true, exit: 4 }, + { name: 'a body that is not JSON', args: ['brief', '1'], env: { IO_API: '' }, html: true, exit: 4 }, + ]; + for (const c of cases) { + const env = { ...(c.env || {}) }; + if (c.dark) env.IO_API = dark.api; + if (c.html) env.IO_API = `${stub.url}/not-the-api`; + const node = await run(c.args, { env }); + const sh = await run(c.args, { env, bin: 'bash' }); + assert.equal(node.code, c.exit, `${c.name}: CLI exit ${node.code} ${node.err}`); + assert.equal(sh.code, c.exit, `${c.name}: io.sh exit ${sh.code} ${sh.err}`); + assert.equal(sh.errJson && sh.errJson.ok, false, `${c.name}: io.sh stderr ${sh.err}`); + assert.deepEqual(sh.errJson, node.errJson, `${c.name}`); + } +}); + +test('#29: without jq, io.sh still passes the API body through unchanged (as documented)', { skip: !HAVE_CURL }, async () => { + const sh = await run(['brief', '99999999999'], { bin: 'bash', env: { IO_SH_NO_JQ: '1' } }); + assert.equal(sh.code, 4); + assert.equal(sh.errJson.ok, undefined); + assert.equal(sh.errJson.message, 'No such article.'); + assert.deepEqual(sh.errJson.data, { status: 404 }); +});