NodeJS Framework for Interactive CLIs

Overview

Cliffy - A Framework For Interactive CLIs

Cliffy is a simple, powerful utility for making interactive command line interfaces.

Cliffy is run as a REPL. This allows you to accept multiple commands with one running node process. Cliffy is NOT an argv parser.

Features:

  • REPL Style interface
  • Simple API
  • Can parse negative numbers
  • Typed parameters
  • Git Style Sub-Commands
  • Optional parameters (New in v2)
  • Rest parameters (New in v2)
  • Options
  • Auto generated help
  • Typescript Support

Gotchas:

  • Options are specified with an @ symbol. Not - or --. This is what allows Cliffy to parse negatives.
  • Requires node v6+

Quickstart

Installation:

npm i cliffy # --save if using npm < v5

Usage

import { CLI } from "cliffy";

const cli = new CLI()
    .setDelimiter("-->")
    .addCommand("run", {
        description: "Run somewhere",
        options: [{ label: "quickly", description: "Run quickly" }],
        parameters: ["destination"],
        action: (params, options) => {
            if (options.quickly) {
                console.log(`I ran to ${params.destination} quickly`)
                return;
            }

            console.log(`I ran to ${params.destination}`)
        },
        subcommands: {
            to: {
                description: "Run to a destination",
                parameters: ["destination"],
                action: params => console.log(`I ran to ${params.destination}`)
            },
            from: {
                description: "Run from a destination",
                parameters: ["location"],
                action: params => console.log(`I ran from ${params.location}`)
            }
        }
    })
    .show();

Result:

--> run to nevada
I ran to nevada
--> help

Available commands:

    run [options]  <destination>    Run somewhere

--> help run

Run somewhere

Usage:

    run [options] <destination>

Options:

   @quickly                          Run quickly

Sub-Commands:

    to [options] <destination>       Run to a destination
    from [options] <destination>     Run from a destination

Quoted parameters

Parameters may be quoted using either ' (single) or " (double) quotes. For example the command could be

say "Hello World" 'Lovely Weather'

This would give two parameters of Hello World and Lovely Weather. When inside the quoted parameter, the other type of quotes can be used. This lets JSON be entered for example.

say '{"text": "This is the weather"}'

Will give a parameter of the string, {"text": "This is the weather"} that can then be parsed as JSON.

Autogenerated Help Menu

Cliffy automatically generates a help menu for each command.

To get an overview of all the commands simply type:

help

To get help with a specific command, type help followed by the command.

help ls

This works with subcommands as well

help git pull

Build instructions

  1. Clone this repo
  2. CD into the repo
  3. npm install
  4. npm run build

API

new CLI()

Interface:

class CLI {
    constructor(opts: {
        input?: NodeJS.ReadableStream,
        output?: NodeJS.WritableStream
    } = {})
}

Usage:

const cli = new CLI(opts)

cli.addCommand(name: string, command: Command): this

Register a command

Takes a name and a command object.

The command name is what the user will enter to execute the command.

The command interface is defined as follows:

interface Command {
    /**
     * The action to perform when its command is called.
     *
     * parameters is a key value store. Where the key is the parameter label,
     * and its value is the value entered by the user.
     *
     * options is a key value store. Key being the option, value being true if the user
     * specified the option, false otherwise.
     */
    action(parameters: any, options: { [key: string]: boolean }): void | Promise<void>;

    /** Optional description for documentation */
    description?: string;

    /** Aliases the command can be accessed from */
    aliases?: string[];

    /**
     * An array of options available to the user.
     * The user specifies an option with an @ symbol i.e. @force
     */
    options?: (Option | string)[];

    /**
     * All the parameters available to the user.
     * See the parameters interface.
     *
     * If a string is passed it is assumed to be string parameter
     */
    parameters?: (Parameter | string)[];

    /** Sub commands of the command. Follows the same interface as Command */
    subcommands?: Commands;
}

export interface Parameter {
    label: string;

    /** The type to convert the provided value to. Can be a custom converter. */
    type?: "boolean" | "number" | "string" | ((val: string) => any);

    /** The parameter is optional */
    optional?: boolean;

    /**
     * The parameter is a rest parameter.
     *
     * If true, the user can pass an indefinite amount of arguments
     * that are put in an array set in this parameter.
     **/
    rest?: boolean;

