From c538c6e19f38dec982adb6854bb8391b2b204d39 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Fri, 20 Nov 2026 06:54:55 +0800 Subject: [PATCH] feat(cli): coloured, live output for wasit test at a terminal At a terminal, `wasit test` now shows its checks in Wasit's own look: a header, two blocks (challenge, payment), and one line per check with a mark and a badge that agree (PASS on green, FAIL on red, SKIP on yellow, ERROR on magenta) and its duration. A spinner line says what the check in flight is doing, and the verdict, the counts and the run's duration come at the end. On a network that is not a test network, the payment block says the checks are refused, never that funds move. A skip that gives the same reason as the skip above it does not repeat it. The colours are the site's and the dashboard's, exact on a terminal with 24-bit colour, and a badge's ink is given as exact black or white, since a terminal that draws bold text in bright colours turns bold black into grey. Every line is cut or wrapped to the terminal's width, so the spinner line never wraps and is always rewritten in place. `wasit mpp-charge` and `wasit mpp-channel` mark their results the same way. Colour is a layer over the same text: every line is sanitised and its secrets redacted before it is styled, so the only escape sequences on screen are Wasit's own. A pipe, CI, --json and NO_COLOR get the plain output exactly as before (compared over every kind of result), and FORCE_COLOR=1 colours a pipe without moving the cursor. --- packages/cli/src/index.ts | 108 ++++++- packages/cli/src/live.ts | 302 +++++++++++++++++++ packages/cli/src/output.ts | 80 +++-- packages/cli/src/style.ts | 222 ++++++++++++++ packages/cli/test/unit/live-output.test.ts | 329 +++++++++++++++++++++ 5 files changed, 1015 insertions(+), 26 deletions(-) create mode 100644 packages/cli/src/live.ts create mode 100644 packages/cli/src/style.ts create mode 100644 packages/cli/test/unit/live-output.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index ded092f..c0edfff 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -16,12 +16,18 @@ import { type ServeMode, } from "./serve.js"; import { executeCiReport } from "./ci-report-command.js"; -import { note, report } from "./output.js"; +import { exitCodeFor, note, report, verdictNotes } from "./output.js"; +import { LiveReport } from "./live.js"; +import { colorDepth, colorEnabled, lineWidth, liveEnabled, styler } from "./style.js"; import { executeRun } from "./run.js"; import { CHECK_CATALOGUE, PROTOCOL_IDS, + X402_PAYMENT_CHECK_IDS, + catalogueEntry, deniedEnvValues, + endpointOutcome, + networkClass, paymentChainFor, runMppChannelSuite, runMppChargeSuite, @@ -226,7 +232,11 @@ is not set: X402-06 settles a payment; X402-07..10 send payments the target must refuse (a corrupted signature, a replay, an underpayment, an expired authorization). X402-11 needs a request the service must refuse, the reject case of a wasit.config.json endpoint: it runs in wasit run and is skipped here. See -docs/CHECKS.md for what each check ID verifies.`, +docs/CHECKS.md for what each check ID verifies. + +At a terminal the output is coloured and live: each check shows while it runs, +with its duration, and the run's duration comes at the end. A pipe, CI, --json +or NO_COLOR gives the plain text; FORCE_COLOR=1 colours a pipe.`, ) .action(async (opts) => { const jsonMode = opts.json === true; @@ -236,6 +246,12 @@ docs/CHECKS.md for what each check ID verifies.`, ...(opts.header ? { headers: opts.header as Record } : {}), }; + // A person at a terminal gets the coloured, live output; a pipe, CI, NO_COLOR + // and --json get the plain text below, unchanged. + if (!jsonMode && colorEnabled(process.stdout, process.env)) { + process.exit(await liveX402Test(opts, shape)); + } + const results = await runX402ReadChecks({ target: opts.target, ...shape }); // Each chain reads its own payer key: a Stellar secret is no use on EVM. const keyEnv = paymentChainFor(opts.network as string)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY"; @@ -569,8 +585,92 @@ that channel.`, }, }); - process.exit(report(results, jsonMode)); + process.exit(report(results, jsonMode, terminalStyle(jsonMode))); + }); + + +/** Colours for the MPP commands' text output, when a person is at the terminal. */ +function terminalStyle(jsonMode: boolean): { style: ReturnType; width: number } { + return { + style: styler(!jsonMode && colorEnabled(process.stdout, process.env), colorDepth(process.env)), + width: lineWidth(process.stdout), + }; +} + +/** + * `wasit test` for a person at a terminal: the same checks, notes and exit code + * as the plain output, drawn live (a RUNNING line with a timer while a check is + * in flight, each result as it arrives, the counts and the duration at the end). + */ +async function liveX402Test( + opts: Record, + shape: { method?: string; body?: string; headers?: Record }, +): Promise { + const secrets = deniedEnvValues(process.env); + const live = new LiveReport({ + stream: process.stdout, + live: liveEnabled(process.stdout, process.env), + depth: colorDepth(process.env), + clean: (text) => sanitizeText(text, { redact: secrets }), }); + const target = opts["target"] as string; + const network = opts["network"] as string; + live.header(CLI_VERSION, "x402 conformance", [ + ["target", `${target}${shape.method !== undefined ? ` ${shape.method.toUpperCase()}` : ""}`], + ["network", network], + ]); + + live.phase("challenge", [["no payment"]]); + live.running("X402-01..05", "Challenge checks"); + const results = await runX402ReadChecks({ target, ...shape, onResult: (result) => live.result(result) }); + live.gap(); + + const keyEnv = paymentChainFor(network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY"; + const payerKey = (opts["payerKey"] as string | undefined) ?? process.env[keyEnv]; + if (opts["readOnly"] === true) { + live.phase("payment", [["not run"]]); + live.note("--read-only set: the payment checks were not run."); + } else if (!payerKey) { + live.phase("payment", [["not run"]]); + live.note(`No payer key: set ${keyEnv} in .env or pass --payer-key. The payment checks were not run.`); + } else if (networkClass(network) !== "test") { + // Not a test network: the guard refuses the payment checks before anything + // is signed (the PREFLIGHT line says why), so no money moves. + live.phase("payment", [[network], ["not a test network: refused", "danger"]]); + } else { + live.phase("payment", [[network], ["testnet funds move", "warning"]]); + live.note( + `When the target offers a ${network} option, X402-06 settles a real payment and X402-07..10 send ` + + "payments it must refuse.", + ); + } + if (opts["readOnly"] !== true && payerKey) { + const order = X402_PAYMENT_CHECK_IDS; + const startAt = (index: number): void => { + const id = order[index]; + if (id !== undefined) live.running(id, catalogueEntry(id)?.name ?? id); + }; + startAt(0); + results.push( + ...(await runX402PaymentChecks({ + target, + network, + payerSecretKey: payerKey, + ...(opts["rpcUrl"] ? { rpcUrl: opts["rpcUrl"] as string } : {}), + ...shape, + onResult: (result) => { + live.result(result); + const index = order.indexOf(result.id); + if (index >= 0) startAt(index + 1); + }, + onProgress: (line) => live.progress(line), + })), + ); + } + + live.finish(results, endpointOutcome(results, "x402"), verdictNotes(results, "x402")); + return exitCodeFor(results, "x402"); +} program .command("mpp-charge") @@ -614,7 +714,7 @@ a real payment and moves testnet funds, because charge mode has no dry run.`, ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}), }); - process.exit(report(results, jsonMode)); + process.exit(report(results, jsonMode, terminalStyle(jsonMode))); }); registerWalletCommand(program); diff --git a/packages/cli/src/live.ts b/packages/cli/src/live.ts new file mode 100644 index 0000000..1d87d4e --- /dev/null +++ b/packages/cli/src/live.ts @@ -0,0 +1,302 @@ +/** + * The coloured, live text output of a check run (Najmi, 2026-11-19), in + * Wasit's own look: a header, the checks in two blocks (challenge, payment), + * one line per check with its mark (✓ pass, ✗ fail, ○ skip, ! error) and its + * duration flush right, a spinner line saying what the check in flight is doing, + * and the verdict, the counts and the run's duration at the end. + * + * It only arranges what the plain output says: the same checks, details, fixes + * and notes, in the same order. It is used only when colour is on + * (`colorEnabled`); `live` adds the spinner line, rewritten in place, on a real + * terminal. That line is cut to the terminal's width so it never wraps: a + * wrapped line cannot be rewritten in place. Every text passes through `clean` + * (the sanitiser, with the secrets redacted) before it is styled. + */ + +import { checkStatus, fixFor, summarize, type CheckResult, type EndpointOutcome } from "@wasit-dev/core"; + +import { + MARKS, + SPINNER_FRAMES, + SPINNER_MS, + duration, + lineWidth, + spread, + styler, + truncate, + visibleLength, + wrap, + type BadgeRole, + type ColorDepth, + type Role, + type Styler, + type StyleStream, +} from "./style.js"; + +export interface LiveStream extends StyleStream { + write(chunk: string): unknown; +} + +export interface LiveOptions { + readonly stream: LiveStream; + /** Rewrite the spinner line in place. Off: lines are only appended. */ + readonly live: boolean; + /** The sanitiser, with the run's secrets redacted. */ + readonly clean: (text: string) => string; + /** The terminal's colour depth (`colorDepth`): 24-bit gives the exact brand colours. Default 16. */ + readonly depth?: ColorDepth; + /** Shorthand for `depth: 24`. */ + readonly truecolor?: boolean; + readonly now?: () => number; + /** How often the spinner line is redrawn. */ + readonly tickMs?: number; +} + +/** What a check does while it runs, for its spinner line. */ +const DOING: Readonly> = { + "X402-01..05": "reading the challenge, no payment", + "X402-06": "paying once, then reading the transfer on chain", + "X402-07": "sending a payment with a corrupted signature", + "X402-08": "sending the same payment again", + "X402-09": "sending a validly signed payment for half the price", + "X402-10": "waiting for an authorization to expire, then sending it", + "X402-11": "sending a payment with the request the service must refuse", +}; + +/** The indent of a check's detail lines, under its ID. */ +const DETAIL = " "; +/** The indent of the lines after the first of a fix. */ +const FIX = " "; + +const STATUS_ROLE: Record = { PASS: "dim", FAIL: "danger", SKIP: "warning", ERROR: "error" }; + +/** + * The lines of one check: its line (mark, ID, name, duration, badge), then its + * detail, its fix and its docs. `withDetail` false leaves the detail out: a + * skip whose reason the skip just above it already gave. + */ +export function resultLines( + result: CheckResult, + style: Styler, + width: number, + clean: (text: string) => string, + ms?: number, + withDetail = true, +): string[] { + const status = checkStatus(result); + const marks = MARKS[status]; + const flag = result.destructive ? style.paint(" [destructive]", "warning") : ""; + const left = ` ${style.paint(marks.mark, "bold", marks.markRole)} ${style.paint(clean(result.id), "bold")} ${clean(result.name)}${flag}`; + const time = ms === undefined ? "" : style.paint(duration(ms), "muted"); + const right = [time, style.badge(marks.badge, marks.badgeRole)].filter((part) => part !== "").join(" "); + const lines = [spread(left, right, width)]; + if (withDetail) { + for (const line of wrap(clean(result.detail), width, DETAIL)) lines.push(style.paint(line, STATUS_ROLE[status] ?? "dim")); + } + const guidance = fixFor(result); + if (guidance !== undefined) { + const fix = wrap(clean(guidance.fix), width, FIX); + fix[0] = `${DETAIL}${style.paint("fix", "bold")} ${fix[0]?.trimStart() ?? ""}`; + lines.push(...fix); + if (guidance.docs !== undefined) lines.push(`${DETAIL}${style.paint(`docs ${clean(guidance.docs)}`, "muted")}`); + } + return lines; +} + +/** "10 passed", "1 failed", "1 could not run", "1 skipped": each count in its colour. */ +export function countsParts(results: readonly CheckResult[], style: Styler): string[] { + const counts = summarize([...results]); + const parts = [style.paint(`${counts.passed} passed`, "bold", "success")]; + if (counts.failed > 0) parts.push(style.paint(`${counts.failed} failed`, "bold", "danger")); + if (counts.errored > 0) parts.push(style.paint(`${counts.errored} could not run`, "bold", "error")); + if (counts.skipped > 0) parts.push(style.paint(`${counts.skipped} skipped`, "bold", "warning")); + return parts; +} + +/** "10 passed · 1 failed · 1 could not run · 1 skipped". */ +export function countsLine(results: readonly CheckResult[], style: Styler): string { + return countsParts(results, style).join(style.paint(" · ", "muted")); +} + +/** Parts joined by " · " into lines of at most `width` columns, each after `indent`. */ +function packParts(parts: readonly string[], width: number, indent: string, style: Styler): string[] { + const separator = style.paint(" · ", "muted"); + const lines: string[] = []; + let current = ""; + for (const part of parts) { + const next = current === "" ? `${indent}${part}` : `${current}${separator}${part}`; + if (current !== "" && visibleLength(next) > width) { + lines.push(current); + current = `${indent}${part}`; + } else { + current = next; + } + } + if (current !== "") lines.push(current); + return lines; +} + +const VERDICT: Record = { + conformant: { text: "CONFORMANT", role: "success" }, + "non-conformant": { text: "NOT CONFORMANT", role: "danger" }, + "no-verdict": { text: "NO VERDICT", role: "error" }, + unsupported: { text: "UNSUPPORTED", role: "warning" }, +}; + +export class LiveReport { + readonly #stream: LiveStream; + readonly #live: boolean; + readonly #clean: (text: string) => string; + readonly #now: () => number; + readonly #tickMs: number; + readonly #style: Styler; + readonly #startedAt: number; + #running: { readonly id: string; readonly name: string; readonly startedAt: number } | undefined; + #drawn = false; + #timer: ReturnType | undefined; + /** The reason of the skip printed just before, so the next skip with the same reason does not repeat it. */ + #lastSkip: string | undefined; + + public constructor(options: LiveOptions) { + this.#stream = options.stream; + this.#live = options.live; + this.#clean = options.clean; + this.#now = options.now ?? Date.now; + this.#tickMs = options.tickMs ?? SPINNER_MS; + this.#style = styler(true, options.depth ?? (options.truecolor === true ? 24 : 16)); + this.#startedAt = this.#now(); + } + + get #width(): number { + return lineWidth(this.#stream); + } + + #line(text = ""): void { + this.#stream.write(`${text}\n`); + } + + /** Clears the spinner line from the screen, if one is drawn. */ + #clearRunning(): void { + if (this.#drawn) this.#stream.write("\r\u001b[2K"); + this.#drawn = false; + } + + /** The spinner line: the frame, the ID, what the check is doing, the time so far; never wider than the terminal. */ + #drawRunning(): void { + const running = this.#running; + if (!this.#live || running === undefined) return; + const elapsed = this.#now() - running.startedAt; + const frame = SPINNER_FRAMES[Math.floor(elapsed / SPINNER_MS) % SPINNER_FRAMES.length] ?? SPINNER_FRAMES[0]; + const id = this.#clean(running.id); + const time = duration(elapsed); + const max = this.#width; + const fixed = 3 + 2 + [...id].length + 2 + 2 + [...time].length; + const doing = truncate(this.#clean(DOING[running.id] ?? running.name), Math.max(1, max - fixed)); + const left = ` ${this.#style.paint(frame, "accent")} ${this.#style.paint(id, "bold")} ${this.#style.paint(doing, "muted")}`; + let line = spread(left, this.#style.paint(time, "muted"), max); + if (visibleLength(line) > max) line = left; + this.#stream.write(`\r\u001b[2K${line}`); + this.#drawn = true; + } + + #stopTimer(): void { + if (this.#timer !== undefined) clearInterval(this.#timer); + this.#timer = undefined; + } + + /** ` ◆ wasit · x402 conformance`, then `label value` rows. */ + public header(version: string, subject: string, rows: ReadonlyArray = []): void { + const s = this.#style; + this.#line(` ${s.paint("◆", "accent")} ${s.paint("wasit", "bold")} ${s.paint(`${this.#clean(version)} · ${this.#clean(subject)}`, "muted")}`); + const pad = Math.max(0, ...rows.map(([label]) => label.length)); + for (const [label, value] of rows) this.#line(` ${s.paint(label.padEnd(pad), "muted")} ${this.#clean(value)}`); + this.#line(); + } + + /** A block heading: ` payment · stellar:testnet · testnet funds move`. */ + public phase(name: string, parts: ReadonlyArray = []): void { + this.#clearRunning(); + const s = this.#style; + const rest = parts.map(([text, role]) => `${s.paint("·", "muted")} ${s.paint(this.#clean(text), role ?? "muted")}`).join(" "); + this.#line(` ${s.paint(this.#clean(name), "bold", "accent")}${rest === "" ? "" : ` ${rest}`}`); + this.#drawRunning(); + } + + /** A note under a block: why checks were left out, or that money moves. */ + public note(text: string): void { + this.#clearRunning(); + for (const line of wrap(this.#clean(text), this.#width, " ")) this.#line(this.#style.paint(line, "warning")); + this.#drawRunning(); + } + + /** A check (or a group of checks) starts: its spinner line, on a real terminal. */ + public running(id: string, name: string): void { + this.#clearRunning(); + this.#stopTimer(); + this.#running = { id, name, startedAt: this.#now() }; + this.#drawRunning(); + if (this.#live) { + this.#timer = setInterval(() => this.#drawRunning(), this.#tickMs); + this.#timer.unref?.(); + } + } + + /** A progress line from the check in flight, dimmed, above its spinner line. */ + public progress(text: string): void { + this.#clearRunning(); + for (const line of wrap(`↳ ${this.#clean(text)}`, this.#width, DETAIL)) this.#line(this.#style.paint(line, "dim")); + this.#drawRunning(); + } + + /** + * A check's result replaces its spinner line and carries the time since it + * started. Results computed together with an earlier one (the challenge + * checks, or the checks skipped after a failed payment) carry none, and a + * skipped check never does. + */ + public result(result: CheckResult): void { + let ms: number | undefined; + if (this.#running !== undefined) { + ms = this.#now() - this.#running.startedAt; + this.#clearRunning(); + this.#stopTimer(); + this.#running = undefined; + } + const skip = checkStatus(result) === "SKIP"; + if (skip) ms = undefined; + const repeated = skip && this.#lastSkip === result.detail; + this.#lastSkip = skip ? result.detail : undefined; + for (const line of resultLines(result, this.#style, this.#width, this.#clean, ms, !repeated)) this.#line(line); + } + + /** A blank line between blocks. */ + public gap(): void { + this.#clearRunning(); + this.#line(); + this.#drawRunning(); + } + + /** The verdict, the counts, the run's duration, and the plain output's closing notes. */ + public finish(results: readonly CheckResult[], outcome: EndpointOutcome | undefined, notes: readonly string[]): void { + this.#clearRunning(); + this.#stopTimer(); + this.#running = undefined; + const s = this.#style; + const verdict = outcome === undefined ? "" : `${s.badge(VERDICT[outcome].text, VERDICT[outcome].role)} `; + this.#line(); + const parts = [...countsParts(results, s), s.paint(duration(this.#now() - this.#startedAt), "bold")]; + const oneLine = ` ${verdict}${parts.join(s.paint(" · ", "muted"))}`; + if (visibleLength(oneLine) <= this.#width) { + this.#line(oneLine); + } else { + if (verdict !== "") this.#line(` ${verdict.trimEnd()}`); + for (const line of packParts(parts, this.#width, " ", s)) this.#line(line); + } + for (const note of notes) { + this.#line(); + const lines = wrap(this.#clean(note), this.#width, " "); + lines[0] = ` ${s.paint("note", "bold", "warning")} ${lines[0]?.trimStart() ?? ""}`; + for (const line of lines) this.#line(line); + } + } +} diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts index 093da64..f03a87b 100644 --- a/packages/cli/src/output.ts +++ b/packages/cli/src/output.ts @@ -14,6 +14,9 @@ import { type ProtocolId, } from "@wasit-dev/core"; +import { countsLine, resultLines } from "./live.js"; +import { lineWidth, type Styler } from "./style.js"; + /** * Prints an advisory/status line meant for a human watching the terminal, * never part of the run's actual result. Routed to stderr when --json is @@ -40,6 +43,41 @@ export interface ReportOptions { readonly emit?: (line: string) => void; /** Values no output may carry. Default: the keys and header values in the environment. */ readonly secrets?: readonly string[]; + /** Colours for a person at a terminal (`colorEnabled`). Absent or off: the plain text, unchanged. */ + readonly style?: Styler; + /** The width coloured lines are laid out to. Default 80. */ + readonly width?: number; +} + +/** The exit code of a run, by the same rule `report` uses. */ +export function exitCodeFor(results: CheckResult[], protocol?: ProtocolId): number { + return protocol === undefined ? summarize(results).exitCode : exitCodeForEndpoint(results, protocol); +} + +/** The notes that close a run's text output, when it has no verdict. */ +export function verdictNotes(results: CheckResult[], protocol?: ProtocolId): string[] { + const counts = summarize(results); + const exitCode = exitCodeFor(results, protocol); + if (counts.errored > 0 && counts.failed === 0) { + return [ + "No verdict: some checks never reached the target or the run is " + + "misconfigured. This is not a statement about the target's conformance.", + ]; + } + if (protocol !== undefined && exitCode === 2 && paymentGroupUnsupported(results, protocol)) { + return [ + "No verdict: the payment checks were asked for and Wasit cannot pay on this network " + + "(unsupported; the skipped checks say why), so nothing was signed. This is not a failure " + + "of the service, and not a pass.", + ]; + } + if (protocol !== undefined && exitCode === 2 && endpointOutcome(results, protocol) === "unsupported") { + return [ + "No verdict: Wasit could not grade this service (unsupported; the skipped checks say why). " + + "This is not a failure of the service, and not a pass.", + ]; + } + return []; } /** @@ -62,7 +100,7 @@ export function report(results: CheckResult[], json: boolean, options: ReportOpt const secrets = options.secrets ?? deniedEnvValues(process.env); const clean = (text: string): string => sanitizeText(text, { redact: secrets }); const counts = summarize(results); - const exitCode = options.protocol === undefined ? counts.exitCode : exitCodeForEndpoint(results, options.protocol); + const exitCode = exitCodeFor(results, options.protocol); if (json) { const run = options.protocol === undefined ? toStructuredRun(results) : toGradedRun(results, options.protocol); @@ -70,6 +108,24 @@ export function report(results: CheckResult[], json: boolean, options: ReportOpt return exitCode; } + // Coloured, for a person at a terminal: the same checks, details, fixes and + // notes, laid out like a test runner. + const style = options.style; + if (style !== undefined && style.enabled) { + const width = options.width ?? lineWidth({}); + let lastSkip: string | undefined; + for (const result of results) { + const skip = checkStatus(result) === "SKIP"; + const repeated = skip && lastSkip === result.detail; + lastSkip = skip ? result.detail : undefined; + for (const line of resultLines(result, style, width, clean, undefined, !repeated)) emit(line); + } + emit(""); + emit(` ${countsLine(results, style)}`); + for (const message of verdictNotes(results, options.protocol)) emit(`\n ${style.paint("note", "bold", "warning")} ${clean(message)}`); + return exitCode; + } + for (const result of results) { const flag = result.destructive ? " [destructive]" : ""; emit(clean(`${checkStatus(result)} ${result.id} ${result.name}${flag}`)); @@ -88,27 +144,7 @@ export function report(results: CheckResult[], json: boolean, options: ReportOpt if (counts.skipped > 0) line.push(`${counts.skipped} skipped`); emit(`${line.join(", ")}.`); - if (counts.errored > 0 && counts.failed === 0) { - emit( - "\nNo verdict: some checks never reached the target or the run is " + - "misconfigured. This is not a statement about the target's conformance.", - ); - } else if (options.protocol !== undefined && exitCode === 2 && paymentGroupUnsupported(results, options.protocol)) { - emit( - "\nNo verdict: the payment checks were asked for and Wasit cannot pay on this network " + - "(unsupported; the skipped checks say why), so nothing was signed. This is not a failure " + - "of the service, and not a pass.", - ); - } else if ( - options.protocol !== undefined && - exitCode === 2 && - endpointOutcome(results, options.protocol) === "unsupported" - ) { - emit( - "\nNo verdict: Wasit could not grade this service (unsupported; the skipped checks say why). " + - "This is not a failure of the service, and not a pass.", - ); - } + for (const message of verdictNotes(results, options.protocol)) emit(`\n${message}`); return exitCode; } diff --git a/packages/cli/src/style.ts b/packages/cli/src/style.ts new file mode 100644 index 0000000..41eed2f --- /dev/null +++ b/packages/cli/src/style.ts @@ -0,0 +1,222 @@ +/** + * Colours and line layout for a person watching the terminal (Najmi, + * 2026-11-19): Wasit's own look, in the palette the site and the dashboard use + * (`dashboard/theme.ts`), a spinner while a check runs, and the run's duration. + * + * Colour is a layer over the plain text, never a second wording: every line is + * sanitised first (`sanitizeText`), then styled, so nothing a service sent can + * carry an escape sequence of its own. Output that a program reads stays plain: + * `--json`, a pipe, CI and `NO_COLOR` all get the exact text Wasit printed + * before colours existed. + */ + +import { THEME } from "./dashboard/theme.js"; + +/** The parts of a stream this module reads. */ +export interface StyleStream { + readonly isTTY?: boolean; + readonly columns?: number; +} + +type Env = Readonly>; + +function set(value: string | undefined): boolean { + return value !== undefined && value !== ""; +} + +/** + * True when lines may carry colour: `NO_COLOR` set turns it off, `FORCE_COLOR` + * set (and not "0") turns it on, a dumb terminal and CI are plain, otherwise a + * TTY is coloured and anything else is not. + */ +export function colorEnabled(stream: StyleStream, env: Env): boolean { + if (set(env["NO_COLOR"])) return false; + if (set(env["FORCE_COLOR"]) && env["FORCE_COLOR"] !== "0") return true; + if (env["TERM"] === "dumb") return false; + if (set(env["CI"]) || set(env["GITHUB_ACTIONS"])) return false; + return stream.isTTY === true; +} + +/** + * True when a line may be rewritten in place (the running line and its + * spinner): colour on, and a real terminal. A forced colour into a pipe gets + * colour but no cursor movement. + */ +export function liveEnabled(stream: StyleStream, env: Env): boolean { + return colorEnabled(stream, env) && stream.isTTY === true && !set(env["CI"]) && !set(env["GITHUB_ACTIONS"]); +} + +/** True when the terminal says it shows 24-bit colour; the brand colours are then exact. */ +export function truecolorEnabled(env: Env): boolean { + const value = (env["COLORTERM"] ?? "").toLowerCase(); + return value === "truecolor" || value === "24bit"; +} + +/** How many colours the terminal says it shows: 24-bit, 256, or the 16 of every terminal. */ +export type ColorDepth = 16 | 256 | 24; + +export function colorDepth(env: Env): ColorDepth { + if (truecolorEnabled(env)) return 24; + if ((env["TERM"] ?? "").includes("256")) return 256; + return 16; +} + +/** The roles a line's parts are painted in. */ +export type Role = "accent" | "muted" | "success" | "warning" | "danger" | "error" | "bold" | "dim"; + +/** Each role: its brand colour, and the 16-colour code a plain terminal gets instead. */ +const ROLES: Record, { readonly hex: string; readonly basic: number }> = { + accent: { hex: THEME.accent, basic: 35 }, + muted: { hex: THEME.muted, basic: 90 }, + success: { hex: THEME.success, basic: 32 }, + warning: { hex: THEME.warning, basic: 33 }, + danger: { hex: THEME.danger, basic: 31 }, + error: { hex: "#d946ef", basic: 95 }, +}; + +function rgb(hex: string): string { + const value = Number.parseInt(hex.slice(1), 16); + return `${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}`; +} + +/** Applies roles to text, or returns it unchanged when colour is off. */ +export interface Styler { + readonly enabled: boolean; + paint(text: string, ...roles: Role[]): string; + /** ` LABEL ` on a background in the role's colour; the bare label when colour is off. */ + badge(label: string, role: BadgeRole): string; +} + +/** The roles a badge's background can take. */ +export type BadgeRole = "success" | "danger" | "warning" | "error"; + +/** Black ink on the light backgrounds (green, yellow), white on the dark ones (red, magenta). */ +const BADGE_DARK_INK: Record = { success: true, warning: true, danger: false, error: false }; +/** The 256-colour backgrounds nearest the brand colours. */ +const BADGE_256: Record = { success: 41, warning: 214, danger: 203, error: 171 }; +const BADGE_16: Record = { success: 42, warning: 43, danger: 41, error: 45 }; + +/** + * The SGR parameters of a badge. The ink is given exactly (24-bit or 256-colour + * black and white), never as a bold colour of the 16: a terminal that draws bold + * text in bright colours (VS Code and iTerm2 by default) turns bold black into + * grey, which melts into a green or yellow background. On a 16-colour terminal + * black ink is not bold, for the same reason. + */ +function badgeParams(role: BadgeRole, depth: ColorDepth): string { + const dark = BADGE_DARK_INK[role]; + if (depth === 24) return `1;${dark ? "38;2;0;0;0" : "38;2;255;255;255"};48;2;${rgb(ROLES[role].hex)}`; + if (depth === 256) return `1;${dark ? "38;5;16" : "38;5;231"};48;5;${BADGE_256[role]}`; + return dark ? `30;${BADGE_16[role]}` : `1;97;${BADGE_16[role]}`; +} + +/** + * A styler. `depth` is the terminal's colour depth (`colorDepth`); `true` is + * read as 24-bit, `false` or nothing as the 16 colours of every terminal. + */ +export function styler(enabled: boolean, depth: ColorDepth | boolean = 16): Styler { + const bits: ColorDepth = depth === true ? 24 : depth === false ? 16 : depth; + const truecolor = bits === 24; + return { + enabled, + badge(label, role) { + if (!enabled) return label; + return `\u001b[${badgeParams(role, bits)}m ${label} \u001b[22;39;49m`; + }, + paint(text, ...roles) { + if (!enabled || roles.length === 0 || text === "") return text; + let open = ""; + let close = ""; + for (const role of roles) { + if (role === "bold" || role === "dim") { + open += role === "bold" ? "\u001b[1m" : "\u001b[2m"; + close = `\u001b[22m${close}`; + continue; + } + const { hex, basic } = ROLES[role]; + open += truecolor ? `\u001b[38;2;${rgb(hex)}m` : `\u001b[${basic}m`; + close = `\u001b[39m${close}`; + } + return `${open}${text}${close}`; + }, + }; +} + +/** The SGR sequences this module writes, and only those, for measuring a line. */ +const SGR = /\u001b\[[0-9;]*m/g; + +/** The width a line takes on screen: its length without the colour codes. */ +export function visibleLength(text: string): number { + return [...text.replace(SGR, "")].length; +} + +/** + * A check's status as a mark and a badge that agree (Najmi, 2026-11-20): + * ✓ PASS, ✗ FAIL, ○ SKIP, ! ERROR (the check could not run). Text marks, not + * emoji: an emoji takes two columns in many terminals and breaks the columns. + */ +export const MARKS = { + PASS: { mark: "✓", markRole: "success", badge: "PASS", badgeRole: "success" }, + FAIL: { mark: "✗", markRole: "danger", badge: "FAIL", badgeRole: "danger" }, + SKIP: { mark: "○", markRole: "warning", badge: "SKIP", badgeRole: "warning" }, + ERROR: { mark: "!", markRole: "error", badge: "ERROR", badgeRole: "error" }, +} as const satisfies Record; + +/** The spinner's frames, as the dashboard draws them, one every 80 ms. */ +export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const; +export const SPINNER_MS = 80; + +/** "12ms" under a second, "6.82s" from a second on. */ +export function duration(ms: number): string { + if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`; + return `${(ms / 1000).toFixed(2)}s`; +} + +/** + * `left` and `right` on one line, `right` flush with the width. A line that + * does not fit keeps two spaces between them and runs over. + */ +export function spread(left: string, right: string, width: number): string { + if (right === "") return left; + const gap = Math.max(2, width - visibleLength(left) - visibleLength(right)); + return `${left}${" ".repeat(gap)}${right}`; +} + +/** Cuts plain text to `max` characters, ending in "…". */ +export function truncate(text: string, max: number): string { + const chars = [...text]; + if (chars.length <= max) return text; + if (max <= 1) return "…".slice(0, Math.max(0, max)); + return `${chars.slice(0, max - 1).join("")}…`; +} + +/** + * Plain text wrapped to `width` columns, every line after `indent`. A word + * longer than a line (a URL, a hash) is kept whole and runs over. + */ +export function wrap(text: string, width: number, indent: string): string[] { + const room = Math.max(20, width - [...indent].length); + const lines: string[] = []; + let current = ""; + for (const word of text.split(/\s+/).filter((part) => part !== "")) { + if (current === "") current = word; + else if ([...current].length + 1 + [...word].length <= room) current += ` ${word}`; + else { + lines.push(current); + current = word; + } + } + if (current !== "") lines.push(current); + return lines.map((line) => `${indent}${line}`); +} + +/** + * The width lines are laid out to: one column less than the terminal's (a line + * as wide as the screen makes some terminals start a new line), at most 100, + * 80 when unknown. + */ +export function lineWidth(stream: StyleStream): number { + const columns = stream.columns; + if (columns === undefined || !Number.isFinite(columns) || columns <= 0) return 80; + return Math.max(20, Math.min(100, Math.floor(columns) - 1)); +} diff --git a/packages/cli/test/unit/live-output.test.ts b/packages/cli/test/unit/live-output.test.ts new file mode 100644 index 0000000..b00f7b5 --- /dev/null +++ b/packages/cli/test/unit/live-output.test.ts @@ -0,0 +1,329 @@ +/** + * The coloured, live text output (Najmi, 2026-11-19), in Wasit's own look: a + * header, two blocks of checks, each line with a mark and a badge that agree + * (✓ PASS on green, ✗ FAIL on red, ○ SKIP on yellow, ! ERROR on magenta), + * each check's duration, a spinner line saying what the check in flight is + * doing, and the verdict, the counts and the run's duration at the end. + * + * What must not change: output a program reads. A pipe, CI, NO_COLOR and + * --json get the plain text, byte for byte; a service's text is sanitised + * before it is coloured, so the only escape sequences on screen are Wasit's own; + * and the spinner line never wraps, since a wrapped line cannot be rewritten. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; +import { type CheckResult, errored, sanitizeText, skipped } from "@wasit-dev/core"; + +import { LiveReport } from "../../src/live.js"; +import { report } from "../../src/output.js"; +import { colorEnabled, liveEnabled, spread, styler, truncate, visibleLength, wrap } from "../../src/style.js"; +import { startPaywall, type Paywall } from "./run-helpers.js"; + +const CLI = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); +const SECRET = "canary-secret-value-91c2"; +const SPINNER = /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/; +const SGR = /\u001b\[[0-9;]*m/g; + +const pass: CheckResult = { id: "X402-01", name: "402 Response Status", pass: true, detail: "Server responded with 402 as required." }; +const fail: CheckResult = { + id: "X402-08", + name: "Payment Replay Rejected", + pass: false, + detail: `The same payment was accepted again (HTTP 200). ${SECRET}`, +}; +const skip = skipped("X402-11", "Rejected Request Not Settled", "no request the service must refuse is configured."); +const error = errored("X402-06", "Signature Resubmit Accepted", new Error("Stellar simulation failed")); +const hostile: CheckResult = { + id: "X402-04", + name: "Required Fields Present", + pass: false, + detail: "bad \u001b]0;title\u0007 body \u001b[2J\u001b[31mred::set-output name=x::1", +}; + +/** A stream that records what is written, as a terminal of `columns` would get it. */ +function terminal(columns = 80, isTTY = true) { + const writes: string[] = []; + return { stream: { isTTY, columns, write: (chunk: string) => writes.push(chunk) }, writes, text: () => writes.join("") }; +} + +const clean = (text: string) => sanitizeText(text, { redact: [SECRET] }); +const plainText = (text: string) => text.replace(SGR, ""); + +describe("when colour is on", () => { + it("is off for a pipe, NO_COLOR, CI, GitHub Actions and a dumb terminal; FORCE_COLOR turns it on", () => { + assert.equal(colorEnabled({ isTTY: true }, {}), true); + assert.equal(colorEnabled({ isTTY: false }, {}), false); + assert.equal(colorEnabled({ isTTY: true }, { NO_COLOR: "1" }), false); + assert.equal(colorEnabled({ isTTY: true }, { CI: "true" }), false); + assert.equal(colorEnabled({ isTTY: true }, { GITHUB_ACTIONS: "true" }), false); + assert.equal(colorEnabled({ isTTY: true }, { TERM: "dumb" }), false); + assert.equal(colorEnabled({ isTTY: false }, { FORCE_COLOR: "1" }), true); + assert.equal(colorEnabled({ isTTY: false }, { FORCE_COLOR: "0" }), false); + assert.equal(colorEnabled({ isTTY: true }, { FORCE_COLOR: "1", NO_COLOR: "1" }), false, "NO_COLOR wins"); + }); + + it("rewrites lines in place only on a real terminal, never in a pipe or CI, even with FORCE_COLOR", () => { + assert.equal(liveEnabled({ isTTY: true }, {}), true); + assert.equal(liveEnabled({ isTTY: false }, { FORCE_COLOR: "1" }), false); + assert.equal(liveEnabled({ isTTY: true }, { FORCE_COLOR: "1", CI: "true" }), false); + }); +}); + +describe("the line layout", () => { + it("puts the right part flush with the width, whatever the colours", () => { + const style = styler(true); + const line = spread(` ${style.paint("✓", "success")} ${style.paint("X402-01", "bold")} 402 Response Status`, style.paint("8ms", "muted"), 79); + assert.equal(visibleLength(line), 79); + }); + + it("wraps text under an indent and cuts a long line with an ellipsis", () => { + const lines = wrap("one two three four five six seven eight nine ten eleven twelve", 30, " "); + assert.ok(lines.length > 1); + for (const line of lines) assert.ok(line.startsWith(" ") && line.length <= 30, line); + assert.equal(truncate("abcdefgh", 5), "abcd…"); + }); +}); + +describe("LiveReport", () => { + it("draws a spinner line saying what the check is doing, then replaces it with ✓, the check and its time", async () => { + const t = terminal(); + let now = 1000; + const live = new LiveReport({ stream: t.stream, live: true, clean, now: () => now, tickMs: 5 }); + live.running("X402-06", "Signature Resubmit Accepted"); + now = 1400; + await new Promise((resolve) => setTimeout(resolve, 30)); + const drawn = t.writes.filter((chunk) => SPINNER.test(chunk)); + assert.ok(drawn.length >= 2, "the spinner was not redrawn"); + assert.match(plainText(drawn.at(-1) ?? ""), /X402-06 {2}paying once, then reading the transfer on chain +400ms$/); + now = 7820; + live.result({ ...pass, id: "X402-06", name: "Signature Resubmit Accepted" }); + const text = t.text(); + assert.match(text, /\r\u001b\[2K/, "the spinner line was not cleared"); + assert.match(plainText(text), /✓ X402-06 {2}Signature Resubmit Accepted +6\.82s {2} PASS \n/); + }); + + it("never draws a spinner line wider than the terminal, so it never wraps", () => { + for (const columns of [30, 50, 80, 200]) { + const t = terminal(columns); + const live = new LiveReport({ stream: t.stream, live: true, clean }); + live.running("X402-10", "Expired Authorization Rejected"); + live.result(pass); + const spinnerLines = t.writes.filter((chunk) => chunk.startsWith("\r\u001b[2K") && SPINNER.test(chunk)); + assert.ok(spinnerLines.length >= 1, `${columns}: no spinner line`); + for (const chunk of spinnerLines) { + assert.ok(!chunk.includes("\n"), `${columns}: a spinner line holds a newline`); + assert.ok(visibleLength(chunk.replace("\r\u001b[2K", "")) < columns, `${columns}: ${JSON.stringify(plainText(chunk))}`); + } + } + }); + + it("marks and badges each status alike: ✓ PASS, ✗ FAIL, ○ SKIP, ! ERROR", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: true, clean }); + live.result(pass); + live.result(fail); + live.running("X402-11", "Rejected Request Not Settled"); + live.result(skip); + live.result(error); + const text = t.text(); + assert.match(text, /\u001b\[30;42m PASS /, "PASS in black on green"); + assert.match(text, /\u001b\[1;97;41m FAIL /, "FAIL in white on red"); + assert.match(text, /\u001b\[30;43m SKIP /, "SKIP in black on yellow"); + assert.match(text, /\u001b\[1;97;45m ERROR /, "ERROR in white on magenta"); + assert.match(text, /\u001b\[32m✓/); + assert.match(text, /\u001b\[31m✗/); + assert.match(text, /\u001b\[33m○/); + assert.match(text, /\u001b\[95m!/); + const plain = plainText(text); + assert.match(plain, /✓ X402-01 {2}402 Response Status +PASS \n/); + assert.match(plain, /✗ X402-08 {2}Payment Replay Rejected +FAIL \n/, "a FAIL is marked ✗, like its badge"); + assert.match(plain, /○ X402-11 {2}Rejected Request Not Settled +SKIP \n/, "a skipped check carries no time"); + assert.match(plain, /! X402-06 {2}Signature Resubmit Accepted +ERROR \n/, "a check that could not run: !"); + assert.ok(!/✓ X402-08/.test(plain), "a FAIL is never marked ✓"); + assert.match(plain, /\n {5}fix {2}/); + }); + + it("gives a skip's reason once when the skips that follow it have the same reason", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: false, clean }); + const reason = "the target was never reached, so it issued no challenge to inspect."; + for (const [id, name] of [["X402-02", "Payment Header Present"], ["X402-03", "Header Payload Decodable"], ["X402-04", "Required Fields Present"]]) { + live.result(skipped(id!, name!, reason)); + } + live.result(skipped("X402-05", "Network Identifier Valid", "another reason entirely.")); + const plain = plainText(t.text()); + assert.equal(plain.split("the target was never reached").length - 1, 1, plain); + for (const id of ["X402-02", "X402-03", "X402-04", "X402-05"]) assert.match(plain, new RegExp(`○ ${id} `)); + assert.match(plain, /another reason entirely/); + }); + + it("uses the exact brand colours when the terminal shows 24-bit colour", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: false, clean, truecolor: true }); + live.result(pass); + assert.match(t.text(), /\u001b\[38;2;40;200;64m✓/, "the site's green, #28c840"); + assert.match(t.text(), /\u001b\[1;38;2;0;0;0;48;2;40;200;64m PASS /, "PASS in exact black on the site's green"); + }); + + it("writes badge ink that stays black or white when bold: never a bold colour of the 16, which some terminals draw bright", () => { + for (const depth of [16, 256, 24] as const) { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: false, clean, depth }); + for (const result of [pass, fail, skip, error]) live.result(result); + live.finish([pass], "conformant", []); + assert.ok(!/\u001b\[1;3[0-7];/.test(t.text()), `${depth}: a bold 16-colour ink`); + assert.ok(!/\u001b\[1;30m|\u001b\[1;30;/.test(t.text()), `${depth}: bold black`); + } + const t = terminal(); + new LiveReport({ stream: t.stream, live: false, clean, depth: 256 }).result(pass); + assert.match(t.text(), /\u001b\[1;38;5;16;48;5;41m PASS /, "256 colours: exact black on green"); + }); + + it("ends with the verdict, the counts and the run's duration, and the notes of the plain output", () => { + const t = terminal(); + let now = 0; + const live = new LiveReport({ stream: t.stream, live: false, clean, now: () => now }); + now = 45_650; + live.finish([pass, fail, skip, error], "non-conformant", ["No verdict: a note."]); + const plain = plainText(t.text()); + assert.match(plain, / NOT CONFORMANT {2}1 passed · 1 failed · 1 could not run · 1 skipped · 45\.65s/); + assert.match(plain, /note {2}No verdict: a note\./); + const ok = terminal(); + new LiveReport({ stream: ok.stream, live: false, clean }).finish([pass], "conformant", []); + assert.match(plainText(ok.text()), / CONFORMANT {2}1 passed · \d+ms/); + assert.match(ok.text(), /\u001b\[30;42m CONFORMANT /); + const narrow = terminal(40); + new LiveReport({ stream: narrow.stream, live: false, clean }).finish([pass, fail, skip, error], "no-verdict", []); + for (const line of plainText(narrow.text()).split("\n")) assert.ok(line.length < 40, `the closing line runs over: ${JSON.stringify(line)}`); + }); + + it("writes no cursor movement and no spinner when it is not live", () => { + const t = terminal(80, false); + const live = new LiveReport({ stream: t.stream, live: false, clean }); + live.running("X402-06", "Signature Resubmit Accepted"); + live.progress("reading the chain"); + live.result(pass); + assert.ok(!t.text().includes("\u001b[2K")); + assert.ok(!SPINNER.test(t.text())); + }); + + it("sanitises a service's text before colouring it: Wasit's own colour codes are the only escapes, and no secret", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: true, clean, truecolor: true }); + live.running("X402-04", "Required Fields Present"); + live.progress(`progress ${SECRET} \u001b]8;;http://x\u0007`); + live.result(hostile); + live.result(fail); + const text = t.text(); + assert.ok(!text.includes("\u0007"), "a BEL reached the terminal"); + // The sanitiser drops the escape characters; a printable leftover such as "]0;title" is plain text. + assert.ok(!text.includes("\u001b]"), "an OSC sequence reached the terminal"); + assert.ok(!text.includes("\u001b[2J"), "a screen clear reached the terminal"); + for (const sequence of text.match(/\u001b[^a-zA-Z]*[a-zA-Z]/g) ?? []) { + assert.match(sequence, /^\u001b\[[0-9;]*[mK]$/, JSON.stringify(sequence)); + } + assert.ok(!text.includes(SECRET), "a secret reached the terminal"); + for (const line of plainText(text).replace(/\r\u001b\[2K/g, "").split("\n")) assert.ok(!/^\s*(::|##\[)/.test(line), line); + }); +}); + +describe("report, with colours", () => { + function render(style?: ReturnType) { + const lines: string[] = []; + const code = report([pass, fail, skip], false, { emit: (line) => lines.push(line), secrets: [SECRET], ...(style ? { style } : {}) }); + return { code, text: lines.join("\n") }; + } + + it("is the plain text, unchanged, when colour is off", () => { + assert.deepEqual(render(styler(false)), render()); + assert.match(render().text, /^PASS {2}X402-01 {2}402 Response Status$/m); + }); + + it("marks the same checks, and keeps the exit code", () => { + const plain = render(); + const coloured = render(styler(true)); + assert.equal(coloured.code, plain.code); + assert.match(plainText(coloured.text), /✗ X402-08 {2}Payment Replay Rejected +FAIL /); + assert.ok(!coloured.text.includes(SECRET)); + }); +}); + +describe("wasit test, as the built binary", () => { + let paywall: Paywall; + let cwd: string; + before(async () => { + paywall = await startPaywall(); + cwd = await mkdtemp(path.join(tmpdir(), "wasit-live-")); + }); + after(async () => { + await paywall.close(); + await rm(cwd, { recursive: true, force: true }); + }); + + function wasit(args: string[], env: Record): Promise<{ code: number | null; out: string }> { + return new Promise((resolve) => { + const child = spawn(process.execPath, [CLI, ...args], { cwd, env: { PATH: process.env["PATH"] ?? "", HOME: cwd, ...env } }); + let out = ""; + child.stdout.on("data", (chunk) => (out += chunk)); + child.stderr.on("data", (chunk) => (out += chunk)); + child.on("close", (code) => resolve({ code, out })); + }); + } + + const read = () => ["test", "--target", `${paywall.base}/paid`, "--read-only"]; + + it("is in Wasit's look with FORCE_COLOR: header, blocks, marks, verdict and duration; same exit code; no cursor movement", async () => { + const plain = await wasit(read(), { NO_COLOR: "1" }); + const coloured = await wasit(read(), { FORCE_COLOR: "1" }); + assert.equal(coloured.code, plain.code); + const text = plainText(coloured.out); + assert.match(text, /◆ wasit 0\.8\.0-beta\.1 · x402 conformance/); + assert.match(text, /^ challenge · no payment$/m); + assert.match(text, /✓ X402-01 {2}402 Response Status .*PASS /); + assert.match(text, / CONFORMANT {2}5 passed · \d/); + assert.match(coloured.out, /\u001b\[32m✓/); + assert.match(coloured.out, /\u001b\[30;42m PASS /); + const term256 = await wasit(read(), { FORCE_COLOR: "1", TERM: "xterm-256color" }); + assert.match(term256.out, /\u001b\[1;38;5;16;48;5;41m PASS /); + assert.ok(!coloured.out.includes("\u001b[2K"), "a pipe got cursor movement"); + const truecolor = await wasit(read(), { FORCE_COLOR: "1", COLORTERM: "truecolor" }); + assert.match(truecolor.out, /\u001b\[38;2;40;200;64m✓/); + }); + + it("is the plain text with NO_COLOR, in CI, and in a pipe", async () => { + const envs: Array> = [{ NO_COLOR: "1", FORCE_COLOR: "1" }, { CI: "true" }, {}]; + for (const env of envs) { + const result = await wasit(read(), env); + assert.ok(!result.out.includes("\u001b["), JSON.stringify(env)); + assert.match(result.out, /^PASS {2}X402-01 {2}402 Response Status$/m, JSON.stringify(env)); + assert.match(result.out, /^5 passed\.$/m, JSON.stringify(env)); + } + }); + + it("on a network that is not a test network, says the payment checks are refused, not that funds move", async () => { + const result = await wasit(["test", "--target", `${paywall.base}/paid`, "--network", "stellar:pubnet"], { + FORCE_COLOR: "1", + STELLAR_PRIVATE_KEY: Keypair.random().secret(), + }); + const text = plainText(result.out); + assert.match(text, /^ payment · stellar:pubnet · not a test network: refused$/m); + assert.ok(!/funds move|settles a real payment/.test(text), "a mainnet run was told that money moves"); + assert.match(text, /! PREFLIGHT .*ERROR /); + assert.match(text, /Nothing was sent and\s+nothing was signed\./); + }); + + it("keeps --json plain JSON, even with FORCE_COLOR", async () => { + const result = await wasit([...read(), "--json"], { FORCE_COLOR: "1" }); + assert.ok(!result.out.includes("\u001b[")); + const start = result.out.indexOf("{"); + assert.doesNotThrow(() => JSON.parse(result.out.slice(start))); + }); +});