Skip to content

flex-development/kronk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

kronk

ci github release npm npm downloads install size codecov module type: esm license conventional commits typescript vitest yarn

✨ a command line builder ✨

Contents

run-the-command-kronk

What is this?

kronk is a utility for building command-line applications in node.js and bun.

Install

This package is ESM only.

With yarn:

yarn add @flex-development/kronk
See Git - Protocols | Yarn Β for info regarding installing from Git.

With bun:

bun add @flex-development/kronk
See bun add for more details.

Use

TODO: use

Creating a program

kronk exports a global program object convenient for quick programs. This is used in the examples throughout this README for brevity.

import { program } from '@flex-development/kronk'

For larger programs using kronk in multiple ways, including unit testing, a Command should be created.

import { Command } from '@flex-development/kronk'
const program: Command = new Command()

Options

Options are defined with the .option() and .options() methods, which also serve as documentation for the options. Each option can have at most 2 flags, typically one long flag and one short or shortish (e.g. -w, --ws) flag. Flags can be separated by commas (,), pipes (|), or spaces ( ).

An option and its option-argument can be separated by an equal sign (=) or spaces ( ). A short option (i.e. -p) and its option-argument can also be combined.

serve --port 80
serve --port=80
serve -p 80
serve -p80
serve -p=80

Options on the command line are not positional, and can be specified before or after command-arguments.

serve --port=80 ./server.mts
serve ./src/main.mts -p8080

If a non-option (i.e. -13) looks like an option because it starts with a hyphen (-), a delimiter (--) can be used to demarcate the command-argument from an option.

clamp -M3 -m-1 -- -13

Parsed options can be accessed by calling .opts<T>() on a Command object, and are passed to the command's action handler. Multi-word options such as --template-engine are camelCased, becoming program.opts().templateEngine, or can be configured to be converted using snake_case, becoming program.opts().template_engine.

There are additional, related routines for when .opts<T>() is not enough:

API

Argument(info)

A command argument (class).

Extends

Signatures

  • constructor(info: ArgumentInfo | string)
  • constructor(info: string, data?: ArgumentData | null | undefined)

Parameters

Argument#id

string

The argument syntax id.

Argument#syntax

ArgumentSyntax

The normalized argument syntax string.

Argument#toString()

Get the argument as a human-readable string.

Returns

(string) String representation of this argument

Command([info])

A command (class).

Extends

Signatures

  • constructor(info: CommandInfo | string)
  • constructor(info: string, data?: CommandData | null | undefined)

Parameters

Command#action([action])

Get or set the command action callback.

Overloads
  • action(action: Action<any> | null | undefined): this
  • action<Opts extends OptionValues = OptionValues, Args extends any[] = any[]>(): Action<Opts, Args>
Type Parameters
  • Opts (OptionValues, optional) β€” parsed command options
  • Args (any[], optional) β€” parsed command arguments
Parameters
  • action (Action<any> | null | undefined) β€” the callback to fire when the command is ran
Returns

(Action<Opts, Args> | this) The command action callback or this command

Command#addArgument(argument)

Add a prepared argument.

Parameters
  • argument (Argument) β€” the argument instance to add
Returns

(never | this) this command

Throws

(KronkError) If the last registered argument is variadic

Command#addCommand(subcommand)

Add a prepared subcommand.

πŸ‘‰ Note: See command for creating an attached subcommand that inherits settings from its parent.

Parameters
  • subcommand (Command) β€” the command instance to add
Returns

(never | this) this command

Throws

(KronkError) If subcommand does not have a valid name or a subcommand with the same name or alias as subcommand already exists

Command#addOption(option)

Add a prepared option.

Parameters
  • option (Option) β€” the option instance to add
Returns

(never | this) this command

Throws

(KronkError) If an option with the same long or short flag as option already exists

Command#alias([alias])

Get an alias for the command or add a command alias.

πŸ‘‰ Note: This method can be called more than once to add multiple aliases.

Overloads
  • alias(alias: string): this
  • alias(): CommandName
Parameters
  • alias (string) β€” an alias for the command
Returns

(CommandName | this) Command alias or this command

Command#aliases([aliases])

Get or add aliases for the command.

Overloads
  • aliases(aliases: List<string> | string | null | undefined): this
  • aliases(): Set<string>
Parameters
  • aliases (List<string> | string | null | undefined) β€” an alias, or list of aliases, for the command
Returns

(Set<string> | this) List of command aliases or this command

Command#ancestors()

Get a list of ancestor commands.

The first command is the parent of this command, and the last is the greatest grandparent of this command.

Returns

(Command[]) List of ancestor commands

Command#args

any[]

Parsed command-line arguments.

Command#argument(info[, data])

Define an argument for the command.

Overloads
  • argument(info: ArgumentInfo | string): this
  • argument(info: string, data?: ArgumentData | null | undefined): this
Parameters
  • info (ArgumentInfo | string) β€” argument info or syntax
  • data (ArgumentData, optional) β€” additional argument info
Returns

(this) this command

Command#arguments([infos])

Get a list of command arguments or batch define arguments for the command.

Overloads
  • arguments(infos: List<ArgumentInfo | string> | string): this
  • arguments(): Argument[]
Parameters
Returns

(Argument[] | this) List of command arguments or this command

Command#argv

string[]

Raw command-line arguments.

Command#command(info[, data])

Define a subcommand.

Overloads
  • command(info: SubcommandInfo | string): Command
  • command(info: string, data?: CommandData | null | undefined): Command
Parameters
Returns

(Command) Subcommand instance

Command#commands([infos])

Get a subcommand map or batch define subcommands for the command.

Overloads
  • commands(infos: SubcommandsInfo): this
  • commands(): Map<string, Command>
Parameters
Returns

(Map<string, Command> | this) Subcommand map or this command

Command#copyInheritedSettings(parent)

Copy settings that are useful to have in common across parent and its subcommands.