    /** Optional description for the help menu */
    description?: string;
}

export interface Option {
    label: string;
    description?: string;
}

Example Usage:

cli.command("run", {
    description: "Run somewhere",
    options: [{ option: "fast", description: "Run fast" }],
    parameters: [{ label: "destination" }],
    action: (params, options) => {
        if (options.fast) return console.log(`I ran to ${params.destination} quickly`);
        console.log(`I ran to ${params.destination}`);
    },
    subcommands: {
        to: {
            parameters: [{ label: "destination" }],
            action: params => console.log(`I ran to ${params.destination}`),
        }
        from: {
            parameters: [{ label: "destination" }],
            action: params => console.log(`I ran to ${params.destination}),
        }
    }
});

cli.addCommand(name: string, opts: Action): this

Register a basic command.

This overload allows you to pass the action function directy. Useful for quick commands where parameters, options, and a description may not be needed.

Example usage:

cli.command("speak", () => sayHello("World"));

cli.addCommands(commands: { [name: string]: Command | Action }): this

Register multiple commands at once.

Example usage:

cli.commands({
    run: {
        action(params, options) {
            console.log("Running");
        }
    },

    jog: {
        action(params, options) {
            console.log("Jogging");
        }
    },

    walk: {
        action(params, options) {
            console.log("Walking");
        }
    }
});

cli.setDelimiter(delimiter: string): this

Set the CLI delimiter

Defaults to: "$>"

cli.setInfo(info: string): this

Set the CLI info.

Info is meant to give an overview of what the CLI does and how to use it. If it is set it is shown directly under the CLI name.

Defaults to: none

cli.setName(name: string): this

Set the name of the CLI (Shown at the top of the help menu)

Defaults to: none

cli.setVersion(version: string): this

Set the CLI version. Shown beside the CLI name if set.

Defaults to: none

cli.show(): this

Show the CLI.

cli.hide(): this

Hide the cli.

cli.showHelp(): this

Show the main help menu.

Comments
  • Small additions & created test

    Small additions & created test

    Changed

    • command deprecated, recommended use addCommand
    • Command.action removed last param ("done")

    Add

    • setDelimiter, addCommand, command, show, hide return CLI instance
    • getDelimiter, removeCommand, addExitCommand, getCommandsCount methods

    And...

    • Simple tests
    • tslint (Reccomended official preset)
    • Configure editorconfig
    opened by SergeShkurko 5
  • console logs from outside of the CLI function are being ignored

    console logs from outside of the CLI function are being ignored

    Hi, Thanks for this great library.

    I was implementing this in my project and noticed that only console.log() from inside the CLI function is displayed on the prompt. Is there any way to show logs from other files in the project?

    opened by prajjwaldimri 3
  • [Request] Command Aliases

    [Request] Command Aliases

    I may do a PR for this if I have time - I imagine this should be relatively simple? Basically, my feature request just an array of aliases - set as a property on addCommand. Then, you can use these to execute the command as well as the normal trigger.

    (The aliases wouldn't have to show up in help)

    enhancement 
    opened by NBTX 2
  • TS Error with option

    TS Error with option "noUnusedLocals"

    With these tsc option"noUnusedLocals": true, TSC give console errors:

    node_modules/cliffy/src/index.ts(4,19): error TS6133: 'Parameter' is declared but its value is never read.
    node_modules/cliffy/src/index.ts(10,7): error TS6133: 'columnify' is declared but its value is never read.
    
    opened by SergeShkurko 2
  • Option to not display help if a blank line is entered

    Option to not display help if a blank line is entered

    Mnay CLIs eg bash/zsh, accept an empty line as input without error. People will separate out commands to make reading easier.

    This PR adds an option to enable any blank input to be ignored. Default is the existing behaviour where the help is displayed.

    @drew-y hope this PR is ok with you; admit I couldn't think of a better option name!

    Signed-off-by: Matthew B White [email protected]

    enhancement 
    opened by mbwhite 1
  • Commands take more arguments than supported

    Commands take more arguments than supported

    I just ran the example snippet and was surprised that this is accepted as input:

    -->run foo bar
    

    The command supports only one argument; if more are provided, I would expect that the CLI yields an error message that reminds the user of the correct syntax, but the CLI seems to ignore the superflous input silently and outputs this:

    I ran to foo
    -->
    
    opened by rondonjon 1
  • Support for single and double quotes

    Support for single and double quotes

    Hope that this is ok! Thanks!

    Added support for single and double quotes. Tests for simple case, and the case where JSON is used. Updated README.md

    Signed-off-by: Matthew B. White [email protected]

    opened by mbwhite 1
  • Add support for quoted command pieces

    Add support for quoted command pieces

    This PR adds support for quoted command pieces, so rather than commands just being split by spaces, you can include a space in a command by quoting it. This allows doing something like:

    addEntry "Best entry ever"
    
    opened by localjo 1
  • Bump path-parse from 1.0.5 to 1.0.7

    Bump path-parse from 1.0.5 to 1.0.7

    Bumps path-parse from 1.0.5 to 1.0.7.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Bump glob-parent from 5.1.1 to 5.1.2

    Bump glob-parent from 5.1.1 to 5.1.2

    Bumps glob-parent from 5.1.1 to 5.1.2.

    Release notes

    Sourced from glob-parent's releases.

    v5.1.2

    Bug Fixes

    Changelog

    Sourced from glob-parent's changelog.

    5.1.2 (2021-03-06)

    Bug Fixes

    6.0.0 (2021-05-03)

    ⚠ BREAKING CHANGES

    • Correct mishandled escaped path separators (#34)
    • upgrade scaffold, dropping node <10 support

    Bug Fixes

    • Correct mishandled escaped path separators (#34) (32f6d52), closes #32

    Miscellaneous Chores

    • upgrade scaffold, dropping node <10 support (e83d0c5)
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Bump y18n from 4.0.0 to 4.0.1

    Bump y18n from 4.0.0 to 4.0.1

    Bumps y18n from 4.0.0 to 4.0.1.

    Changelog

    Sourced from y18n's changelog.

    Change Log

    All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

    5.0.5 (2020-10-25)

    Bug Fixes

    5.0.4 (2020-10-16)

    Bug Fixes

    • exports: node 13.0 and 13.1 require the dotted object form with a string fallback (#105) (4f85d80)

    5.0.3 (2020-10-16)

    Bug Fixes

    • exports: node 13.0-13.6 require a string fallback (#103) (e39921e)

    5.0.2 (2020-10-01)

    Bug Fixes

    5.0.1 (2020-09-05)

    Bug Fixes

    5.0.0 (2020-09-05)

    ⚠ BREAKING CHANGES

    • exports maps are now used, which modifies import behavior.
    • drops Node 6 and 4. begin following Node.js LTS schedule (#89)

    Features

    ... (truncated)

    Commits
    Maintainer changes

    This version was pushed to npm by oss-bot, a new releaser for y18n since your current version.


    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Feature suggestions

    Feature suggestions

    Been playing around with this for a CLI client before building a full on GUI. Had some ideas:

    1. Tab support - command name or if sub command is next suggest that instead
    2. Support single quotes for parameters - compute networkID 'a b c' currently gives a while compute networkID "a b c" gives an a b c
    3. Function to display help for a certain command. For example if I use compute for as a namespace, if I type compute without a sub command following it, then I could show a list of sub commands help as if I typed help compute

    Also curious, is it's possible to type while writing out text? I was playing with a CLI a few years ago and ran into that problem, but thinking it's probably some limitation in general. https://youtu.be/Q_E7ZFtoKY4 - I guess if that's the case then you wouldn't want to write anything to the console unless responding to a command.

    enhancement help wanted 
    opened by keverw 4
  • Custom Error Messages and Header

    Custom Error Messages and Header

    I would like to start off that the tool is exactly what I needed only I miss out on the following:

    • Customize Error (Command not Found)
    • Maybe set a header as ASCII Art that will come back
    enhancement help wanted 
    opened by gitdevries 1
Releases(v2.0.0)
  • v2.0.0(Nov 9, 2018)

    2.0.0 - 9 November 2018

    Added

    • Support for optional parameters
    • Support for rest parameters

    Changed

    • The options are specified with { label: string } instead of { option: string }.
    • Most CLI methods return a reference to this, allowing method chaining.
    • command and commands methods have been renamed to addCommand and addCommands respectively
    • If an action does not return a promise, it is assumed to be synchronous. done is no longer required.

    Removed

    • Action functions are no longer passed done. Return a promise instead.

    Deprecated

    • command - use addCommand instead.
    • commands - use addCommands instead.
    • registerCommands - use addCommands instead.
    Source code(tar.gz)
    Source code(zip)
Owner
Drew Youngwerth
VersaBuilt Robotics Inc.
Drew Youngwerth
Terminal ui for discord with interactive terminal

dickord why No fucking clue i was bored or something. why does it look dogshit Try and find a node module that supports terminal functions like trauma

Hima 3 Nov 7, 2022
➰ It's never been easier to try nodejs modules!

trymodule A simple cli tool for trying out different nodejs modules. Installation npm install -g trymodule Usage trymodule colors Downloads the module

Victor Bjelkholm 1.1k Dec 3, 2022
Tasks Management CLI application with Nodejs, Mongodb, inquirer.js, and commander

Tasks CLI Tasks CLI is a program to manage your tasks in a database using terminal or console. This is a sample project for beginners Requirements Nod

Fazt Web 9 Nov 17, 2022
NodeJS built CLI, allows to spell check in 14 languages, get Coleman-Liau Index and build hash Pyramids

Magic CLI ?? ?? NodeJS built CLI, allows to spell check in 14 languages, get Coleman-Liau Index and build hash Pyramids Installing Install dependencie

Lucas 3 Sep 27, 2022
Node.js Open CLI Framework. Built with 💜 by Heroku.

oclif: Node.JS Open CLI Framework ?? Description ?? Getting Started Tutorial ✨ Features ?? Requirements ?? CLI Types ?? Usage ?? Examples ?? Commands

oclif 8k Jan 4, 2023
Started pack for working with the new GameTest Framework API. Usable in windows, and mobile in worlds and realms!

GameTest FrameWork GameTest FrameWork is a new feature in Minecraft Bedrock Edition. This gives you the ability to script! In this example I will be u

null 40 Dec 24, 2022
A fullstack(NestJS、React) framework for building efficient and scalable applications

A fullstack(NestJS、React) framework for building efficient and scalable applications. Description The Kunlun CLI is a command-line interface tool that

图灵人工智能研究院前端技术团队 3 Mar 12, 2022
Workshop: Crafting Human Friendly CLIs with Node.js Core

$ Crafting Human Friendly CLIs with Node.js Core █ A workshop by Simon Plenderleith & Kevin Cunningham. Getting ready for the workshop 1. Required sof

Simon Plenderleith 13 Dec 26, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
GeoIP-NodeJS - Basic GeoIP coded on NodeJS for educational purposes.

IP-Tracker NodeJS Basic GeoIP coded on NodeJS for educational purposes. Tool coded on nodejs that grabs info about an IP Address. Install and Usage np

Kaixin 1 Jan 1, 2022
Json2video-nodejs-sdk - Create videos programmatically in the cloud from NodeJS: add watermarks, resize videos, create slideshows, add soundtrack, voice-over with text-to-speech (TTS), text animations.

Create videos programmatically in Node JS Create and edit videos: add watermarks, resize videos, create slideshows, add soundtrack, automate the creat

null 2 Nov 20, 2022
CLI Progress Bar implemented in NodeJS to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code

NodeJS-ProgressBar CLI Progress Bar for NodeJS and JavaScript to track Time, ETA and Steps for any long running jobs in any loops in JS, NodeJS code D

Atanu Sarkar 5 Nov 14, 2022
A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

CTSP- Create TS Project A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and conf

Jean Rodríguez 7 Sep 13, 2022
An interactive story framework.

Tale-js Tale-js is an interactive story maker, that allows you to write a story using JavaScript logic controls. There are a few requirements: // For

Jesse 4 May 23, 2022
Framework for setting up RESTful JSON APIs with NodeJS.

Restberry works with both Express and Restify! Framework for setting up RESTful JSON APIs with NodeJS. Define your models and setup CRUD API calls wit

Restberry 117 Jul 5, 2021
Component based MVC web framework for nodejs targeting good code structures & modularity.

Component based MVC web framework for nodejs targeting good code structures & modularity. Why fortjs Based on Fort architecture. MVC Framework and fol

Ujjwal Gupta 47 Sep 27, 2022
Nodeparse - A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with NodeJS.

nodeparse A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with No

Trần Quang Kha 1 Jan 8, 2022