getCommandContext

function

Returns the CommandContext for the currently executing command.

Must be called from within a command handler (not during builders or middleware).

Runtime safety

When called with a CLI instance, getCommandContext validates at runtime
that the instance is part of the active command chain — the root app,
any ancestor on the chain, or the currently-running subcommand. If you
pass a CLI that isn't in the chain (a sibling command, an unrelated app,
a descendant that didn't run), it throws with a descriptive error. This
catches the common bug where the wrong instance is passed as a type
witness and inject() silently returns the wrong providers.

Two ways to reach subcommand-typed access

Option 1 — from the root, walk by name:

const ctx = getCommandContext(app);
const buildCtx = ctx.getChildContext('build');
console.log(buildCtx.args.target);

Option 2 — pass a composed subcommand reference directly, skipping
the getChildContext hop:

import { build } from './build'; // standalone CLI composed into app
const ctx = getCommandContext(build);
console.log(ctx.args.target);

Both forms are runtime-safe. Option 2 is only typed if the subcommand
reference carries the full TProviders — i.e. the subcommand is declared
inside the parent's .command('name', { builder, handler }) call, where
TypeScript can thread parent providers into the builder's cmd. A
standalone cli('build', ...) reference doesn't see inherited providers
in its type; use Option 1 for that shape.

Type witness (no instance)

The parameterless overload returns a context typed by an explicit generic
— useful when you can't get a live reference to the CLI from where the
handler is written. This form has no runtime safety: the T type
parameter is trusted as-is, so a mismatched generic silently returns a
context typed for a CLI that isn't running. Prefer passing the CLI
instance whenever feasible.

Parameters

NameTypeDescription
cliTCLI instance used as both a type witness for inference and a runtime identity check. Required for runtime-safe usage.

Type Parameters

Examples

import { getCommandContext } from 'cli-forge/context';
import { app } from './cli';

const ctx = getCommandContext(app);
const db = ctx.inject('db');