πŸ‘‰ Note: This method is used internally via command so subcommands can inherit parent settings.

Parameters
  • parent (Command) β€” the parent command to copy settings from
Returns

(this) this command

Command#createArgument(info[, data])

Create a new unattached argument.

Overloads
  • createArgument(info: ArgumentInfo | ArgumentSyntax): Argument
  • createArgument(info: ArgumentSyntax, data?: ArgumentData | null | undefined): Argument
Parameters
Returns

(Argument) New argument instance

Command#createCommand([info][, data])

Create a new unattached command.

Overloads
  • createCommand(info?: CommandInfo | string | null | undefined): Command
  • createCommand(info: string, data?: CommandData | null | undefined): Command
Parameters
Returns

(Command) New command instance

Command#createOption(info[, data])

Create a new unattached option.

Overloads
  • createOption(info: Flags | OptionInfo): Option
  • createOption(info: VersionOptionInfo): VersionOption
  • createOption(info: Flags, data?: OptionData | null | undefined): Option
Parameters
Returns

(Option | VersionOption) New option instance

Command#default

boolean

Whether the command is the default subcommand of its parent.

Command#defaultCommand

Command | null | undefined

The default command.

Command#done([done])

Get or set the command done callback.

Overloads
  • done(done: Action<any> | null | undefined): this
  • done<Opts extends OptionValues = OptionValues, Args extends any[] = any[]>(): Action<Opts, Args>
Type Parameters
  • Opts (OptionValues, optional) β€” parsed command options with globals
  • Args (any[], optional) β€” parsed command arguments
Parameters
  • done (Action<any> | null | undefined) β€” the callback to fire after the command is ran
Returns

(Action<Opts, Args> | this) The command done callback or this command

Command#emit(event)

Emit an event.

Parameters
Returns

(boolean) true if event has listeners, false otherwise

Command#emitOption(option, value, source[, flag])

Emit a parsed option event.

Parameters
  • option (Option) β€” the command option instance
  • value (RawOptionValue) β€” the raw option value
  • source (OptionValueSource) β€” the source of the raw option value
  • flag? (Flags, optional) β€” the parsed option flag
Returns

(boolean) true if event has listeners, false otherwise

Command#error(info)

Display an error message and exit.

Parameters
Returns

(never) Never, exits erroneously

Command#example(info[, prefix])

Add an example for the command.

πŸ‘‰ Note: This method can be called more than once to add multiple examples.

Overloads
  • example(info: ExampleInfo | string): this
  • example(info: string, prefix?: string | null | undefined): this
Parameters
  • info (ExampleInfo | string) β€” example info or text
  • prefix (string | null | undefined) β€” the example text prefix
Returns

(this) this command

Command#examples([examples])

Get or add examples for the command.

Overloads
  • examples(examples: ExamplesData | null | undefined): this
  • examples(): ExampleInfo[]
Parameters
  • examples (ExamplesData | null | undefined) β€” example info, example text, or a list of such
Returns

(ExampleInfo[] | this) List of examples or this command

Command#exit([e])

Exit the process.

πŸ‘‰ Note: The exit code (process.exitCode) is set, but process.exit is not called. To change this behavior, override the exit callback using exiter.

Overloads
  • exit(e: CommandError | KronkError): never
  • exit(e?: null | undefined): undefined
Parameters
Returns

(never | undefined) Nothing

Throws

(KronkError) If e is an unhandled error after calling the command exit callback

Command#exiter([exit])

Get or set the exit callback.

Overloads
  • exiter(exit: Exit | null | undefined): this
  • exiter(): Exit
Parameters
  • exit (Exit | null | undefined) β€” the callback to fire on process exit
Returns

(Exit | this) Command exit callback or this command

Command#findCommand(ref)

Find a command with a name or alias matching ref.

Parameters
Returns

(Command | this | undefined) Command with a name or alias matching ref

Command#findOption(flag[, direction])

Find an option with a flag matching flag.

Options known to this command and its (defaultCommand) are searched by default. Set direction to 0 to only search for options known to the current command.

Parameters
  • flag (string | null | undefined) β€” the option flag to match
  • direction (0 | null | undefined, optional) β€” the direction to search for options
Returns

(Option | undefined) Option with the long or short flag flag

Command#helpCommand([help])

Get or configure the help subcommand.

Overloads
  • helpCommand(help: HelpCommandData | null | undefined): this
  • helpCommand<T extends Command = Command>(): T | null
Type Parameters
  • T (Command) β€” help subcommand instance
Parameters
  • help (HelpCommandData | null| undefined) β€” subcommand instance, subcommand info, false to disable the help subcommand, or any other allowed value to use the default configuration
Returns

(T | this | null) Help subcommand or this command

Command#helpOption([help])

Get or configure the help option.

Overloads
  • helpOption(help: HelpOptionData | null | undefined): this
  • helpOption<T extends Option = Option>(): T | null
Type Parameters
  • T (Option) β€” help option instance
Parameters
  • help (HelpOptionData | null| undefined) β€” option flags, option instance, option info, false to disable the help option, or any other allowed value to use the default configuration
Returns

(T | this | null) Help option or this command

Command#helpUtility([util])

Get or set the help text utility.

Overloads
  • helpUtility(util: Help | null | undefined): this
  • helpUtility<T extends Help>(): T
Type Parameters
  • T (Help) β€” help text utility instance
Parameters
  • util (Help | null| undefined) β€” the help text utility
Returns

(T | this) Help text utility or this command

Command#id([name])

Get or set the name of the command.

Overloads
  • id(name: CommandName | undefined): this
  • id(): CommandName
Parameters
  • name (CommandName | undefined) β€” the name of the command
Returns

(CommandName | this) The name of this command or this command

Command#logger

Logger

Logger instance.

Command#on<T>(event, listener[, options])

Register an event listener.

Type Parameters
  • T (KronkEvent) β€” the event being listened for
