[data-reveal]{opacity:1!important;transform:none!important}
DocumentationPlugin API

Plugin API

Reference for the CLI output module of the AntelopeJS core, which gives a CLI plugin the output, errors and exit codes of `ajs`.

Overview

@antelopejs/core/cli is the output layer of ajs itself, published for plugins. A plugin that uses it prints the same symbols and colors as the core commands, writes results and feedback to the same streams, renders the same help pages, reports errors with the same template of title, reason and fixes, and exits with the same codes.

The module is CommonJS with TypeScript declarations. It loads nothing from the AntelopeJS runtime, so importing it costs a few milliseconds. It loads the failure descriptions only when a run fails, and the prompt library only when a question is asked.

Declare @antelopejs/core as a peer dependency. The module first shipped in core 1.12.0, and later releases added exports such as applyHelpConventions and isQuietRun. Start the range at the release you build and test against, which npm view @antelopejs/core version prints:

json
{
  "peerDependencies": {
    "@antelopejs/core": ">=1.18.0 <2"
  }
}

TypeScript resolves the module through the package exports, so set "moduleResolution" to "node16", "nodenext" or "bundler".

Output contract

ajs <plugin> runs the plugin with the standard streams of ajs and exits with the plugin's exit code. A plugin reads like a core command when it follows the contract below. This module implements it.

  • stdout carries only results, so it can be piped or redirected. Results are data, --json documents, help and the version.
  • stderr carries everything else, such as progress, warnings, errors, summaries and next steps.
  • The exit code is 0 on success, 1 on failure, 2 on a usage error and 130 when the user cancels (see Exit codes). When a signal stops the plugin, ajs exits with 128 plus the signal number.
  • The global options of ajs given before the plugin name reach the plugin as environment variables. ajs --no-color dms dev sets NO_COLOR=1. ajs --verbose dms dev sets ANTELOPEJS_VERBOSE=*, and --verbose=cli,api sets ANTELOPEJS_VERBOSE=cli,api. Only the = form takes channels. ajs -q dms dev and ajs --quiet dms dev set ANTELOPEJS_QUIET=1. The module reads these variables. ajs forwards the options after the plugin name as arguments, so declare --no-color and -q, --quiet on your program too.
  • A quiet run (-q, --quiet or ANTELOPEJS_QUIET) prints only results, warnings and errors, and keeps its exit codes. It prints no progress, information, success messages, summaries or next steps. The Ui and the tasks of this module leave those out by themselves. For output you write yourself, isQuietRun() tells whether the run is quiet.

A complete command

typescript
import { Command } from "commander";
import {
  CliError,
  USAGE_EXIT_CODE,
  formatUsageErrors,
  getProcessUi,
  runTask,
  runWithErrorBoundary,
} from "@antelopejs/core/cli";

declare function buildFrontend(): Promise<void>;

const program = new Command()
  .name("ajs dms")
  .option("-q, --quiet", "Print only results, warnings and errors")
  .option("--no-color", "Disable colors (also NO_COLOR=1)");

program
  .command("build")
  .option("--port <port>", "Port of the preview server", "3000")
  .action(async (options: { port: string }) => {
    const port = Number(options.port);
    if (!Number.isInteger(port) || port < 1 || port > 65535) {
      throw new CliError({
        title: `Port ${options.port} is out of range`,
        reason: "A port is a number from 1 to 65535.",
        fixes: ["Pass a port such as --port 3000"],
        exitCode: USAGE_EXIT_CODE,
      });
    }
    await runTask("Building the frontend", () => buildFrontend(), {
      done: "Built the frontend",
    });
    getProcessUi().summary({
      headline: "Build complete",
      artifact: "./dist",
      nextSteps: [{ command: "ajs dms start", description: "serve the build" }],
    });
  });

formatUsageErrors(program);

void runWithErrorBoundary(async () => {
  await program.parseAsync();
});

runWithErrorBoundary prints whatever the command throws once, on stderr, and leaves the exit code in process.exitCode. formatUsageErrors prints commander's usage errors, such as an unknown option or a missing argument, with the same error template and exit code 2.

Output

ExportUse
getProcessUi()The Ui bound to stdout and stderr, which writes above the running tasks
createUi({ streams, capabilities, isQuiet })A Ui on other streams, for example in-memory streams in tests
getProcessPalette(channel)The colors of a channel, plain text when that channel has no colors
writeData(ui, { data, isJson, render })One JSON document on stdout with --json, the human rendering otherwise
formatDuration, pluralize, displayPath2.1s, 2 modules, ./modules/auth

A Ui writes results (value, json, table, list, heading, details) on stdout and feedback (message, problem, summary) on stderr. On a terminal, a Ui aligns a table under a header and fits it to the terminal width. It keeps the first column whole and cuts the widest other columns with ui.symbols.ellipsis. When the terminal is too narrow even for that, each row becomes one block of header and value lines. When stdout is piped, each table row becomes one line of tab-separated values. A quiet Ui leaves out info, success, skip and hint messages, feedback details and summaries. Its isQuiet option defaults to isQuietRun().

On a terminal, a Ui wraps everything else it writes as text to the terminal width, between words. That covers messages and their details, problems (title, reason, details and fixes), list items, details values and the descriptions of next steps. Each line after the first is indented under the text it continues, and a detail keeps its own leading spaces. Colors do not count toward the width. A word longer than the line, such as a long path, stays whole. When the stream is not a terminal, or its width is unknown, the Ui writes lines whole, so piped output and logs keep one line per message. For text you lay out yourself, wrapText(text, width) wraps it the same way.

