@adonisjs/ace

  • Version 13.0.0
  • Published
  • 234 kB
  • 11 dependencies
  • MIT license

Install

npm i @adonisjs/ace
yarn add @adonisjs/ace
pnpm add @adonisjs/ace

Overview

A CLI framework for Node.js

Index

Variables

variable args

const args: {
string<Type = string>(
options?: Partial<Omit<StringArgument<Type>, 'type'>>
): <Key extends string, Target extends { [K in Key]?: Type }>(
target: Target,
propertyName: Key
) => void;
spread<Type_1 extends unknown = string[]>(
options?: Partial<Omit<SpreadArgument<Type_1>, 'type'>>
): <Key_1 extends string, Target_1 extends { [K_1 in Key_1]?: Type_1 }>(
target: Target_1,
propertyName: Key_1
) => void;
};
  • Namespace for defining arguments using decorators.

variable flags

const flags: {
string<Type = string>(
options?: Partial<Omit<StringFlag<Type>, 'type'>>
): <Key extends string, Target extends { [K in Key]?: Type }>(
target: Target,
propertyName: Key
) => void;
boolean<Type_1 = boolean>(
options?: Partial<Omit<BooleanFlag<Type_1>, 'type'>>
): <Key_1 extends string, Target_1 extends { [K_1 in Key_1]?: Type_1 }>(
target: Target_1,
propertyName: Key_1
) => void;
number<Type_2 = number>(
options?: Partial<Omit<NumberFlag<Type_2>, 'type'>>
): <Key_2 extends string, Target_2 extends { [K_2 in Key_2]?: Type_2 }>(
target: Target_2,
propertyName: Key_2
) => void;
array<Type_3 extends any[] = string[]>(
options?: Partial<Omit<ArrayFlag<Type_3>, 'type'>>
): <Key_3 extends string, Target_3 extends { [K_3 in Key_3]?: Type_3 }>(
target: Target_3,
propertyName: Key_3
) => void;
};
  • Namespace for defining flags using decorators.

Classes

class BaseCommand

class BaseCommand extends Macroable {}
  • The base command sets the foundation for defining ace commands. Every command should inherit from the base command.

constructor