Parameters
  • event (T['id']) β€” the name of the event being listened for
  • listener (KronkEventListener<T>) β€” the event listener
  • options (OnOptions, optional) β€” event listening options
Returns

(undefined) Nothing

Command#option(info[, data])

Define an option for the command.

Overloads
  • option(info: Flags | OptionInfo): this
  • option(info: Flags, data?: OptionData | null | undefined): this
Parameters
Returns

(this) this command

Command#optionPriority([priority])

Get or set the strategy to use when merging global and local options.

Overloads
  • optionPriority(priority: OptionPriority | null | undefined): this
  • optionPriority(): OptionPriority
Parameters
  • priority (OptionPriority | null| undefined) β€” the strategy to use when merging options
Returns

(OptionPriority | this) Option merge strategy or this command

Command#optionValue(key[, value][, source])

Get or set an option value.

Overloads
  • optionValue(key: Option['key'], value: unknown, source?: OptionValueSource | null | undefined): this
  • optionValue<T>(key: Option['key']): T
Type Parameters
  • T (any) β€” parsed option value type
Parameters
  • key (Option['key']) β€” option key
  • value (unknown) β€” the parsed option value to store
  • source (OptionValueSource | null | undefined) β€” the source of the original option value
Returns

(T | this) Stored option value or this command

Command#optionValueSource(key[, source])

Get or set an option value source.

Overloads
  • optionValueSource(key: Option['key'], source: OptionValueSource | null | undefined): this
  • optionValueSource(key: Option['key']): OptionValueSource | null | undefined
Parameters
Returns

(OptionValueSource | this | null | undefined) Option value source for key or this command

Command#options([infos])

Get a list of command options or batch define options for the command.

Overloads
  • options(infos: List<Flags | OptionInfo>): this
  • options(): Option[]
Parameters
Returns

(Option[] | this) List of command options or this command

Command#opts<T>()

Get a record of local option values.

Type Parameters
Returns

(T) Local option values

Command#optsWithGlobals<T>()

Get a record of global and local option values.

πŸ‘‰ Note: Local options overwrite global options by default. Prioritize global options (i.e. cmd.optionPriority('global')) to change this behavior.

Type Parameters
Returns

(T) Merged option values

Command#parent

Command | null | undefined

The parent command.

Command#parse([argv][, options])

Parse argv, setting options and invoking commands when defined.

The default expectation is that the arguments are from node and have the application as argv[0] and the script being run in argv[1], with user parameters after that.

πŸ‘‰ Note: If the action handler is async, parseAsync should be used instead.

Parameters
  • argv (List<string> | null | undefined, optional) β€” list of command-line arguments
  • options (ParseOptions | null | undefined, optional) β€” options for parsing argv
Returns

(Command | this) The command that was run

Command#parseAsync([argv][, options])

Asynchronously parse argv, setting options and invoking commands when defined.

Otherwise the same as parse.

πŸ‘‰ Note: If the action handler is async, this method should be used instead of parse.

Command#process

Process

Information about the current process.

Command#snapshot()

Get a snapshot of this command.

Returns

(CommandSnapshot) Command snapshot object

Command#summary([summary])

Get or set the command summary.

Overloads
  • summary(summary: string | null | undefined): this
  • summary(): string | null
Parameters
  • summary (string | null| undefined) β€” the command summary
Returns

(string | this | null) Summary of this command or this command

Command#toString()

Get the command as a human-readable string.

Returns

(string) String representation of this argument

Command#unknown

UnknownStrategy

The strategy for handling unknown command-line arguments.

Command#unknowns([strategy])

Get or set the strategy for handling unknown command-line arguments.

Overloads
  • unknowns(strategy: UnknownStrategy | null | undefined): this
  • unknowns(): UnknownStrategy
Parameters
  • strategy (UnknownStrategy | null| undefined) β€” the strategy for handling unknown command-line arguments
Returns

(UnknownStrategy | this) Unknown command-line argument strategy or this command

Command#usage([usage])

Get or set the command usage description.

Overloads
  • usage(usage: UsageData | null | undefined): this
  • usage(): UsageInfo
Parameters
  • usage (UsageData | null| undefined) β€” command usage data
Returns

(UsageInfo | this) Command usage info or this command

Command#version([version])

Get or set the command version.

πŸ‘‰ Note: When setting the command version, this method auto-registers the version option with the flags -v | --version. No cleanup is performed when this method is called with different flags (i.e. info as a string or info.flags).

Overloads
  • version(version: VersionData | null | undefined): this
  • version<T extends string = string>(): T | null
Type Parameters
  • T (string, optional) β€” command version type
Parameters
  • version (VersionData | null| undefined) β€” command version, version option instance, or version option info
Returns

(T | this | null) Command version or this command

CommandError(info)

A command error (class).

Extends

Parameters

CommandError#command

Command | null

The command where the error originated.

CommandError#snapshot()

Get a snapshot of the error.

Returns

(CommandErrorSnapshot) Error snapshot object

Help([options])

Help text utility (class).

Parameters

  • options (HelpTextOptions | null | undefined) β€” options for formating help text

Help#text(cmd)

Generate help text for a command.

Parameters
  • cmd (Command) β€” the command to generate help text for
Returns

(string) Formatted help text

Helpable([info])

A help text candidate (abstract class).

Parameters

Helpable#description([description])

Get or set the candidate description.

The description can be long or short form text, or a URL pointing to more information about the candidate.

Overloads
  • description(description: URL | string | null | undefined): this
  • description(): string
Parameters
  • description (URL | string) β€” candidate description text or a URL pointing to more info
Returns

(string | this) Candidate description or this candidate

Helpable#hidden

boolean

Whether the candidate should not be displayed in help text.

Helpable#hide([hidden])

Remove the candidate from the help text.

Parameters
  • hidden (boolean | null | undefined) β€” whether the candidate should be hidden in help text
    • default: true
Returns

(this) this candidate