Colors and symbols follow the rules of ajs, described in Global options. --no-color anywhere on the command line and NO_COLOR turn colors off, and FORCE_COLOR forces them. Terminals that cannot draw Unicode get an ASCII symbol set. detectCapabilities(processCapabilityContext()) returns what was detected. ui.symbols, selectSymbols and SYMBOL_SETS give the symbols themselves. These are the level symbols, bullet, rule and spinner, plus three symbols that join, cut and point without a hard-coded Unicode character: separator (" · " or " - "), ellipsis ("…" or "...") and arrow ("→" or "->"). Declare --no-color on your program so commander accepts it.

JSON data

ui.json(data) and the data of writeData accept only values that JSON.stringify writes as themselves: strings, numbers, booleans, null, and arrays and plain objects of these. Optional properties are allowed. Both type data as Data & JsonValue<Data>, and @antelopejs/core/cli exports JsonValue<Data>, which maps every other member to never. A function, symbol, bigint or undefined member, a Date, a class instance with methods, and any value typed unknown fail to compile. DataOutput<Data> takes the same type argument as writeData.

To print data of an unknown type, such as a parsed response body, narrow or parse it to a typed shape first:

typescript
import { CliError, getProcessUi, writeData } from "@antelopejs/core/cli";

interface Manifest {
  name: string;
  version: string;
}

declare const body: unknown;
declare const options: { json?: boolean };

function parseManifest(value: unknown): Manifest {
  if (
    typeof value === "object" &&
    value !== null &&
    "name" in value &&
    typeof value.name === "string" &&
    "version" in value &&
    typeof value.version === "string"
  ) {
    return { name: value.name, version: value.version };
  }
  throw new CliError({
    title: "Cannot read the manifest",
    reason: "The backend answered with no name or version.",
  });
}

const manifest = parseManifest(body);
writeData(getProcessUi(), {
  data: manifest,
  isJson: options.json,
  render: (ui) => ui.value(`${manifest.name}@${manifest.version}`),
});

Help

The module exports the help conventions of ajs, so a plugin's help pages read like the core's.

ExportUse
applyHelpConventions(program)-h, --help and help [command] worded like ajs, global options on every page, pages wrapped to the terminal
withExamples(command, examples)Appends an Examples: block that prints each { description, command } as a comment followed by the command
formatExamples(examples, width)The Examples: block as text
helpWidth(stream), helpTextWidth(context)The width help wraps to, which is the terminal width up to 80 columns, and 80 columns in a pipe
wrapText(text, width), unbreakable(text)Wraps text between words. The words of an unbreakable run, such as a command, stay on one line
formatHelpItem(term, termWidth, description, width)A term and its description, beside it or under it when fewer than 30 columns are left

applyHelpConventions applies to the command and every subcommand it has at that point, so call it once the program is complete. Commander does not wrap text added with addHelpText. Pass a function instead, and wrap the text with wrapText(text, helpTextWidth(context)).

Progress

runTask(label, work, { done, failed }) runs work as a task of the process TaskList, which getProcessTasks() returns. On an interactive terminal the task is an animated line. In CI, in pipes and with --verbose, it is a single final line. Tasks that take a second or more show their duration. Create a new TaskList({ streams }) to run tasks on other streams.

Errors

Throw a CliError for every failure the user can act on.

typescript
import { CliError } from "@antelopejs/core/cli";

declare const error: unknown;

throw new CliError(
  {
    title: "Cannot read the manifest",
    reason: "The backend answered 401.",
    fixes: ["Check DMS_TOKEN, then try again"],
  },
  { cause: error },
);

The boundary prints a problem as its title, its reason and its details, then its fixes. Pass the low-level error as cause. --verbose and ANTELOPEJS_VERBOSE print its stack trace, and the error suggests --verbose only when it has such a cause or command output to show. isVerboseRun() tells whether the run is verbose.

To explain the errors your commands do not wrap in one place, pass the translate option to runWithErrorBoundary. It receives every failure that is not a CliError and returns a problem, or undefined to keep the default description.

typescript
import { runWithErrorBoundary } from "@antelopejs/core/cli";

declare function main(): Promise<void>;

void runWithErrorBoundary(main, {
  translate: (cause) =>
    cause instanceof TypeError && cause.message === "fetch failed"
      ? {
          title: "Cannot reach the DMS backend",
          fixes: ["Start the backend, then try again"],
        }
      : undefined,
});

Prompts

createPrompter({ command, acceptsDefaults, defaultsFlag }) asks the questions a command cannot get from its flags. Each question takes the flag that answers it. When nobody can answer, because stdin is not a terminal or CI is set, the prompter throws a NeedsInputError that names that flag, with exit code 2. A cancelled prompt throws a CancelledError, reported as Cancelled with exit code 130.

typescript
import { createPrompter } from "@antelopejs/core/cli";

declare const options: { yes?: boolean };

const prompter = createPrompter({ command: "ajs dms clean" });
const isConfirmed = await prompter.confirm({
  message: "Delete the build output?",
  flag: "--yes",
  answer: options.yes,
  defaultAnswer: false,
});

Exit codes

ExportCodeMeaning
SUCCESS_EXIT_CODE0The command succeeded
FAILURE_EXIT_CODE1The command failed
USAGE_EXIT_CODE2The command line is wrong; nothing was attempted
CANCELLED_EXIT_CODE130The user cancelled the command

A CliError exits with 1 unless its problem sets another exitCode.

Versioning

Every export of @antelopejs/core/cli follows semantic versioning with @antelopejs/core. Other paths inside the package are internal, and the package exports field blocks imports of them.