This module serves a light version of Decaf CLI tool, providing a comprehensive set of utilities and functionalities for command-line interface operations. It encompasses several key components:
- Input Handling: Manages user input and command-line arguments processing.
- Utility Functions: Offers a collection of helper functions and constants for various operations.
- Type Definitions: Defines custom types and interfaces used throughout the module.
- Output Management: Provides different output writing strategies for flexible console output handling.
The module is designed to facilitate the creation of robust CLI applications by offering:
- Standardized input parsing and validation
- Consistent output formatting and handling
- Reusable utility functions for common CLI tasks
- Extensible architecture for adding new commands and features
It supports various output modes, including standard console output and regular expression-based output, allowing for versatile data presentation and processing. The modular structure enables easy maintenance and extension of the CLI functionality.
This module is particularly useful for developers building complex command-line tools that require structured input handling, flexible output formatting, and a rich set of utility functions.
Classes
- Command
Provides a structure for creating command-line interface commands with input handling, logging, and execution flow.
Interfaces
- AddAttachParams
Interface for attachment parameters
- AddMsgParams
Interface for message parameters
- Color
The Color interface defines a function that can be called with or without arguments to apply color styling to text or chain multiple color operations.
- CommandResult
Extends Promise with additional properties related to the command execution. This interface provides a comprehensive way to handle and interact with the results of an asynchronous command execution, including access to the command details, output logs, and the ability to abort the execution.
- Kleur
The Kleur interface provides methods for applying various colors, background colors, and text styles to strings in terminal output.
- OutputWriter
The OutputWriter interface provides a standardized set of methods for handling various types of output in a command-line interface (CLI) application. It includes methods for writing data, handling errors, and managing the program's exit process. This interface allows for consistent output handling across different parts of the application.
- ParseArgsOptionConfig
Defines the structure and behavior of a command-line option.
- ParseArgsOptionsConfig
A mapping of long option names to their configurations.
- PromiseExecutor
Provides methods to resolve or reject a promise.
Members
string
# static constant AbortCode
Standard message used when a process is manually terminated.
Code used to indicate an operation was aborted.
string
# static constant Encoding
The standard UTF-8 encoding used for text processing.
Default encoding for text operations.
# static constant JestReportersTempPathEnvKey
Constant defining the environment variable key for Jest HTML reporters
Environment variable key for Jest HTML reporters temporary directory path
string
# static constant NoCIFLag
Used to specify that a command should run outside of a Continuous Integration environment.
Flag to indicate non-CI environment.
RegExp
# static constant SemVersionRegex
A regex pattern to match and parse semantic version strings.
Regular expression for semantic versioning.
string
# static constant SetupScriptKey
Identifies the script that runs after package installation.
Key for the setup script in package.json.
# static constant VERSION
This constant stores the version number of the @asdasdasd/utils module. The actual version number is replaced during the build process, with the placeholder "##VERSION##" being substituted with the current version.
Represents the current version of the module.
# static constant colors
Defines a set of ANSI color codes used to style the banner text.
Array of ANSI color codes for banner styling.
# static constant dependencies
List of npm packages needed for reporting functionality
Array of dependencies required by the test reporter
string
# static exports.SemVersion
Defines the three levels of semantic versioning: PATCH, MINOR, and MAJOR.
Enum for semantic version components.
string
# static exports.Tokens
Defines the file names for storing different types of authentication tokens.
Enum for various authentication tokens.
Methods
# static awaitTimeout(ms) → {Promise.<void>}
Utility function that pauses execution for a given number of milliseconds.
Creates a promise that resolves after a specified time.
Parameters:
Name | Type | Description |
---|---|---|
ms |
number
|
The number of milliseconds to wait. |
A promise that resolves after the specified timeout.
Promise.<void>
# static chainAbortController(…signals) → {AbortController}
Creates a new abort controller that will be triggered if any of the provided signals are aborted.
Creates a new controller chained to multiple abort signals.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
signals |
AbortSignal
|
<repeatable> |
One or more abort signals that can trigger the new controller. |
A new abort controller connected to the signals.
AbortController
# static copyFile(source, dest) → {void}
Creates a copy of a file or directory from the source path to the destination path.
Copies a file or directory.
Parameters:
Name | Type | Description |
---|---|---|
source |
string
|
The source path of the file or directory. |
dest |
string
|
The destination path for the file or directory. |
void
# static deletePath(p) → {void}
Removes a file or directory at the specified path, with recursive and force options enabled.
Deletes a file or directory.
Parameters:
Name | Type | Description |
---|---|---|
p |
string
|
The path to the file or directory to delete. |
void
# static escapeRegExp(string) → {string}
Adds backslashes before characters that have special meaning in regular expressions, allowing the string to be used as a literal match in a RegExp.
Escapes special characters in a string for use in a regular expression.
Parameters:
Name | Type | Description |
---|---|---|
string |
string
|
The string to escape for regular expression use. |
The escaped string safe for use in regular expressions.
string
# static getAllFiles(p, filteropt) → {Array.<string>}
Traverses through directories and subdirectories to collect all file paths.
Retrieves all files recursively from a directory.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
p |
string
|
The path to start searching from. |
|
filter |
function
|
<optional> |
Optional function to filter files by name or index. |
Array of file paths.
Array.<string>
# static getDependencies(pathopt) → {Promise.<{prod: Array.<{name: string, version: string}>, dev: Array.<{name: string, version: string}>, peer: Array.<{name: string, version: string}>}>}
Executes 'npm ls --json' command to get a detailed list of all dependencies (production, development, and peer) and their versions.
Retrieves all dependencies from the project.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
path |
string
|
<optional> |
process.cwd() | The directory path of the project. |
An object containing arrays of production, development, and peer dependencies.
Promise.<{prod: Array.<{name: string, version: string}>, dev: Array.<{name: string, version: string}>, peer: Array.<{name: string, version: string}>}>
# static getPackage(popt, propertyopt) → {object|string}
Loads and parses the package.json file from a specified directory or the current working directory. Can return the entire package object or a specific property.
Retrieves package information from package.json.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
p |
string
|
<optional> |
process.cwd() | The directory path where the package.json file is located. |
property |
string
|
<optional> |
Optional. The specific property to retrieve from package.json. |
The parsed contents of package.json or the value of the specified property.
object
|
string
# static getPackageVersion(popt) → {string}
A convenience function that calls getPackage to retrieve the "version" property from package.json.
Retrieves the version from package.json.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
p |
string
|
<optional> |
process.cwd() | The directory path where the package.json file is located. |
The version string from package.json.
string
# static getSlogan(iopt) → {string}
Fetches a random slogan or a specific one by index from the slogans list.
Retrieves a slogan from the predefined list.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
i |
number
|
<optional> |
Optional index to retrieve a specific slogan. |
The selected slogan.
string
# static installDependencies(dependencies) → {Promise.<void>}
Installs production, development, and peer dependencies as specified.
Installs project dependencies.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
dependencies |
object
|
Object containing arrays of dependencies to install. |
|
prod |
Array.<string>
|
<optional> |
Production dependencies to install. |
dev |
Array.<string>
|
<optional> |
Development dependencies to install. |
peer |
Array.<string>
|
<optional> |
Peer dependencies to install. |
A promise that resolves when all dependencies are installed.
Promise.<void>
# static installIfNotAvailable(deps, dependenciesopt) → {Promise.<SimpleDependencyMap>}
Checks if specified dependencies are installed and installs any that are missing.
Installs dependencies if they are not already available.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
deps |
Array.<string>
|
string
|
The dependencies to check and potentially install. |
|
dependencies |
SimpleDependencyMap
|
<optional> |
Optional map of existing dependencies. |
Updated map of dependencies.
Promise.<SimpleDependencyMap>
# static isBrowser() → {boolean}
Checks if the code is running in a browser environment.
Determines if the current environment is a browser by checking the prototype chain of the global object.
True if the environment is a browser, false otherwise.
boolean
# static lockify(f)
This higher-order function takes a function and returns a new function that ensures sequential execution of the original function, even when called multiple times concurrently. It uses a Promise-based locking mechanism to queue function calls.
Creates a locked version of a function.
Parameters:
Name | Type | Description |
---|---|---|
f |
The function to be locked. It can take any number of parameters and return a value of type R. |
A new function with the same signature as the input function, but with sequential execution guaranteed.
# static normalizeImport(importPromise) → {Promise.<T>}
Utility function to handle module import differences between formats
Normalizes imports to handle both CommonJS and ESModule formats
Parameters:
Name | Type | Description |
---|---|---|
importPromise |
Promise.<T>
|
Promise returned by dynamic import |
Normalized module
Promise.<T>
# static padEnd(str, length, charopt) → {string}
Extends the input string to a specified length by adding a padding character to the end. If the input string is already longer than the specified length, it is returned unchanged.
Pads the end of a string with a specified character.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
str |
string
|
The input string to be padded. |
||
length |
number
|
The desired total length of the resulting string. |
||
char |
string
|
<optional> |
" " | The character to use for padding. Defaults to a space. |
If the padding character is not exactly one character long.
Error
The padded string.
string
# static patchFile(path, values) → {void}
Reads a file, applies patches using TextUtils, and writes the result back to the file.
Patches a file with given values.
Parameters:
Name | Type | Description |
---|---|---|
path |
string
|
The path to the file to be patched. |
values |
Record.<string, (number|string)>
|
The values to patch into the file. |
void
# static patchPlaceholders(input, values) → {string}
Interpolates a string by replacing placeholders of the form ${variableName} with corresponding values from the provided object. If a placeholder doesn't have a corresponding value, it is left unchanged in the string.
Replaces placeholders in a string with provided values.
Parameters:
Name | Type | Description |
---|---|---|
input |
string
|
The input string containing placeholders to be replaced. |
values |
Record.<string, (number|string)>
|
An object containing key-value pairs for replacement. |
The interpolated string with placeholders replaced by their corresponding values.
string
# static patchString(input, values, flagsopt) → {string}
Iterates through a set of key-value pairs and replaces all occurrences of each key in the input string with its corresponding value. Supports regular expression flags for customized replacement.
Replaces occurrences of keys with their corresponding values in a string.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
input |
string
|
The input string in which replacements will be made. |
||
values |
Record.<string, (number|string)>
|
An object containing key-value pairs for replacement. |
||
flags |
string
|
<optional> |
"g" | Regular expression flags to control the replacement behavior. |
The string with all specified replacements applied.
string
# static printBanner(loggeropt)
Generates and prints a colorful ASCII art banner with a random slogan.
Prints a styled banner to the console.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
logger |
Logger
|
<optional> |
Optional logger for verbose output. |
# static pushToGit() → {Promise.<void>}
Temporarily changes Git user configuration, commits all changes, pushes to remote, and restores original user configuration.
Pushes changes to Git repository.
A promise that resolves when changes are pushed.
Promise.<void>
# static readFile(path) → {string}
Reads the content of a file at the specified path and returns it as a string.
Reads a file and returns its content.
Parameters:
Name | Type | Description |
---|---|---|
path |
string
|
The path to the file to be read. |
The content of the file.
string
# static renameFile(source, dest) → {Promise.<void>}
Moves a file or directory from the source path to the destination path.
Renames a file or directory.
Parameters:
Name | Type | Description |
---|---|---|
source |
string
|
The source path of the file or directory. |
dest |
string
|
The destination path for the file or directory. |
A promise that resolves when the rename operation is complete.
Promise.<void>
# static runCommand(command, opts, outputConstructor, args) → {CommandResult}
This function runs a shell command as a child process, providing fine-grained control over its execution and output handling. It supports custom output writers, allows for command abortion, and captures both stdout and stderr.
Executes a command asynchronously with customizable output handling.
Parameters:
Name | Type | Description |
---|---|---|
command |
The command to run, either as a string or an array of strings. |
|
opts |
Spawn options for the child process. Defaults to an empty object. |
|
outputConstructor |
Constructor for the output writer. Defaults to StandardOutputWriter. |
|
args |
Additional arguments to pass to the output constructor. |
A promise that resolves to the command result of type R.
# static setPackageAttribute(attr, value, popt) → {void}
Updates a specific attribute in the package.json file with the provided value.
Sets an attribute in the package.json file.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
attr |
string
|
The attribute name to set in package.json. |
||
value |
string
|
number
|
object
|
The value to set for the attribute. |
||
p |
string
|
<optional> |
process.cwd() | The directory path where the package.json file is located. |
void
# static spawnCommand(output, command, opts, abort, logger) → {ChildProcessWithoutNullStreams}
Creates a child process to execute a command with support for piping multiple commands, custom output handling, and abort control. This function handles the low-level details of spawning processes and connecting their inputs/outputs when piping is used.
Spawns a command as a child process with output handling.
Parameters:
Name | Type | Description |
---|---|---|
output |
StandardOutputWriter.<R>
|
The output writer to handle command output. |
command |
string
|
The command to execute, can include pipe operators. |
opts |
SpawnOptionsWithoutStdio
|
Options for the spawned process. |
abort |
AbortController
|
Controller to abort the command execution. |
logger |
Logger
|
Logger for recording command execution details. |
The spawned child process.
ChildProcessWithoutNullStreams
# static toCamelCase(text) → {string}
Transforms the input string into camelCase format, where words are joined without spaces and each word after the first starts with a capital letter.
Converts a string to camelCase.
Parameters:
Name | Type | Description |
---|---|---|
text |
string
|
The input string to be converted. |
The input string converted to camelCase.
string
# static toENVFormat(text) → {string}
Transforms the input string into uppercase with words separated by underscores, typically used for environment variable names.
Converts a string to ENVIRONMENT_VARIABLE format.
Parameters:
Name | Type | Description |
---|---|---|
text |
string
|
The input string to be converted. |
The input string converted to ENVIRONMENT_VARIABLE format.
string
# static toKebabCase(text) → {string}
Transforms the input string into lowercase with words separated by hyphens.
Converts a string to kebab-case.
Parameters:
Name | Type | Description |
---|---|---|
text |
string
|
The input string to be converted. |
The input string converted to kebab-case.
string
# static toPascalCase(text) → {string}
Transforms the input string into PascalCase format, where words are joined without spaces and each word starts with a capital letter.
Converts a string to PascalCase.
Parameters:
Name | Type | Description |
---|---|---|
text |
string
|
The input string to be converted. |
The input string converted to PascalCase.
string
# static toSnakeCase(text) → {string}
Transforms the input string into lowercase with words separated by underscores.
Converts a string to snake_case.
Parameters:
Name | Type | Description |
---|---|---|
text |
string
|
The input string to be converted. |
The input string converted to snake_case.
string
# static updateDependencies() → {Promise.<void>}
Runs npm-check-updates to update package.json and then installs the updated dependencies.
Updates project dependencies to their latest versions.
A promise that resolves when dependencies are updated.
Promise.<void>
# static writeFile(path, data) → {void}
Writes the provided data to a file at the specified path.
Writes data to a file.
Parameters:
Name | Type | Description |
---|---|---|
path |
string
|
The path to the file to be written. |
data |
string
|
Buffer
|
The data to be written to the file. |
void
Type Definitions
Object
# CommandOptions
Combines input options, input option configurations, and logging configurations into a single type.
Type definition for command options.
Object
# DefaultCommandOptions
Defines the structure and default values for common command-line options used across various CLI commands.
Default command options for CLI commands.
Properties:
Name | Type | Description |
---|---|---|
verbose |
Object
|
Verbosity level option. |
type |
string
|
The type of the verbose option (number). |
short |
string
|
The short flag for the verbose option (V). |
default |
number
|
The default value for verbosity (0). |
version |
Object
|
Version display option. |
type |
string
|
The type of the version option (boolean). |
short |
string
|
The short flag for the version option (v). |
default |
undefined
|
The default value for version display (undefined). |
help |
Object
|
Help display option. |
type |
string
|
The type of the help option (boolean). |
short |
string
|
The short flag for the help option (h). |
default |
boolean
|
The default value for help display (false). |
logLevel |
Object
|
Log level option. |
type |
string
|
The type of the logLevel option (string). |
default |
string
|
The default value for log level ("info"). |
logStyle |
Object
|
Log styling option. |
type |
string
|
The type of the logStyle option (boolean). |
default |
boolean
|
The default value for log styling (true). |
timestamp |
Object
|
Timestamp display option. |
type |
string
|
The type of the timestamp option (boolean). |
default |
boolean
|
The default value for timestamp display (true). |
banner |
Object
|
Banner display option. |
type |
string
|
The type of the banner option (boolean). |
default |
boolean
|
The default value for banner display (false). |
Object
# DefaultCommandValues
Creates an object with the default values of all options defined in DefaultCommandOptions.
Default command values derived from DefaultCommandOptions.
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
key: string |
unknown
|
<optional> |
The default value for each option in DefaultCommandOptions. |
Object
# DependencyMap
Represents the structure of project dependencies categorized by type (production, development, peer). Each category contains an array of objects with name and version information.
Map of project dependencies with detailed information.
Properties:
Name | Type | Description |
---|---|---|
prod |
Array.<{name: string, version: string}>
|
Production dependencies with name and version. |
dev |
Array.<{name: string, version: string}>
|
Development dependencies with name and version. |
peer |
Array.<{name: string, version: string}>
|
Peer dependencies with name and version. |
prod |
Array
|
|
prod[].name |
string
|
|
prod[].version |
string
|
|
dev |
Array
|
|
dev[].name |
string
|
|
dev[].version |
string
|
|
peer |
Array
|
|
peer[].name |
string
|
|
peer[].version |
string
|
# EnvironmentFactory(args)
Defines a function type that creates and returns Environment instances.
Factory type for creating Environment instances.
Parameters:
Name | Type | Description |
---|---|---|
args |
Array
|
object
# InputOptions
Defines the structure of input options for CLI commands.
Interface for input options.
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
verbose |
number
|
<optional> |
The verbosity level. |
version |
boolean
|
<optional> |
Flag to show version information. |
banner |
boolean
|
<optional> |
Flag to show banner. |
help |
boolean
|
<optional> |
Flag to show help information. |
verbose |
number
|
<optional> |
|
version |
boolean
|
<optional> |
|
banner |
boolean
|
<optional> |
|
help |
boolean
|
<optional> |
Object
# MdCode
Represents a code block with optional language specification
Code block element type in markdown
Properties:
Name | Type | Description |
---|---|---|
code |
MdCodeDefinition
|
The code block definition object |
code |
MdCodeDefinition
|
Object
# MdCodeDefinition
Defines the structure for code blocks
Code block definition type in markdown
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
language |
string
|
<optional> |
Optional programming language specification |
content |
string
|
Array.<string>
|
The code content as string or array of strings |
|
language |
string
|
<optional> |
|
content |
string
|
Array
|
MdSingleLine
|
MdMultiLine
|
MdImage
|
MdListItem
|
MdTable
|
MdCode
|
MdSeparator
|
MdLink
# MdElements
Represents all possible markdown elements that can be used in document generation. This type combines various markdown elements including headers, paragraphs, images, lists, tables, code blocks, separators, and links into a union type for flexible markdown content creation.
Markdown element type definition
Object
# MdImage
Represents an image element with its properties
Image element type in markdown
Properties:
Name | Type | Description |
---|---|---|
img |
MdImageDefinition
|
The image definition object |
img |
MdImageDefinition
|
Object
# MdImageDefinition
Defines the structure for image elements
Image definition type in markdown
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
title |
string
|
<optional> |
Optional image title |
source |
string
|
Image source URL |
|
alt |
string
|
<optional> |
Optional alternative text |
title |
string
|
<optional> |
|
source |
string
|
||
alt |
string
|
<optional> |
Object
# MdLink
Represents a hyperlink with title and source
Link element type in markdown
Properties:
Name | Type | Description |
---|---|---|
link |
Object
|
The link definition object |
link |
object
|
|
title |
string
|
|
source |
string
|
"p"
|
"blockquote"
# MdMultiLineElement
Defines the available multi-line element types
Multi-line element types in markdown
Object
# MdSeparator
Represents a horizontal rule separator
Horizontal rule element type in markdown
Properties:
Name | Type | Description |
---|---|---|
hr |
string
|
The horizontal rule representation |
hr |
string
|
"h1"
|
"h2"
|
"h3"
|
"h4"
|
"h5"
|
"h6"
# MdSingleLineElement
Represents the possible header levels in markdown
Single line markdown element type
Object
# MdTable
Represents a table structure with headers and rows
Table element type in markdown
Properties:
Name | Type | Description |
---|---|---|
table |
MdTableDefinition
|
The table definition object |
table |
MdTableDefinition
|
Object
# MdTableDefinition
Defines the structure for table elements
Table definition type in markdown
Properties:
Name | Type | Description |
---|---|---|
headers |
Array.<string>
|
Array of table header names |
rows |
Array.<Object>
|
Array of row objects containing column values |
headers |
Array
|
|
rows |
Array
|
|
rows[].column: |
string
|
Array
|
string |
Object
# OptionToken
Can be either an option with a value or an option without a value.
Represents a parsed command-line option token.
Properties:
Name | Type | Description |
---|---|---|
kind |
"option"
|
|
index |
number
|
|
name |
string
|
|
rawName |
string
|
|
value |
string
|
|
inlineValue |
boolean
|
|
kind |
"option"
|
|
index |
number
|
|
name |
string
|
|
rawName |
string
|
|
value |
undefined
|
|
inlineValue |
undefined
|
"stdout"
|
"stderr"
# OutputType
A union type for standard output and standard error streams.
Represents the type of output stream.
object
# OutputWriterConstructor
Defines the structure for creating new output writer instances. This type represents a constructor function that takes a PromiseExecutor and additional arguments to create a new instance of an output writer. It allows for flexible creation of different types of output writers while maintaining a consistent interface.
Constructor type for output writers.
Properties:
Name | Type | Description |
---|---|---|
cmd: |
C
|
string, lock: PromiseExecutor<R, E>, ...args: unknown[] |
Object
# ParseArgsResult
Contains parsed values, positional arguments, and optionally the parsed tokens.
The result of parsing command-line arguments.
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
values |
string
|
boolean
|
Array.<string>
|
Array.<boolean>
|
undefined
|
Parsed option values. |
|
positionals |
Array.<string>
|
Positional arguments. |
|
tokens |
Array.<Token>
|
<optional> |
Parsed tokens (if requested). |
values |
object
|
||
p: |
string
|
boolean
|
Array
|
undefined
|
string |
|
positionals |
Array
|
||
tokens |
Array
|
<optional> |
"json"
|
"image"
|
"text"
|
"md"
# PayloadType
Union type for payload types
Types of payloads that can be handled
Object
# SimpleDependencyMap
Represents a simplified structure of project dependencies categorized by type. Each category contains an optional array of dependency names without version information.
Simplified map of project dependencies.
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
prod |
Array.<string>
|
<optional> |
Optional array of production dependency names. |
dev |
Array.<string>
|
<optional> |
Optional array of development dependency names. |
peer |
Array.<string>
|
<optional> |
Optional array of peer dependency names. |
prod |
Array
|
<optional> |
|
dev |
Array
|
<optional> |
|
peer |
Array
|
<optional> |
OptionToken
|
Object
# Token
Can be an option, a positional argument, or an option terminator.
Represents a parsed command-line token.
Properties:
Name | Type | Description |
---|---|---|
kind |
"positional"
|
|
index |
number
|
|
value |
string
|
|
kind |
"option-terminator"
|
|
index |
number
|