KronkError(info)

A command-line error (class).

Extends

  • Error

Signatures

  • constructor(info: KronkErrorInfo | string)
  • constructor(info: string, id?: EmptyString | KronkErrorId | null | undefined, code?: ExitCode | null | undefined)

Parameters

  • info (KronkErrorInfo | string) β€” error info or human-readable description of the error
  • id (EmptyString | KronkErrorId) β€” unique id representing the error
  • code (ExitCode) β€” suggested exit code to use with process.exit

KronkError#additional

string[]

Additional lines to be logged with the error.

KronkError#cause

KronkErrorCause | null | undefined

Info about the cause of the error.

KronkError#code

number

The suggested exit code to use with process.exit.

KronkError#id

KronkErrorId

Unique id representing the error.

KronkError#toJSON()

Get the error as a JSON object.

Returns

(KronkErrorJson) JSON representation of this error

KronkError#toString()

Get the error as a human-readable string.

Returns

(string) String representation of this error

KronkEvent(id)

An event (class).

Parameters

KronkEvent#id

KronkEventName

The unique id representing the event.

KronkEvent#toString()

Get the event as a human-readable string.

Returns

(string) String representation of this event

Option(info)

A command option (class).

Extends

Signatures

  • constructor(info: Flags | OptionInfo)
  • constructor(info: Flags, data?: OptionData | null | undefined)

Parameters

Option#boolean

boolean

Whether the option is a boolean option. Boolean options are options that do not take any option-arguments.

Option#conflicts([conflicts])

Get or set option names that conflict with the option.

Overloads
  • conflicts(conflicts: List<string> | string | null | undefined): this
  • conflicts(): Set<string>
Parameters
  • conflicts (List<string> | string | null | undefined) β€” an option name, or list of option names, that conflict with the option
Returns

(Set<string> | this) List of conflicting option names or this option

Option#env([env])

Get or set the environment variables to check for the value of the option.

Overloads
  • env(env: List<string> | string | null | undefined): this
  • env(): Set<string>
Parameters
  • env (List<string> | string | null | undefined) β€” the name of the environment variable to check, or a list of names, in order of priority, to check
Returns

(string | this) Environment variable names or this option

Option#event

OptionEventName

The event name for the option.

Option#flags

Flags

The normalized option flags string.

Option#id

string

The option id.

Option#implies([implies])

Get or set implied option values.

Implied option values are values that are set on other options when this option is passed, but the implied option is not.

Lone keys (string implies) imply true, i.e. { [implies]: true }.

The option-argument parser will be called for implied values that are strings and string arrays.

Overloads
  • implies(implies: OptionValues | string | null | undefined): this
  • implies<T extends OptionValues>(): T
Type Parameters
Parameters
  • implies (OptionValues | string | null | undefined) β€” the key of an implied option, or a map where each key is an implied option key and each value is the value to use when the option is set but the implied option is not
Returns

(T | this) Map of implied option values or this option

Option#key

string

The option id in a format that can be used an object property key.

Option#long

string | null

The long flag for the option. If null, the short flag will be a non-empty string.

Option#mandate([mandatory])

Specify if the option is mandatory.

Mandatory options must have a value after parsing, which usually means the option must be specified on the command line.

πŸ‘‰ Note: This method is a no-op if mandatory option syntax was used when defining option flags (i.e. new Option('--token <!>')).

Parameters
  • mandatory (boolean | null | undefined, optional) β€” whether the option must have a value after parsing
Returns

(this) this option

Option#mandatory

boolean

Whether the option must have a value after parsing.

Option#optional

boolean

Whether a value is optional when the option is specified.

Option#preset([preset])

Get or set the preset to use when the option is specified without an argument.

The option-argument parser will be called.

Overloads
  • preset(preset: string | null | undefined): this
  • preset<T extends string>(): T | null
Type Parameters
  • T (string) β€” option-argument preset
Parameters
  • preset (string | null | undefined) β€” the option-argument preset
Returns

(T | this | null) The option-argument preset or this option

Option#short

string | null

The short flag for the option. If null, the long flag will be a non-empty string.

Option#toString()

Get the option as a human-readable string.

Returns

(string) String representation of this option

OptionEvent<T>(option, value, source[, flag])

A parsed option event (class).

πŸ‘‰ Note: For options where the source is 'implied', the value may not be a raw option value.

Extends

Signatures

  • constructor(option: T, value: RawOptionValue, source: OptionValueSource, flag?: Flags | null | undefined)
  • constructor(option: T, value: unknown, source: optionValueSource.implied, flag?: Flags | null | undefined)
Type Parameters
  • T (Option, optional) β€” Parsed command option
Parameters
  • option (T) β€” the command option instance
  • value (RawOptionValue) β€” the option value
  • source (OptionValueSource) β€” the source of the option value
  • flag (Flags, optional) β€” the parsed option flag

OptionEvent#flag

Flags | null | undefined

The parsed command option flag.

OptionEvent#id

Option['event']

The option event name.

OptionEvent#option

T

The command option instance.

OptionEvent#source

OptionValueSource

The source of the raw option value.

OptionEvent#value

RawOptionValue

The raw option value.

Parseable([info])

A parse candidate (abstract class).

Parse candidates are the parseable components of commands (e.g. arguments and options).

Parameters

Parseable#choices([choices])

Get or set candidate choices.

Overloads
  • choices(choices: List<string> | null | undefined): this
  • choices<T extends string>(): Set<T>
Type Parameters
  • T (string) β€” candidate choice
Parameters
  • choices (List<string> | null | undefined) β€” list of allowed candidate choices
Returns

(Set<T> | this) List of candidate choices or this candidate

Parseable#default([info])

Get or set the default value configuration.

Overloads
  • default(info: DefaultInfo | null | undefined): this
  • default<T>(): DefaultInfo<T> | undefined
Type Parameters
  • T (any) β€” default value
Parameters
Returns

