ArgBuilder
Immutable positional argument schema builder.
The type parameter C is a phantom that tracks the value type, presence, and variadic state through the fluent chain. Each modifier returns a new builder — the original is never mutated.
- Import:
@kjanat/dreamcli - Export kind: class
- Declared in:
src/core/schema/arg.ts - Source link:
src/core/schema/arg.ts:1211
Signatures
class ArgBuilder<C extends ArgConfig> {}Members
Constructors
constructor
Create an arg builder from a pre-built schema descriptor.
constructor(schema: ArgSchema);Methods
complete
Compute value candidates when the user requests shell completion.
The callback runs without the command action, middleware, prompts, or config discovery. Return complete values; DreamCLI filters by prefix. Candidates containing control characters are omitted.
complete(handler: CompletionHandler): ArgBuilder<WithoutArgElementEligibility<C>>;required
Mark the arg as required (this is the default for positional args). Produces an error if no value resolves from any configured source (CLI → stdin → env → config → prompt → default).
required(): ArgBuilder<WithArgPresence<C, "required">>;optional
Mark the arg as optional. Handlers receive undefined when absent.
optional(): ArgBuilder<WithArgPresence<C, "optional">>;default
Provide a default value. The arg becomes "always present" — handlers will never see undefined.
The generic constraint ArgDefaultValue ensures the default matches what the arg resolves to: an array for a variadic arg, a record for a keyValue one, and a single value otherwise.
Resolution order when extra sources are configured: CLI → stdin → env → config → prompt → default.
default<V extends ArgDefaultValue<C>>(value: V, options?: DefaultValueOptions): ArgBuilder<WithArgPresence<C, "defaulted">>;variadic
Mark this arg as variadic — it consumes all remaining positional arguments. The inferred type becomes T[].
A variadic arg is the last positional a command can declare. Registering another positional after it throws INVALID_BUILDER_STATE from .arg() and from createCommandSchema().
variadic(): ArgBuilder<WithVariadic<C>>;separator
Split each positional token on a separator before element coercion, so mycli build a,b c collects ['a', 'b', 'c'] into a variadic arg.
The separator is the CLI policy alone. Env values split on ',' and the stdin buffer on line terminators unless .split() says otherwise.
Available on an arg that aggregates, so call it after .variadic() or on arg.keyValue().
separator(this: ArgBuilder<C & { variadic: true; }> | ArgBuilder<C & { argKind: "keyValue"; }>, value: string): ArgBuilder<C>;split
Set how each source decodes into elements.
CLI tokens accept 'whole' and a delimiter; env values also accept 'json'; the stdin buffer accepts every format, including 'lines'. The strings 'whole', 'lines', and 'json' name their format, and every other string is the delimiter to split on. A source left out keeps what it already had, or its default: whole CLI tokens, comma-delimited env values, line-delimited stdin. For stdin, 'whole' passes the complete buffer to a string element, including its final line terminator.
Available on an arg that aggregates, so call it after .variadic() or on arg.keyValue().
split(this: ArgBuilder<C & { variadic: true; }> | ArgBuilder<C & { argKind: "keyValue"; }>, options: SplitOptions): ArgBuilder<C>;unique
Deduplicate the resolved values of a variadic arg, preserving first-seen order. Applied after all sources resolve, using SameValueZero semantics.
Available on a variadic arg of a list kind, so call it after .variadic().
unique(this: ArgBuilder<C & { variadic: true; argKind: ListArgKind; }>, value?: boolean): ArgBuilder<C>;duplicateKeys
Set how a repeated key combines.
duplicateKeys(this: ArgBuilder<C & { argKind: "keyValue"; }>, policy: DuplicateKeys): ArgBuilder<C>;standard
Validate the resolved value with a Standard Schema v1 validator.
On a single-value builder the validator sees each value; on a builder that already aggregates (.variadic() or arg.keyValue()) it sees the completed array or record, after every element passed its own validator.
The builder this is called on is what decides, so where the call sits relative to .variadic() chooses between the two.
standard(schema: StandardSchemaV1): ArgBuilder<C>;stdin
Let this arg read its value from piped stdin.
An explicit - in the arg's slot is CLI-sourced with bytes from stdin and keeps CLI precedence. An absent positional takes the stdin fallback stage, which sits between CLI and env, so an arg set in the environment still reads stdin and stdin wins. The whole buffer becomes the value, byte for byte for a string arg; every other kind drops the single line terminator a pipe appends before decoding, and { trim: true } drops it for a string arg too.
On an arg that aggregates, a - among the tail tokens splices what the buffer decodes to into that position, so mycli build a - b over 'x\ny\n' collects ['a', 'x', 'y', 'b']. Each - stands for the whole source, so two of them splice the buffer twice. A - typed beside other tokens with nothing piped fails with MISSING_STDIN; a tail of nothing but - falls through to the later sources.
A stdin-enabled arg cannot receive a literal - as its value, since the token names the source.
One command may declare a single exclusive stdin consumer; pass { consume: 'broadcast' } on every input that should share the buffer.
stdin(options?: StdinOptions): ArgBuilder<WithoutArgElementEligibility<C>>;env
Bind to an environment variable.
When the arg is not provided on the CLI or by stdin, the resolver checks this env var before config, prompt, and the default value. The env string is coerced to the arg's declared kind (passthrough for strings, parsed for numbers, run through parseFn for custom args).
Resolution order when extra sources are configured: CLI → stdin → env → config → prompt → default.
Help output shows [env: VAR] next to the arg description.
Under a CLI-wide namespace (CLIBuilder.envPrefix()) the name is relative: .env('TARGET') in cli('foo').envPrefix() reads FOO_TARGET. Pass { absolute: true } to read the name exactly as written.
Bind to an indexed family of environment variables, read as one env source; see FlagBuilder.env() for the count and template rules. A value family needs a variadic arg (call .variadic() first), and a fields family a Standard Schema arg.custom().
Bind to an environment variable derived from this input's registered name (api-token and apiToken → API_TOKEN), relative to the CLI namespace unless { absolute: true }.
env(varName: string, options?: EnvOptions): ArgBuilder<WithoutArgElementEligibility<C>>;
env(binding: IndexedEnvBinding, options?: EnvOptions): ArgBuilder<WithoutArgElementEligibility<C>>;
env(options?: EnvOptions): ArgBuilder<WithoutArgElementEligibility<C>>;config
Bind to a dotted config path.
The config value is read after CLI, stdin, and env, and is coerced to the arg's declared kind the same way a flag's config value is.
config(path: string): ArgBuilder<WithoutArgElementEligibility<C>>;prompt
Attach interactive prompt configuration.
When CLI, stdin, env, and config all produce nothing, the prompt engine uses this config to ask the user. In non-interactive contexts the prompt is skipped and resolution falls through to the default or the missing-arg error.
The compatible kinds follow the value and the cardinality: a variadic arg takes the multiselect a flag.array() takes, and every other arg takes what its kind takes on the flag surface.
prompt(config: AllowedArgPromptConfig<C>): ArgBuilder<WithoutArgElementEligibility<C>>;sensitive
Mark this input's values as sensitive.
Sensitive defaults are omitted from definition and input JSON Schemas and from automatic help text. A custom default description remains safe to show.
sensitive(value?: boolean): ArgBuilder<WithoutArgElementEligibility<C>>;describe
Human-readable description shown in help output.
describe(description: HelpDescription): ArgBuilder<WithoutArgElementEligibility<C>>;group
Place this argument in a named arguments section in command help.
group(name: string): ArgBuilder<WithoutArgElementEligibility<C>>;deprecated
Mark this arg as deprecated.
When used, a warning is emitted to stderr. Help text shows [deprecated] or [deprecated: <reason>].
Does not change the arg's type-level config — it's metadata only.
deprecated(message?: string): ArgBuilder<WithoutArgElementEligibility<C>>;int
Require an integer value. Composes with other numeric constraints.
int(this: ArgBuilder<C & { argKind: "number"; }>, value?: boolean): ArgBuilder<C>;min
Set an inclusive lower bound. Composes with other numeric constraints; a later call overrides an earlier min (including one from the options object).
min(this: ArgBuilder<C & { argKind: "number"; }>, value: number): ArgBuilder<C>;max
Set an inclusive upper bound. Composes with other numeric constraints; a later call overrides an earlier max.
max(this: ArgBuilder<C & { argKind: "number"; }>, value: number): ArgBuilder<C>;finite
Require (or, with false, allow) a finite value. Finiteness is enforced by default, so this is mainly used as .finite(false) to re-allow Infinity / -Infinity.
finite(this: ArgBuilder<C & { argKind: "number"; }>, allow?: boolean): ArgBuilder<C>;nonEmpty
Reject empty strings. Composes with other string constraints.
nonEmpty(this: ArgBuilder<C & { argKind: "string"; }>, value?: boolean): ArgBuilder<C>;minLength
Set an inclusive minimum length (UTF-16 code units). Composes with other string constraints; a later call overrides an earlier minLength.
minLength(this: ArgBuilder<C & { argKind: "string"; }>, value: number): ArgBuilder<C>;maxLength
Set an inclusive maximum length (UTF-16 code units). Composes with other string constraints; a later call overrides an earlier maxLength.
maxLength(this: ArgBuilder<C & { argKind: "string"; }>, value: number): ArgBuilder<C>;pattern
Require the value to match a regular expression. Anchor with ^/$ for full-string matching. Composes with other string constraints.
pattern(this: ArgBuilder<C & { argKind: "string"; }>, value: RegExp): ArgBuilder<C>;Examples
// Full command with multiple args and modifiers
import { command, arg } from '@kjanat/dreamcli';
command('deploy')
.arg('target', arg.string()
.env('DEPLOY_TARGET')
.describe('Deploy target'))
.arg('port', arg.number()
.env('PORT')
.default(3000)
.describe('Port number'))
.arg('files', arg.string()
.variadic()
.optional()
.describe('Extra config files'))
.action(({ args }) => {
args.target; // string (required, from CLI or $DEPLOY_TARGET)
args.port; // number (defaulted, from CLI, $PORT, or 3000)
args.files; // string[] (optional variadic)
});// Type inference
const target = arg.string();
type T = InferArg<typeof target>; // string
const opt = arg.string().optional();
type O = InferArg<typeof opt>; // string | undefined
const files = arg.string().variadic();
type F = InferArg<typeof files>; // string[]