Extensions
Add shared flags, commands, hooks, and generated files to your CLI.
Extensions add behavior across your CLI. Start with the built-ins for help, version output, color control, and command suggestions:
import { Crust, defineCommand } from "@crustjs/core";
import { didYouMean, help, noColor, version } from "@crustjs/extensions";
const deploy = defineCommand("deploy", { description: "Deploy the app" }, (command) =>
command.action(() => {}),
);
export const app = new Crust("my-cli", { version: "0.2.0" })
.add(deploy)
.extend(noColor(), version(), help(), didYouMean());
await app.execute();$ my-cli --version
my-cli v0.2.0
$ my-cli deply
Unknown command "deply". Did you mean "deploy"?
Available commands: deploy
# exit 1help() adds -h and --help and shows help when this actionless root is invoked. The .extend() order doesn't change behavior: --help --version prints help and --version --help the version, the flag given first winning as in GNU tools, and --no-color applies to help output too.
Call .extend() on the root builder, not inside a command recipe. See built-in Extensions for the full list.
Write your own
Use an Extension when shared behavior needs flags, commands, or lifecycle hooks. For a helper used only inside actions, a plain function is enough.
This Extension adds a preview mode that skips the action:
import { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
export const preview = defineExtension(defineExtensionId("acme:preview"))
.flags({ preview: { type: "boolean", description: "Show the plan" } })
.handle("preview", (ctx) => ctx.stdout("nothing changed"));
const app = new Crust("deploy").extend(preview).action(({ stdout }) => stdout("deployed"));
await app.execute();$ deploy
deployed
$ deploy --preview
nothing changed.handle(flag, run) takes over the invocation when the user passes a flag the Extension owns, unless it is a negated boolean such as --no-preview: run replaces preRun, validation, and the action, and run() reports a handled outcome. The flag name must come from the Extension's own .flags(), so a typo is a compile error. Validation includes invalid argv and environment values, so a handler wins over them; an invalid flag or argument reads as undefined in ctx.flags and ctx.args, not as its default, and doesn't trigger a handler.
When several handled flags are passed, the one given first on the command line wins, whatever the .extend() order. Pass { eager: true } for flags that must win over every other handler, as help() and version() do: deploy --preview --help shows help. Typed run() input ranks handled flags by the key order of its flags object, and a flag set only through its env variable ranks after flags passed on the command line.
Give each Extension a namespaced id such as acme:preview. Registering the same id again replaces the earlier registration. The types don't track ids yet: they still see the earlier registration's commands, so a re-registration that contributes the same literal command names, or a later command reusing one of them, is a compile-time collision even though the app runs.
Builder methods other than .factory() return new frozen Extensions; there is no finalization step. Declare flags and Contexts before the hooks that read them. Collection methods append; setting a hook again replaces its callback.
For configurable Extensions, chain .factory():
import { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
export const banner = defineExtension(defineExtensionId("acme:banner")).factory(
(extension, text: string = "hello") => extension.preRun((ctx) => ctx.stdout(text)),
);
const app = new Crust("my-cli").extend(banner("welcome")).action(() => {});
await app.execute();Return a chain on the supplied Extension to keep its id. See ExtensionBuilder and ExtensionFactory for the full contracts.
Owned flags and commands
The preview flag above is available on every command, so no command may declare its own --preview. Set recursive: false on a flag definition to make it root-only; then only the root's flags must avoid its spellings.
An Extension can also install top-level commands:
import { Crust, defineCommand, defineExtension, defineExtensionId } from "@crustjs/core";
const doctor = defineCommand("doctor", (command) =>
command.action(({ rootCommand, stdout }) => stdout(`checking ${rootCommand.meta.name}`)),
);
export const diagnostics = defineExtension(defineExtensionId("acme:diagnostics")).add(doctor);
const app = new Crust("my-cli").extend(diagnostics);
await app.execute();$ my-cli doctor
checking my-cliContributed commands work like commands added with .add(), including typed run() paths. Like sibling commands, they cannot replace each other: a name or alias that collides with an app command or another Extension's command is a compile error, and a collision TypeScript can't see, such as a name chosen by a factory option, is a DEFINITION error when the app prepares. Such a name doesn't hide collisions among the other, statically known command names, but it makes run() results unknown for Extension commands registered up to and in that call, since a same-id re-registration may replace them; your own commands keep their result types. @crustjs/mcp uses this pattern to install an mcp command that serves your commands as MCP tools.
Hooks
After routing and parsing, an invocation runs these hooks:
setup → handle → preRun → validation → action → postRun
└─ no handler and no action → noActionimport { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
export const outcomes = defineExtension(defineExtensionId("acme:outcomes"))
.flags({ skip: { type: "boolean" } })
.handle("skip", () => {})
.postRun((ctx, outcome) => {
ctx.stdout(`outcome: ${outcome.}`);
});
const completed = new Crust("app").extend(outcomes).action(() => {});
console.log((await completed.run([])).stdout); // => "outcome: completed"
console.log((await completed.run([], { flags: { skip: true } })).stdout);
// => "outcome: handled"
const failed = new Crust("app").extend(outcomes).action(() => {
throw new Error("boom");
});
console.log((await failed.run([])).stdout); // => "outcome: failed"setupconfigures the process before anything prints, such as color or log level. Every setup runs, in.extend()order, before any handler; setups must not depend on each other. Register cleanup withctx.defer(), as in a Context's setup: it runs afterpostRunhooks, in reverse order together with Context cleanup, including after a failure..handle()is the only way a flag takes over the invocation; see Write your own.noActionruns when the command has no action and no handler took over, and ends the invocation ashandled. Use it for fallbacks such as help for a command group. Only one Extension in an application may set it; a second is aDEFINITIONerror when the app prepares.preRunruns only when the action will run, in.extend()order, before validation. Use it for checks and notices that must precede every action but never--helpor--version, such as a login check or a deprecation warning. Throw to fail the invocation;preRuncan't end it successfully.postRunruns in reverse order after every invocation that reached hooks, including handled and failed ones. Acompletedoutcome carries the command's result asoutcome.result: the awaited output of its.output()schema if it declares one, otherwise the action's awaited return value (undefinedfor a command without an action). After an async generator action,completedandfailedoutcomes also carry its yielded values asoutcome.events([]if it yielded none). Preparation, routing, argv-parse, and typedrun()input-binding failures happen before hooks and skip it; actx.bindInput()failure is a failure of thesetuporpreRunhook that called it and reaches it. Context cleanup runs afterwards.onErrorrenders terminal errors from.execute()in.extend()order; see Error handling..renderer()chooses how the action's output is presented; see Renderers.ctx.bindInput({ args, flags, raw })insetuporpreRunbinds structured input, such as a JSON object read from a flag likeinput()does, into the invocation. Arguments, flags, and passthrough tokens given explicitly on argv win, even when equal to the default; every other supplied key replaces the environment value or default and is converted exactly as typedrun()input. Underrun()nothing came from argv, so supplied keys replace the typed input. The last call wins. Afterwardsctx.args,ctx.flags, andctx.rawArgsshow the bound values to every later hook, and validation and the action use them. Bind insetupso everypreRuncheck sees the values whatever the.extend()order; it then also happens for--helpand--version. Bind inpreRunto do it only when the action will run. A bound flag never selects a handler. An unknown key, a positional argument supplied after an omitted earlier one, or a conversion failure (including a non-array value for a variadic argument ormultipleflag) throws aPARSEerror that fails the invocation like any other error from that hook: it reachesonErrorandpostRun, and fromsetupit also stops any flag handler,preRun, and the action.ctx.sourcesreports where each current value came from, keyed by argument name and canonical flag name:"argv","run","env","bound", or"default"; a name without a value is absent, andrawcovers passthrough tokens. It reads live, so keysbindInputsupplied report"bound". For example, with a booleanverboseflag (short-V) and aportflag read fromPORT,my-cli -VwithPORT=9000set gives{ args: {}, flags: { verbose: "argv", port: "env" }, raw: undefined }. An Extension that converts input before binding it can drop the keys argv gave first, so an invalid value argv overrides never fails.ctx.commandPathOf(definition)returns where a command definition is mounted, as canonical names from the root likectx.commandPath, orundefinedwhen the app does not add it. It matches the definition object by identity, so an Extension that takes command definitions from app code can print their command lines.
Only handlers and noAction can end an invocation early. Handlers are selected by the order of their flags on the command line, or by key order for typed run(); noAction runs only when the command has no action and no handler took over. Reordering .extend() changes neither choice, only what is meant to be ordered: setups, preRun checks, and onError hooks run in registration order, and postRun hooks and cleanups in reverse.
Hook flags are pre-validation values, not schema outputs. Check values before using them. See ExtensionHooks for the full lifecycle.
Renderers
Core decides when output happens; one Extension can decide how. .renderer(select) returns a Renderer for the invocation, or undefined to keep the default:
import { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
export const quiet = defineExtension(defineExtensionId("acme:quiet"))
.flags({ quiet: { type: "boolean" } })
.renderer((ctx) =>
// Drop the action's stdout lines; keep its diagnostics.
ctx.flags.quiet === true ? { text: () => {}, diag: ctx.stderr } : undefined,
);
const app = new Crust("app").extend(quiet).action(({ stdout }) => {
stdout("deployed");
});
console.log((await app.run([])).stdout); // => "deployed"
console.log((await app.run([], { flags: { quiet: true } })).stdout); // => ""textanddiagreceive each line the action or a Context writes withstdout()andstderr(). An Extension's ownctx.stdoutandctx.stderrbypass the renderer, so help and notices print as usual.result, if set, receives the action's return value after the action completes and its.output()schema, if any, validates it, and beforepostRun. Throwing from it fails the invocation.stream, if set, is called once when the action turns out to be an async generator, before its first event, so the renderer knows the invocation streams beforeevent,result, orerror.event, if set, receives each value the action yields, as it is yielded and before the caller'sonEventoption. Throwing from either closes the generator and fails the invocation. Withoutevent, events are not printed.error, if set, replaces Core'sError: messagerendering in.execute()when noonErrorhook claimed the failure. Core calls it at most once, never under.run(), where callers readoutcome.error, and never for a cancellation.cleanup, if set, replaces Core'sCleanup failed: messagelines in.execute(): Core calls it once for each cleanup failure that follows an already-rendered failure or happens while a cancellation unwinds; cleanups that fail together are passed one by one, not as theirSuppressedErrororAggregateError. If it throws, Core writes its own lines, so a cleanup failure is never hidden. Exit codes don't change.
Core calls select once per invocation, after every setup and before any flag handler, so it sees what setups bound. It may be async, for example to import() a formatter only when it is needed; Core awaits it. Output the action side writes earlier, such as from a Context a setup pulled, waits and then goes through the chosen renderer; without a .renderer() in the application, it is written immediately. A setup failure still goes through the chosen renderer: Core calls select after it, since flags are already bound, and falls back to the default if select fails too. A selector or renderer that throws there never replaces the setup failure. Routing and argv syntax errors happen before flags are bound and render by default. Only one Extension in an application may set .renderer(); a second is a DEFINITION error when the app prepares.
Dependency injection
Extensions can install Contexts and use them from hooks:
import { Crust, defineContext, defineExtension, defineExtensionId } from "@crustjs/core";
const logger = defineContext("logger").setup(({ stdout }) => ({ info: stdout }));
export const logging = defineExtension(defineExtensionId("acme:logging"))
.provide(logger())
.use(logger)
.postRun(async ({ ctx }, outcome) => {
(await ctx.).info(`outcome: ${outcome.status}`);
});
const app = new Crust("my-cli").extend(logging).action(({ stdout }) => stdout("ready"));
await app.execute();$ my-cli
ready
outcome: completed.provide() installs Context instances across the command tree; .use() declares which factories the hooks need. An Extension that supplies and reads a Context needs both. To use an app-supplied Context instead, omit the Extension's .provide() and call .provide(logger()) on the app before .extend(logging). That order is a TypeScript rule: the app checks an Extension's dependencies when it prepares, so at runtime the reverse order works too.
A provided Context's documentation sections appear once on the root, not on every command.
A provided Context's flags are parsed by the root, its inline .command() children, and the commands that .use() the Context or the Extension:
const confirm = defineContext("confirm")
.flags({ yes: { type: "boolean", description: "Skip the confirmation" } })
.setup(({ flags }) => ({ skip: flags.yes === true }));
const confirmation = defineExtension(defineExtensionId("acme:confirmation")).provide(confirm());
const remove = defineCommand("remove", (command) =>
command
.use(confirm)
.action(async ({ ctx, stdout }) => {
stdout((await ctx.confirm).skip ? "removed" : "pass --yes to remove");
}),
);
export const list = defineCommand("list", (command) =>
command.action(({ stdout }) => stdout("a b")),
);
export const app = new Crust("my-cli").extend(confirmation).add(remove, list);$ my-cli remove --yes
removed
$ my-cli list --yes
Error: Unknown flag "--yes"When the Extension's own hooks .use() the Context, every command parses its flags, because hooks run on every command. With .extend(audited), my-cli list --yes is accepted:
export const audited = confirmation
.use(confirm)
.postRun(async ({ ctx, stderr }, outcome) => {
// A handled invocation, such as --help, skipped flag validation.
if (outcome.status !== "completed") return;
if ((await ctx.confirm).skip) stderr("confirmation skipped with --yes");
});A flag-owning Context requires successful validation. Use it in the action, or in postRun after validation has succeeded—not after an Extension handled the invocation early and skipped validation.
Use an Extension's Contexts from a command
A reusable command can pass an Extension, or its factory, to .use() to use every Context that Extension provides:
import {
Crust,
defineCommand,
defineContext,
defineExtension,
defineExtensionId,
} from "@crustjs/core";
const clock = defineContext("clock").setup(() => ({ now: () => "12:00" }));
export const time = defineExtension(defineExtensionId("acme:time"))
.provide(clock())
.factory((extension) => extension);
const now = defineCommand("now", (command) =>
command.use(time).action(async ({ ctx, stdout }) => {
stdout((await ctx.clock).now());
}),
);
const app = new Crust("my-cli").extend(time()).add(now);
await app.execute();
// Checked but not rendered: the guide states that a missing Extension is a type error.
function unextended() {
// @ts-expect-error `now` uses `time`, which this app does not extend
return new Crust("my-cli").add(now);
}
void unextended;$ my-cli now
12:00.use(time) and .use(time()) both declare the Contexts time() provides, here ctx.clock, so the command does not import the Context factory, and it parses the flags they own. TypeScript requires those Contexts where the command is added, as for .use(clock); when the app prepares, Core throws a DEFINITION error (missing-extension) if it does not extend that Extension.
Required root metadata
An Extension that needs version can require it with defineExtension<"version">(id):
import { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
export const stamp = defineExtension<"version">(defineExtensionId("acme:stamp")).preRun((ctx) => {
ctx.stdout(`version ${ctx.rootCommand.meta.}`);
});
// new Crust("my-cli").extend(stamp);
// Type error (FIX_ROOT_META): Extension requires root metadata "version"; pass it to new Crust(name, { version })
const app = new Crust("my-cli", { version: "1.2.3" }).extend(stamp).action(() => {});
console.log((await app.run([])).stdout); // => "version 1.2.3"TypeScript rejects .extend(stamp) unless the root declares version. Bun and Node builds (bun build, or crust build for those runtimes) skip this check, so run tsc --noEmit first.
If a factory argument can supply the value instead, build the factory without a metadata requirement and annotate it with overloads. Only calls that omit the argument then require root metadata. Like the check above, TypeScript enforces this and the runtime does not repeat it, so in code that type-checks the implementation can rely on one of the two being set:
import {
Crust,
defineExtension,
defineExtensionId,
type Extension,
type ExtensionId,
} from "@crustjs/core";
type Stamp<MetaKeys extends "version"> = Extension<{}, [], {}, [], MetaKeys>;
export interface StampFactory {
(version: string): Stamp<never>; // an explicit value needs no root metadata
(version?: string): Stamp<"version">; // an omitted value requires it
readonly id: ExtensionId;
}
export const stamp: StampFactory = defineExtension(defineExtensionId("acme:stamp")).factory(
(extension, version?: string) =>
extension.preRun((ctx) => {
// The overloads guarantee root `version` whenever `version` is omitted.
const resolved = version ?? ctx.rootCommand.meta.version!;
ctx.stdout(`version ${resolved}`);
}),
);
new Crust("my-cli").extend(stamp("1.2.3"));
new Crust("my-cli", { version: "1.2.3" }).extend(stamp());
// new Crust("my-cli").extend(stamp());
// Type error: the root metadata does not guarantee "version".version(), updateNotifier(), and completion() use this pattern.
Command sections
Add documentation with .sections(). command: [] targets the root; command: ["deploy"] would target a deploy command:
import { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
import { help } from "@crustjs/extensions";
export const guidance = defineExtension(defineExtensionId("acme:guidance")).sections(() => [
{
command: [],
title: "Environment",
body: "Set DEPLOY_TOKEN before running.",
},
]);
const app = new Crust("my-cli").extend(guidance, help()).action(() => {});
await app.execute();my-cli --help includes:
Environment:
Set DEPLOY_TOKEN before running.The callback runs when the application prepares and receives a snapshot containing contributed commands and flags, but no Extension-contributed sections. Commands it reads are built on demand, so a callback that reads only root metadata leaves the rest of the tree unbuilt. See ExtensionSectionContribution for validation and audience rules.
Build hooks
A build hook returns files; Crust writes them. This one saves the frozen Command Snapshot as JSON:
import { Crust, defineExtension, defineExtensionId } from "@crustjs/core";
export const manifest = defineExtension(defineExtensionId("acme:manifest")).build(
({ snapshot }) => [
{ path: "acme-manifest/manifest.json", content: JSON.stringify(snapshot) },
],
);
export const app = new Crust("my-cli").extend(manifest).action(() => {});
await app.execute();During crust build:
Preparing Command Snapshot for my-cli...
acme:manifest 1 file acme-manifest/manifest.jsonPut files under an Extension-specific directory such as acme-manifest/. Loose files at the root of .crust/artifacts/ are not copied into staged packages. Return file contents rather than writing into the build output yourself.
Hooks run in registration order. Section callbacks refresh after each hook, so later hooks can see sections based on earlier artifacts. For example, register skill() before man() to list packaged skills in the man page. See ExtensionBuildContext and BuildFile for output and path rules.
Section consumers
The built-in help, man, schema, and skill Extensions render sections for different audiences. A custom generator can do the same with visibleSectionsFor():
import { Crust, defineCommand, defineExtension, defineExtensionId } from "@crustjs/core";
import { visibleSectionsFor } from "@crustjs/core/tooling";
const WEB_DOCS = defineExtensionId("acme:web-docs");
export const webDocs = defineExtension(WEB_DOCS).build(({ snapshot }) => {
const lines = visibleSectionsFor(snapshot, WEB_DOCS).flatMap(({ , }) => [
`# ${[snapshot.meta.name, ...path].join(" ")}`,
...sections.map((s) => `## ${s.title}\n${s.body}`),
]);
return [{ path: "web-docs/docs.md", content: lines.join("\n\n") }];
});
const deploy = defineCommand(
"deploy",
{
sections: [
{ title: "Safety", body: "Run preview first." },
{ title: "Screenshots", body: "", only: [webDocs] },
],
},
(command) => command.action(() => {}),
);
const app = new Crust("my-cli").add(deploy).extend(webDocs);
await app.execute();The generated web-docs/docs.md contains:
# my-cli deploy
## Safety
Run preview first.
## Screenshots
only: [webDocs] keeps the Screenshots section out of other consumers, such as help. Use except to exclude consumers instead; both accept Extension values or ids.
visibleSectionsFor(snapshot, id) selects visible commands and merges same-title sections for that consumer. For one command, use sectionsFor(sections, id). Both come from @crustjs/core/tooling.