(DefaultInfo<T> | this | undefined) Default value info or this candidate

Parseable#id

string

The unique id for the candidate (abstract).

Parseable#parser([parser])

Get or set the handler used to parse candidate-arguments.

Overloads
  • parser(parser: ParseArg<any, any> | null | undefined): this
  • parser<T, Value extends RawParseValue = RawParseValue>(): ParseArg<T, Value>
Type Parameters
  • T (any) β€” parse result
  • Value (RawParseValue, optional) β€” the argument or arguments to parse
Parameters
Returns

(ParseArg<T, Value> | this) The candidate-argument parser or this candidate

Parseable#required

boolean

Whether the candidate is required.

Required arguments must have a value after parsing. Required options must have a value supplied when the option is specified.

Parseable#toString()

Get the candidate as a human-readable string (abstract).

Returns

(string) String representation of this candidate

Parseable#variadic

boolean

Whether the candidate can be specified multiple times.

VersionOption(info)

A command version option (class).

Extends

Parameters

VersionOption#version

string

The version of the command.

keid

Default error ids (const enum).

const enum keid {
  argument_after_variadic = 'kronk/argument-after-variadic',
  conflicting_option = 'kronk/conflicting-option',
  duplicate_option = 'kronk/duplicate-option',
  duplicate_subcommand = 'kronk/duplicate-subcommand',
  error = 'kronk/error',
  excess_arguments = 'kronk/excess-arguments',
  invalid_argument = 'kronk/invalid-argument',
  invalid_argument_syntax = 'kronk/invalid-argument-syntax',
  invalid_flags = 'kronk/invalid-flags',
  invalid_subcommand_name = 'kronk/invalid-subcommand-name',
  missing_argument = 'kronk/missing-argument',
  missing_mandatory_option = 'kronk/missing-mandatory-option',
  no_flags = 'kronk/no-flags',
  unknown_implied_option = 'kronk/unknown-implied-option',
  unknown_option = 'kronk/unknown-option'
}

optionValueSource

Default option value sources (const enum).

const enum optionValueSource {
  cli = 'cli',
  config = 'config',
  default = 'default',
  env = 'env',
  implied = 'implied'
}

Types

This package is fully typed with TypeScript.

Action

The callback to fire when a command is executed (TypeScript type).

type Action<
  Opts extends OptionValues = OptionValues,
  Args extends any[] = any[]
> = (
  this: Command,
  opts: Opts,
  ...args: Args
) => Awaitable<null | undefined | void>

Type Parameters

  • Opts (OptionValues, optional) β€” command options
  • Args (any[], optional) β€” command arguments

Parameters

  • this (Command) β€” the command or subcommand being executed
  • options (Opts) β€” parsed command options
  • ...args (Args) β€” parsed command arguments

Returns

(Awaitable<null | undefined | void>) Nothing

ArgumentData

Data transfer object for command-arguments (TypeScript interface).

Extends

ArgumentInfo

Data used to create command-arguments (TypeScript interface).

Extends

Properties

ArgumentMetadata

Command-argument metadata (TypeScript interface).

Extends

Properties

  • id (string) β€” argument syntax id
  • required (boolean) β€” whether required syntax was used when defining the argument
  • variadic (boolean) β€” whether variadic syntax was used when defining the argument

ArgumentSyntaxMap

Registry of strings used to define command and option arguments (TypeScript interface).

interface ArgumentSyntaxMap {/* see code */}

When developing extensions that use additional syntaxes, augment ArgumentSyntaxMap to register custom syntaxes:

declare module '@flex-development/kronk' {
  interface ArgumentSyntaxMap {
    requiredMaybe: `<${string}?>`
  }
}

ArgumentSyntax

Union of registered syntaxes used to define command and option arguments (TypeScript type).

To register custom syntaxes, augment ArgumentSyntaxMap. They will be added to this union automatically.

type ArgumentSyntax = ArgumentSyntaxMap[keyof ArgumentSyntaxMap]

ArgumentsData

Union of types used to create command arguments (TypeScript type).

type ArgumentsData =
  | ArgumentInfo
  | List<ArgumentInfo | ArgumentSyntax>
  | string

ArgvSourceMap

Registry of command-line argument sources (TypeScript interface).

interface ArgvSourceMap {/* see code */}

When developing extensions that use additional sources, augment ArgvSourceMap to register custom sources:

declare module '@flex-development/kronk' {
  interface ArgvSourceMap {
    electron: 'electron'
  }
}

ArgvSource

Union of registered command-line argument sources (TypeScript type).

To register custom sources, augment ArgvSourceMap. They will be added to this union automatically.

type ArgvSource = ArgvSourceMap[keyof ArgvSourceMap]

Awaitable

Create a union of T and T as a promise (TypeScript type).

Type Parameters

  • T (any, optional)
    • the value
type Awaitable<T = unknown> = Promise<T> | T

CommandData

Data transfer object for commands (TypeScript interface).

Extends

Properties

  • action? (Action<any>, optional) β€” callback to fire when the command is executed
  • aliases? (List<string> | string, optional) β€” aliases for the command
  • arguments? (List<string>, optional) β€” arguments for the command
  • default? (boolean, optional) β€” whether this is the default command
  • done? (Action<any>, optional) β€” callback to fire after the command action is executed
  • exit? (Exit, optional) β€” callback to fire when the process is exited
  • helpCommand? (HelpCommandData, optional) β€” customize the help subcommand, or disable it (false)

    πŸ‘‰ Note: to configure the help subcommand for helpCommand, a Command instance must be used. helpCommand.helpCommand is set to false when helpCommand is not a Command.

    • default: { description: 'show help', name: 'help' }
  • helpOption? (HelpOptionData, optional) β€” customize the help option, or disable it (false)
    • default: { description: 'show help', flags: '-h | --help' }
  • helpUtility? (Help, optional) β€” the help text utility to use when generating help text
    • default: new Help()
  • optionPriority? (OptionPriority, optional) β€” the strategy to use when merging global and local options
    • default: 'local'
  • options? (OptionsData, optional) β€” options for the command
  • parent? (Command, optional) β€” the parent command
  • subcommands? (SubcommandsData, optional) β€” subcommands for the command
  • summary? (string, optional) β€” a summary of the command
  • unknown? (UnknownStrategy, optional) β€” the strategy to use for handling unknown command-line arguments
    • default: false
  • usage? (UsageData, optional) β€” an object describing how the command is used
    • default: { arguments: null, options: '[options]', subcommand: '[command]' }
  • version? (VersionData, optional) β€” command version configuration