constructor(kernel: Kernel<any>, parsed: any, ui: any, prompt: Prompt);

    property aliases

    static aliases: string[];
    • A collection of aliases for the command

    property args

    static args: Argument[];
    • Registered arguments

    property args

    readonly args: Argument[];
    • Reference to the command args

    property booted

    static booted: boolean;

      property colors

      readonly colors: Colors;
      • Add colors to console messages

      property commandName

      static commandName: string;
      • The command name one can type to run the command

      property commandName

      readonly commandName: string;
      • Reference to the command name

      property description

      static description: string;
      • The command description

      property error

      error?: any;
      • The error raised at the time of the executing the command. The value is undefined if no error is raised.

      property exitCode

      exitCode?: number;
      • The exit code for the command

      property flags

      static flags: Flag[];
      • Registered flags

      property flags

      readonly flags: Flag[];
      • Reference to the command flags

      property help

      static help?: string | string[];
      • The help text for the command. Help text can be a multiline string explaining the usage of command

      property hydrated

      protected hydrated: boolean;
      • Check if a command has been hypdrated

      property isMain

      readonly isMain: boolean;
      • Is the current command the main command executed from the CLI

      property kernel

      protected kernel: Kernel<any>;

        property logger

        readonly logger: any;
        • Logger to log messages

        property options

        static options: CommandOptions;
        • Configuration options accepted by the command

        property options

        readonly options: CommandOptions;
        • Reference to the command options

        property parsed

        protected parsed: any;

          property prompt

          prompt: Prompt;

            property result

            result?: any;
            • The result property stores the return value of the "run" method (unless commands sets it explicitly)

            property ui

            ui: any;

              method assertExitCode

              assertExitCode: (code: number) => void;
              • Assert the command exists with a given exit code

              method assertFailed

              assertFailed: () => void;
              • Assert the command exists with non-zero exit code

              method assertLog

              assertLog: (message: string, stream?: 'stdout' | 'stderr') => void;
              • Assert command to log the expected message

              method assertLogMatches

              assertLogMatches: (matchingRegex: RegExp, stream?: 'stdout' | 'stderr') => void;
              • Assert command to log the expected message

              method assertNotExitCode

              assertNotExitCode: (code: number) => void;
              • Assert the command exists with a given exit code

              method assertSucceeded

              assertSucceeded: () => void;
              • Assert the command exists with zero exit code

              method assertTableRows

              assertTableRows: (rows: string[][]) => void;
              • Assert the command prints a table to stdout

              method boot

              static boot: () => void;
              • Define static properties on the class. During inheritance, certain properties must inherit from the parent.

              method defineArgument

              static defineArgument: (
              name: string,
              options: Partial<Argument> & { type: 'string' | 'spread' }
              ) => void;
              • Specify the argument the command accepts. The arguments via the CLI will be accepted in the same order as they are defined.

                Mostly, you will be using the @args decorator to define the arguments.

                Command.defineArgument('entity', { type: 'string' })

              method defineFlag

              static defineFlag: (
              name: string,
              options: Partial<Flag> & { type: 'string' | 'boolean' | 'array' | 'number' }
              ) => void;
              • Specify a flag the command accepts.

                Mostly, you will be using the @flags decorator to define a flag.

                Command.defineFlag('connection', { type: 'string', required: true })

              method exec

              exec: () => Promise<any>;
              • Executes the commands by running the command's run method.

              method getParserOptions

              static getParserOptions: (options?: FlagsParserOptions) => {
              flagsParserOptions: Required<FlagsParserOptions>;
              argumentsParserOptions: ArgumentsParserOptions[];
              };
              • Returns the options for parsing flags and arguments

              method hydrate

              hydrate: () => void;
              • Hydrate command by setting class properties from the parsed output

              method run

              run: (..._: any[]) => Promise<any>;
              • The run method should include the implementation for the command.

              method serialize

              static serialize: () => CommandMetaData;
              • Serializes the command to JSON. The return value satisfies the CommandMetaData

              method toJSON

              toJSON: () => {
              commandName: string;
              options: CommandOptions;
              args: any[];
              flags: { [argName: string]: any };
              error: any;
              result: any;
              exitCode: number | undefined;
              };
              • JSON representation of the command

              method validate

              static validate: (parsedOutput: ParsedOutput) => void;
              • Validate the yargs parsed output againts the command.

              class ExceptionHandler

              class ExceptionHandler {}
              • The base exception handler that is used by default to exception ace exceptions.

                You can extend this class to custom the exception rendering behavior.

              property debug

              debug: boolean;

                property internalKnownErrorCode

                protected internalKnownErrorCode: string[];
                • Internal set of known error codes.

                property knownErrorCodes

                protected knownErrorCodes: string[];
                • Known error codes. For these error, only the error message is reported using the logger

                method logError

                protected logError: (
                error: { message: any } & unknown,
                kernel: Kernel<any>
                ) => void;
                • Logs error to stderr using logger

                method prettyPrintError

                protected prettyPrintError: (error: object) => Promise<void>;
                • Pretty prints uncaught error in debug mode

                method render

                render: (error: unknown, kernel: Kernel<any>) => Promise<void>;
                • Renders an exception for the console

                class FsLoader

                class FsLoader<Command extends AbstractBaseCommand>
                implements LoadersContract<Command> {}
                • Fs loader exposes the API to load commands from a directory. All files ending with ".js", ".cjs", ".mjs", ".ts" and ".mts" are considered as commands

                constructor

                constructor(comandsDirectory: string, filter?: (filePath: string) => boolean);

                  method getCommand

                  getCommand: (metaData: CommandMetaData) => Promise<Command | null>;
                  • Returns the command class constructor for a given command. Null is returned when unable to lookup the command

                  method getMetaData

                  getMetaData: () => Promise<CommandMetaData[]>;
                  • Returns the metadata of commands

                  class HelpCommand

                  class HelpCommand extends BaseCommand {}
                  • The Help command is used to view help for a given command

                  property commandName

                  static commandName: string;
                  • Command metadata

                  property description

                  static description: string;

                    property name

                    name: string;
                    • The command name argument

                    method renderDescription

                    protected renderDescription: (command: CommandMetaData) => void;
                    • Logs command description

                    method renderHelp

                    protected renderHelp: (command: CommandMetaData) => void;
                    • Logs command help text

                    method renderList

                    protected renderList: (command: CommandMetaData) => void;
                    • Logs commands arguments and options tables

                    method renderUsage

                    protected renderUsage: (command: CommandMetaData) => void;
                    • Logs command usage

                    method run

                    run: () => Promise<void>;
                    • Executed by ace directly

                    class IndexGenerator

                    class IndexGenerator {}
                    • The index generators creates a commands laoder that can be lazily imported.

                      Also, a command.json index file is created that has metadata for all the files. Doing so, speeds up the commands lookup, as we do not have to import all the classes just to find if a command exists or not.

                    constructor

                    constructor(commandsDir: string);

                      method generate

                      generate: () => Promise<any>;
                      • Generate index

                      class Kernel

                      class Kernel<Command extends AbstractBaseCommand> {}
                      • The Ace kernel manages the registration and execution of commands.

                        The kernel is the main entry point of a console application, and is tailored for a standard CLI environment.

                      constructor

                      constructor(
                      defaultCommand: AbstractBaseCommand,
                      executor: ExecutorContract<Command>
                      );

                        property commandExecutor

                        static commandExecutor: ExecutorContract<typeof BaseCommand>;
                        • The default executor for creating command's instance and running them

                        property defaultCommand

                        static defaultCommand: typeof BaseCommand;
                        • The default command to use when creating kernel instance via "static create" method.

                        property exitCode

                        exitCode?: number;
                        • The exit code for the kernel. The exit code is inferred from the main code when not set explicitly.

                        property flags

                        readonly flags: ({ name: string } & Flag)[];
                        • List of global flags

                        property info

                        info: Map<string, AllowedInfoValues>;
                        • CLI info map

                        property prompt

                        prompt: Prompt;
                        • Instance of prompt to display CLI prompts. We share a single instance with all the commands. This allows trapping prompts for commands executed internally.

                        property ui

                        ui: any;
                        • The UI primitives to use within commands

                        method addAlias

                        addAlias: (alias: string, command: string) => this;
                        • Register alias for a comamnd name.

                        method addLoader

                        addLoader: (
                        loader: LoadersContract<Command> | (() => Promise<LoadersContract<Command>>)
                        ) => this;
                        • Register a commands loader. The commands will be collected by all the loaders.

                          Incase multiple loaders returns a single command, the command from the most recent loader will be used.

                        method boot

                        boot: () => Promise<void>;
                        • Loads commands from all the registered loaders. The "addLoader" method must be called before calling the "load" method.

                        method create

                        static create: () => Kernel<typeof BaseCommand>;
                        • Creates an instance of kernel with the default executor and default command

                        • Creates a command instance by parsing and validating the command-line arguments.

                        method defineFlag

                        defineFlag: (
                        name: string,
                        options: Partial<Flag> & { type: 'string' | 'boolean' | 'array' | 'number' }
                        ) => void;
                        • Define a global flag that is applicable for all the commands.

                        method exec

                        exec: <T extends Command>(
                        commandName: string,
                        argv: string[]
                        ) => Promise<InstanceType<T>>;
                        • Execute a command. The second argument is an array of commandline arguments (without the command name)

                        method executed

                        executed: (
                        callback: HookHandler<[Command, boolean], [Command, boolean]>
                        ) => this;
                        • Listen for the event after the command has been executed

                        method executing

                        executing: (
                        callback: HookHandler<[Command, boolean], [Command, boolean]>
                        ) => this;
                        • Listen for the event before we start to execute the command.

                        method find

                        find: <T extends Command>(commandName: string) => Promise<T>;
                        • Find a command by its name

                        method finding

                        finding: (callback: HookHandler<[string], [string]>) => this;
                        • Listen for the event before we begin the process of finding the command.

                        method getAliasCommand

                        getAliasCommand: (alias: string) => CommandMetaData | null;
                        • Returns the command metata for a given alias. Returns null if alias is not recognized.

                        method getAliases

                        getAliases: () => string[];
                        • Returns an array of aliases registered.

                          - Call getCommandAliases method to get aliases for a given command - Call getAliasCommand to get the command or a given alias

                        method getCommand

                        getCommand: (commandName: string) => CommandMetaData | null;
                        • Returns the command metadata by its name. Returns null when the command is missing.

                        method getCommandAliases

                        getCommandAliases: (commandName: string) => string[];
                        • Returns an array of aliases for a given command

                        method getCommands

                        getCommands: () => CommandMetaData[];
                        • Returns a flat list of commands metadata registered with the kernel. The list is sorted alphabetically by the command name.

                        method getCommandSuggestions

                        getCommandSuggestions: (keyword: string) => string[];
                        • Returns an array of command and aliases name suggestions for a given keyword.

                        method getDefaultCommand

                        getDefaultCommand: () => Command;
                        • Returns a reference for the default command. The return value is the default command constructor

                        method getMainCommand

                        getMainCommand: () => InstanceType<Command> | undefined;
                        • Returns reference to the main command

                        method getNamespaceCommands

                        getNamespaceCommands: (namespace?: string) => CommandMetaData[];
                        • Get a list of commands for a specific namespace. All non-namespaces commands will be returned if no namespace is defined.

                        method getNamespaces

                        getNamespaces: () => string[];
                        • Returns a list of namespaces. The list is sorted alphabetically by the namespace name

                        method getNamespaceSuggestions

                        getNamespaceSuggestions: (keyword: string) => string[];
                        • Returns an array of namespaces suggestions for a given keyword.

                        method getState

                        getState: () => 'booted' | 'idle' | 'running' | 'completed';
                        • Get the current state of the kernel.

                        method handle

                        handle: (argv: string[]) => Promise<void>;
                        • Handle process argv and execute the command. Calling this method makes kernel own the process and register SIGNAL listeners

                        method loaded

                        loaded: (callback: HookHandler<[Command], [Command]>) => this;
                        • Listen for the event when the command has been imported

                        method loading

                        loading: (callback: HookHandler<[CommandMetaData], [CommandMetaData]>) => this;
                        • Listen for the event when importing the command

                        method on

                        on: (option: string, callback: FlagListener<Command>) => this;
                        • Listen for CLI options and execute an action. Only one listener can be defined per aption.

                          The callbacks are only executed for the main command

                        method shortcircuit

                        shortcircuit: () => boolean;
                        • A named function that returns true. To be used by flag listeners

                        class ListCommand

                        class ListCommand extends BaseCommand {}
                        • The list command is used to view a list of commands

                        property commandName

                        static commandName: string;
                        • Command metadata

                        property description

                        static description: string;

                          property help

                          static help: string[];

                            property json

                            json?: boolean;

                              property namespaces

                              namespaces?: string[];
                              • Optional flag to filter list by namespace

                              method renderList

                              protected renderList: () => void;
                              • The method is used to render a list of options and commands

                              method renderToJSON

                              protected renderToJSON: () => CommandMetaData[];

                                method run

                                run: () => Promise<void>;
                                • Executed by ace directly

                                class ListLoader

                                class ListLoader<Command extends AbstractBaseCommand>
                                implements LoadersContract<Command> {}
                                • List loader exposes the API to register commands as classes

                                constructor

                                constructor(commands: Command[]);

                                  method getCommand

                                  getCommand: (metaData: CommandMetaData) => Promise<Command | null>;
                                  • Returns the command class constructor for a given command. Null is returned when unable to lookup the command

                                  method getMetaData

                                  getMetaData: () => Promise<CommandMetaData[]>;
                                  • Returns an array of command's metadata

                                  class Parser

                                  class Parser {}
                                  • Parses the command line arguments. The flags are parsed using yargs-parser

                                  constructor

                                  constructor(options: {
                                  flagsParserOptions: FlagsParserOptions;
                                  argumentsParserOptions: ArgumentsParserOptions[];
                                  });

                                    method parse

                                    parse: (argv: string | string[]) => ParsedOutput;
                                    • Parse commandline arguments

                                    Namespaces

                                    namespace errors

                                    module 'build/src/errors.d.ts' {}
                                    • Command is missing the static property command name

                                    variable E_COMMAND_NOT_FOUND

                                    const E_COMMAND_NOT_FOUND: {
                                    new (args: [command: string]): {
                                    commandName: string;
                                    name: string;
                                    help?: string | undefined;
                                    code?: string | undefined;
                                    status: number;
                                    toString(): string;
                                    readonly [Symbol.toStringTag]: string;
                                    message: string;
                                    stack?: string | undefined;
                                    cause?: unknown;
                                    };
                                    status: number;
                                    help?: string | undefined;
                                    code?: string | undefined;
                                    message?: string | undefined;
                                    captureStackTrace(
                                    targetObject: object,
                                    constructorOpt?: Function | undefined
                                    ): void;
                                    prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any;
                                    stackTraceLimit: number;
                                    };
                                    • Cannot find a command for the given name

                                    variable E_INVALID_FLAG

                                    const E_INVALID_FLAG: new (
                                    args: [flag: string, expectedDataType: string],
                                    options?: ErrorOptions | undefined
                                    ) => Exception;
                                    • Invalid value provided for the flag

                                    variable E_MISSING_ARG

                                    const E_MISSING_ARG: new (
                                    args: [arg: string],
                                    options?: ErrorOptions | undefined
                                    ) => Exception;
                                    • Missing a required argument when running the command

                                    variable E_MISSING_ARG_VALUE

                                    const E_MISSING_ARG_VALUE: new (
                                    args: [arg: string],
                                    options?: ErrorOptions | undefined
                                    ) => Exception;
                                    • Missing value for an argument

                                    variable E_MISSING_COMMAND_NAME

                                    const E_MISSING_COMMAND_NAME: new (
                                    args: [command: string],
                                    options?: ErrorOptions | undefined
                                    ) => Exception;
                                    • Command is missing the static property command name

                                    variable E_MISSING_FLAG

                                    const E_MISSING_FLAG: new (
                                    args: [flag: string],
                                    options?: ErrorOptions | undefined
                                    ) => Exception;
                                    • Missing a required flag when running the command

                                    variable E_MISSING_FLAG_VALUE

                                    const E_MISSING_FLAG_VALUE: new (
                                    args: [flag: string],
                                    options?: ErrorOptions | undefined
                                    ) => Exception;
                                    • Missing value for a flag that accepts values

                                    variable E_PROMPT_CANCELLED

                                    const E_PROMPT_CANCELLED: new (
                                    args?: any,
                                    options?: ErrorOptions | undefined
                                    ) => Exception;

                                      variable E_UNKNOWN_FLAG

                                      const E_UNKNOWN_FLAG: new (
                                      args: [flag: string],
                                      options?: ErrorOptions | undefined
                                      ) => Exception;
                                      • An unknown flag was mentioned

                                      Package Files (13)

                                      Dependencies (11)

                                      Dev Dependencies (25)

                                      Peer Dependencies (0)

                                      No peer dependencies.

                                      Badge

                                      To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                      You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@adonisjs/ace.

                                      • Markdown
                                        [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@adonisjs/ace)
                                      • HTML
                                        <a href="https://www.jsdocs.io/package/@adonisjs/ace"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>