GitHub
Skip to content

Custom renderers

Replace how one format, or every format, is written, and render Markdown answers for a person.

A renderer is pure. render(run, ctx) returns { stdout?, stderr? }, and createOut does the writing, stdout first.

const out = createOut<{ hosts: string[] }>({
  tool: "fleet",
  command: "list",
  argv,
  renderers: {
    json: {
      render: (run) =>
        run.failure
          ? { stdout: `${JSON.stringify({ ok: false, error: run.failure.error.message })}\n` }
          : { stdout: `${JSON.stringify(run.result)}\n` },
    },
  },
});
ts

renderers replaces the renderer of the formats it names. The others keep readerly's. A name that isn't built in, such as sarif, also needs formats: ["sarif"] so --format sarif is accepted.

const out = createOut({
  tool: "acme",
  argv,
  render: (run, ctx) => ({ stdout: `${run.counts.error} errors\n` }),
});
ts

render replaces the rendering of every format. ctx.profile says which one the reader gets, and ctx.style colors text only when color is on.

renderers: {
  text: {
    entry: (entry) => (entry.type === "log" ? { stderr: `${entry.message}\n` } : undefined),
    render: (run) => ({}),
  },
},
ts

entry runs for each diagnostic, log and next line as the command adds it. jsonl uses it to write each record at once.

run holds the entries in call order, the counts, the result, the status, the summary, any failure and answer, and rerun, the command without reader flags. ctx holds the profile, the style, and maxRows, the rows to show before hiding the rest.

readerly doesn't render Markdown. Render an answer with @comark/ansi for a person, and pass it as it is to everyone else:

import { renderAnsi } from "@comark/ansi";

const page = await explain(code); // Markdown
out.write(
  out.profile.format === "text" ? await renderAnsi(page, { colors: out.profile.color }) : page,
);
return out.end();
ts

renderAnsi is async, so it runs before out.write, not inside a renderer. An agent reads the Markdown as it is, and JSON and jsonl carry it as answer.