CommandErrorInfo

Data used to create command errors (TypeScript interface).

Extends

Properties

  • command? (Command, optional) β€” the command where the error originated
  • id (KronkErrorId) β€” unique id representing the error

CommandErrorSnapshot

Command error overview (TypeScript interface).

Extends

Properties

  • command (CommandSnapshot | null) β€” an overview of the failed command

CommandInfo

Data used to create commands (TypeScript interface).

Extends

Properties

  • name? (CommandName, optional) β€” the name of the command

CommandMetadata

Command metadata (TypeScript interface).

Extends

Properties

  • aliases (Set<string>) β€” list of command aliases
  • arguments (Argument[]) β€” list of command arguments
  • examples (ExampleInfo[]) β€” list of command examples
  • helpCommand (Command | null | undefined) β€” the help subcommand
  • helpOption (Option | null | undefined) β€” the help option
  • helpUtility (Help) β€” the help text utility to use when generating help text
  • options (Map<string, Option>) β€” map, where each key is a long or short flag and each value is the command option instance registered for that flag
  • parent? (null | undefined) β€” the parent command
  • subcommands (Map<string, Command>) β€” map, where each key is the name of a subcommand each value is a subcommand
  • version (VersionOption | null | undefined) β€” the version option

CommandName

The name of a command (TypeScript type).

Parent commands do not need to have a name, but all subcommands must have a name. Valid command names are non-empty strings.

type CommandName = string | null

CommandSnapshot

Object representing a command overview (TypeScript interface).

Properties

  • ancestors (CommandName[]) β€” list of ancestor command names
  • args (string[]) β€” list of parsed command arguments
  • argv (string[]) β€” list of raw command arguments
  • name (CommandName) β€” the name of the command
  • optionValueSources (OptionValueSources) β€” record, where each key is an option key and each value is the source of the parsed option value
  • opts (OptionValues) β€” parsed command options
  • optsWithGlobals (OptionValues) β€” parsed command options (with globals)

DefaultInfo

Data used to configure the default value of a command argument or option (TypeScript interface).

Type Parameters

  • T (any, optional) β€” default value type

Properties

  • description? (URL | string, optional) β€” description of the default value
  • value? (T, optional) β€” the default value
    • default: undefined

EmptyString

An empty string (TypeScript type).

type EmptyString = ''

ExampleInfo

Command example info (TypeScript interface).

Properties

  • prefix? (string, optional) β€” the example text prefix
  • text (string) β€” the example text

ExamplesData

Union of types used to configure command examples (TypeScript type).

type ExamplesData = ExampleInfo | List<ExampleInfo | string> | string

ExitCode

Union of exit status code types (TypeScript type).

type ExitCode = number | string

ExitProcess

Terminate the process synchronously with an exit status of code (TypeScript type).

If code is omitted, exit uses either the 'success' code 0 or the value of process.exitCode if it has been set.

type ExitProcess = (code?: ExitCode | null | undefined) => undefined

Parameters

  • code? (ExitCode, optional) β€” exit status code

Returns

(undefined) Nothing

Exit

The callback to fire when the process is exited (TypeScript type).

type Exit = (
  this: Command,
  e?: CommandError | KronkError | null | undefined
) => undefined

Parameters

  • this (Command) β€” the current command or subcommand being executed
  • e? (CommandError | KronkError, optional) β€” the error to handle (if any)

Returns

(undefined) Nothing

Flags

A string comprised of option flags (TypeScript type).

The flags string can contain at most 2 flags, typically one long flag and one short or shortish (e.g. --ws) flag. Flags are separated by commas (,), pipes (|), or spaces.

A short flag is a hyphen β€” specifically HYPHEN-MINUS U+002D β€” followed by one case-insensitive alphanumeric character. The letters themselves have conventional meanings and are worth following, if possible.

A long flag starts with two hyphens followed by one or more case-insensitive alphanumeric characters. Using two hyphens prevents long flags from being confused for grouped short options. Hyphens and full stops (FULL STOP U+002E) can be used to separate words, as well as camelCase format.

Option-arguments are marked as required using empty angle brackets (<>) or by wrapping an argument id in angle brackets: <id>. Optional arguments use empty square brackets ([]) or have their id wrapped in square brackets: [id].

Variadic arguments are specified with an ellipsis wrapped in brackets (e.g. <...>, [...]) or by appending the ellipsis to the end of the argument id (<value...>, [value...]). Option-arguments can also be marked as mandatory by appending an exclamation mark to the end of the argument id: (<!>, <id!>, <value!...>).

type Flags = string

HelpCommandData

Union of types used to configure the help subcommand (TypeScript type).

The help subcommand can be customized with a Command instance, subcommand info object, or a subcommand name. It can also be disabled (false).

type HelpCommandData = Command | SubcommandInfo | string | false

HelpOptionData

Union of types used to configure the help option (TypeScript type).

The command help option can be customized with an Option instance, flags, or an info object. It can also be disabled (false).

type HelpOptionData = Flags | Option | OptionInfo | false

HelpTextOptions

Options for formating help text (TypeScript interface).

Extends

Properties

  • columns? (number, optional) β€” the maximum number of columns to output
    • default: 80

HelpableInfo

Data used to create help text candidates (TypeScript interface).

Properties

  • description? (URL | string, optional) β€” a description of the candidate. the description can be long or short form text, or a URL pointing to more information about the candidate
  • hidden? (boolean, optional) β€” whether the candidate should not be displayed in help text

KronkErrorCause

Info about the cause of an error (TypeScript interface).

πŸ‘‰ Note: Symbol.hasInstance and Symbol.unscopables are used to identify arrays and functions.

interface KronkErrorCause {
  [Symbol.hasInstance]?: never
  [Symbol.unscopables]?: never
  [key: string]: any
}

KronkErrorId

Union of registered error ids (TypeScript type).

To register custom error ids, augment KronkErrorMap. They will be added to this union automatically.

type KronkErrorId = `kronk/${keyof KronkErrorMap}`

KronkErrorInfo

Data used to create errors (TypeScript interface).

Properties

  • additional? (string | string[], optional) β€” additional lines to be logged with the error
  • cause? (KronkErrorCause, optional) β€” info about the cause of the error
  • code? (ExitCode, optional) β€” the suggested exit code to use with process.exit
    • default: 1
  • id? (EmptyString | KronkErrorId, optional) β€” the unique id representing the error
    • default: 'kronk/error'
  • reason (string) β€” a human-readable description of the error

KronkErrorJson

JSON representation of an error (TypeScript interface).

Properties

  • additional (string[]) β€” additional lines to be logged with the error
  • cause? (KronkErrorCause, optional) β€” info about the cause of the error
  • code (number) β€” the suggested exit code to use with process.exit
  • id (KronkErrorId) β€” the unique id representing the error
  • message (string) β€” the human-readable description of the error
  • stack? (string, optional) β€” stack trace

KronkErrorMap

Registry of errors (TypeScript interface).

Each key is the suffix of an error id and each value is a KronkError.

interface KronkErrorMap {/* see code */}

When developing extensions that use additional errors, augment KronkErrorMap to register custom errors:

declare module '@flex-development/kronk' {
  interface KronkErrorMap {
    'action-error': CustomCommandError
    'parse-error': CustomKronkError
  }
}

KronkEventListener

Handle an event (TypeScript type).

type KronkEventListener<T extends KronkEvent = KronkEvent> = (
  event: T
) => undefined

Type Parameters

  • T (KronkEvent, optional) β€” the emitted event

Parameters

  • event (T) β€” the emitted event

Returns

(undefined) Nothing

KronkEventNameMap

Registry of event names (TypeScript interface).

interface KronkEventNameMap extends OptionEventNameMap {/* see code */}

When developing extensions that use additional events, augment KronkEventNameMap to register custom event names:

declare module '@flex-development/kronk' {
  interface KronkEventNameMap {
    custom: 'command:custom'
  }
}

KronkEventName

Union of registered event names (TypeScript type).

To register custom event names, augment KronkEventNameMap. They will be added to this union automatically.

type KronkEventName = KronkEventNameMap[keyof KronkEventNameMap]

List

A list (TypeScript type).

Type Parameters

  • T (any, optional) β€” list item type
type List<T = unknown> = ReadonlySet<T> | readonly T[]

OptionData

Data transfer object for command options (TypeScript interface).

Extends

Properties

  • conflicts? (List<string> | string, optional) β€” an option name, or list of option names, that conflict with the option.
    an error will be displayed if conflicting options are found during parsing
  • env? (List<string> | string, optional) β€” the name of the environment variable to check for option value, or a list of names, in order of priority, to check
  • implies? (OptionValues | string, optional) β€” the key of an implied option, or a map where each key is an implied option key and each value is the value to use when the option is set but the implied option is not.
    lone keys imply (string implies) true, i.e. { [implies]: true }.
    the option-argument parser will be called for implied values that are strings and string arrays
  • mandatory? (boolean, optional) β€” whether the option is mandatory. mandatory options must have a value after parsing, which usually means the option must be specified on the command line
    • default: false
  • preset? (string, optional) β€” for boolean and optional options, the preset to use when the option is specified without an option-argument.

    πŸ‘‰ note: the option-argument parser will be called.

  • snakecase? (boolean, optional) β€” whether to use snake_case format when converting the option id to an object property key

OptionEventListener

Handle a parsed command option event (TypeScript type).

type OptionEventListener<T extends Option = Option> = (
  event: OptionEvent<T>
) => undefined

Type Parameters

  • T (Option, optional) β€” the parsed command option

Parameters

Returns

(undefined) Nothing

OptionEventNameMap

Registry of option event names (TypeScript interface).

interface OptionEventNameMap {/* see code */}

When developing extensions that use additional events, augment OptionEventNameMap to register custom event names:

declare module '@flex-development/kronk' {
  interface OptionEventNameMap {
    custom: `option.${string}`
  }
}

OptionEventName

Union of registered option event names (TypeScript type).

To register custom event names, augment OptionEventNameMap. They will be added to this union automatically.

type OptionEventName = OptionEventNameMap[keyof OptionEventNameMap]

OptionInfo

Data used to create command options (TypeScript interface).

Extends

Properties

  • flags (Flags) β€” option flags

OptionMetadata

Command option metadata (TypeScript interface).

Extends

Properties

  • long (string | null | undefined) β€” long flag
  • optional (boolean) β€” whether a value is optional when the option is specified
  • required (boolean) β€” whether a value must be supplied when the option is specified
  • short (string | null | undefined) β€” short (or shortish, e.g. --ws) flag

    πŸ‘‰ note: if null or undefined, the long flag will be a non-empty string

  • variadic (boolean) β€” whether the option can be specified multiple times

OptionPriority

Union of strategies used when merging global and local options (TypeScript type).

  • global: global options overwrite local options
  • local: local options overwrite global options
type OptionPriority = 'global' | 'local'

OptionValueSourceMap

Registry of option value sources (TypeScript interface).

interface OptionValueSourceMap {/* see code */}

When developing extensions that use additional sources, augment OptionValueSourceMap to register custom sources:

declare module '@flex-development/kronk' {
  interface OptionValueSourceMap {
    builder: 'builder'
  }
}

OptionValueSource

Union of registered option value sources (TypeScript type).

To register custom sources, augment OptionValueSourceMap. They will be added to this union automatically.

type OptionValueSource = OptionValueSourceMap[keyof OptionValueSourceMap]

OptionValueSources

Record, where each key is an option key (Option.key) and each value is an OptionValueSource (TypeScript type).

type OptionValueSources = {
  [x: Option['key']]: OptionValueSource | null | undefined
}

OptionValues

Record, where each key is an option key (Option.key) and each value is a parsed option value (TypeScript type).

Type Parameters

  • T (any, optional) β€” parsed option value type
type OptionValues<T = any> = { [x: Option['key']]: T }

OptionsData

Union of types used to create command options (TypeScript type).

type OptionsData =
  | Flags
  | List<Flags | OptionInfo>
  | OptionInfo

ParseArg

Parse a command or option argument value (TypeScript type).

type ParseArg<T = any, Value extends RawParseValue = RawParseValue> = (
  this: void,
  value: Value,
  previous: T | undefined
) => T

Type Parameters

  • T (any, optional) β€” parse result
  • Value (RawParseValue, optional) β€” the argument or arguments to parse

Parameters

  • this (Command) β€” the current command or subcommand being executed
  • value (Value) β€” the raw argument or arguments to parse
  • previous (T | undefined) β€” the default argument value

Returns

(T) Parse result

ParseOptions

Options for parsing command-line arguments (TypeScript interface).

Properties

  • from? (ArgvSource, optional) β€” the source of the command line arguments

ParseUnknownResult

The result of parsing unknown arguments (TypeScript interface).

Properties

  • operands (string[]) β€” list of arguments that are operands (not options or values)
  • unknown (string[]) β€” list containing the first unknown option and any remaining unknown arguments

ParseableInfo

Data used to create parse candidates (TypeScript interface).

Extends

Properties

  • choices? (List<string>, optional) β€” list of option choices
  • default? (DefaultInfo, optional) β€” default value configuration

    πŸ‘‰ note: the option-argument parser will not be called.

  • parser? (ParseArg<any, string> | ParseArg<any, string[]>, optional) β€” handler used to parse arguments. the handler receives two parameters, the raw, unparsed argument (or arguments for variadic candidates), and the default value for the argument. it should return the new value for the argument

ParseableMetadata

Parse candidate metadata (TypeScript interface).

Extends

Properties

  • required? (boolean, optional) β€” whether required syntax was used when defining the candidate
  • variadic? (boolean, optional) β€” whether variadic syntax was used when defining the candidate.

ProcessEnv

Information about the current user environment (TypeScript interface).

interface ProcessEnv {
  [key: string]: string | undefined
}

Process

Information about the current process (TypeScript interface).

Properties

  • argv (string[]) β€” list of command-line arguments passed when the process was launched
  • env (ProcessEnv) β€” object containing information about the user environment
  • exit (ExitProcess) β€” terminate the process synchronously with an exit status of code
  • exitCode? (ExitCode, optional) β€” the exit code to use when the process exits gracefully, or is exited via exit without specifying a code
  • stderr (WriteStream) β€” the writeable stream for standard error output
  • stdout (WriteStream) β€” the writeable stream for standard output

RawOptionValue

Union of raw option value types (TypeScript type).

type RawOptionValue = boolean | string | string[] | null

RawParseValue

The argument or arguments passed to an argument parser (TypeScript type).

type RawParseValue = string | readonly string[]

SubcommandInfo

Data used to create subcommands (TypeScript interface).

Extends

Properties

  • name (string) β€” the name of the subcommand

SubcommandsData

Union of types used to create subcommands (TypeScript type).

type SubcommandsData = SubcommandInfo | SubcommandsInfo

SubcommandsInfo

Record, where each key is the name of a subcommand and each value is an info object.

type SubcommandsInfo = { [subcommand: string]: CommandInfo }

UnknownStrategy

Union of values used to alter handling of unknown command-line arguments (TypeScript type).

  • 'arguments': allow unknown command-arguments only
  • 'options': allow unknown options only
  • false: disallow unknown command-arguments and options
  • true: allow unknown command-arguments and options
type UnknownStrategy = 'arguments' | 'options' | boolean

UsageData

An object describing command usage (TypeScript interface).

Properties

  • arguments? (string, optional) β€” command arguments descriptor

    πŸ‘‰ note: displayed in auto-generated help text only when a command has at least one visible argument

    • default: generated using visible command arguments
  • options? (string, optional) β€” command options descriptor

    πŸ‘‰ note: displayed in auto-generated help text only when a command has at least one visible option

  • subcommand? (string, optional) β€” subcommands descriptor

    πŸ‘‰ note: displayed in auto-generated help text only when a command has at least one visible subcommand

    • default: '[command]'

UsageInfo

Command usage info (TypeScript interface).

Extends

Properties

  • options (string) β€” command options descriptor

    πŸ‘‰ note: displayed in auto-generated help text only when a command has at least one visible option

  • subcommand (string) β€” subcommands descriptor

    πŸ‘‰ note: displayed in auto-generated help text only when a command has at least one visible subcommand

VersionData

Union of types used to configure the version of a Command (TypeScript type).

type VersionData = Version | VersionOption | VersionOptionInfo

VersionOptionInfo

Data used to create command version options (i.e. -v | --version) (TypeScript interface).

Extends

Properties

  • flags? (Flags, optional) β€” option flags
    • default: '-v | --version'
  • version (Version) β€” the command version

Version

Union of command version types (TypeScript type).

type Version = import('semver').SemVer | string

Contribute

See CONTRIBUTING.md.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

Releases

No releases published

Sponsor this project

 

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages