@dovenv/core
Version:
Quickly and easily set up your environment for your code projects
1,213 lines (1,193 loc) • 40.8 kB
TypeScript
import * as _dovenv_utils from '@dovenv/utils';
import { color, line, icon, table, box, highlight, ValidateAnyType, exec, createCli, validate, promptLine, promptLineGroup, PackageJSON, cache, RuntimeData, PackageManagerData, PackageData, getPaths } from '@dovenv/utils';
import * as ora from 'ora';
import * as consola from 'consola';
import * as yargs from 'yargs';
type Line = NonNullable<Parameters<typeof line>[0]>;
declare class CommandStyle {
color: typeof color;
line: typeof line;
icon: typeof icon;
/**
* Indent text.
*
* @param {string} v - text.
* @param {string} [prefix] - prefix
* @returns {string} Text indented
*/
indent: (v: string, prefix?: string) => string;
main: {
icon: string | undefined;
/** Main title */
h1: (v: unknown) => string;
/** General title */
h: (v: unknown) => string;
/** General text */
text: (v: unknown) => string;
msg: (t: string, msg?: unknown) => string;
code: ({ desc: descV, code: codeV, lang, readmore, }: {
desc: string;
code: string;
lang?: string;
readmore?: string;
}) => string;
/** List key */
lk: (v: unknown) => string;
/** List value */
lv: (v: unknown) => string;
/** List item */
li: (k: unknown, v: unknown) => string;
/** Unordered list */
ul: (list: Array<[unknown, unknown]>) => string;
/** Paragraph */
p: (v: unknown) => string;
/** Anchor */
a: (msg: string) => string;
/** Bold */
b: (msg: unknown) => string;
/** Badge */
badge: (msg: unknown) => string;
/** Line / sepator */
hr: (title?: string, titleAlign?: Line["titleAlign"], dim?: boolean) => string;
};
section: {
icon: string | undefined;
/** Main title */
h1: (v: unknown) => string;
/** General title */
h: (v: unknown) => string;
/** General text */
text: (v: unknown) => string;
msg: (t: string, msg?: unknown) => string;
code: ({ desc: descV, code: codeV, lang, readmore, }: {
desc: string;
code: string;
lang?: string;
readmore?: string;
}) => string;
/** List key */
lk: (v: unknown) => string;
/** List value */
lv: (v: unknown) => string;
/** List item */
li: (k: unknown, v: unknown) => string;
/** Unordered list */
ul: (list: Array<[unknown, unknown]>) => string;
/** Paragraph */
p: (v: unknown) => string;
/** Anchor */
a: (msg: string) => string;
/** Bold */
b: (msg: unknown) => string;
/** Badge */
badge: (msg: unknown) => string;
/** Line / sepator */
hr: (title?: string, titleAlign?: Line["titleAlign"], dim?: boolean) => string;
};
error: {
icon: string | undefined;
/** Main title */
h1: (v: unknown) => string;
/** General title */
h: (v: unknown) => string;
/** General text */
text: (v: unknown) => string;
msg: (t: string, msg?: unknown) => string;
code: ({ desc: descV, code: codeV, lang, readmore, }: {
desc: string;
code: string;
lang?: string;
readmore?: string;
}) => string;
/** List key */
lk: (v: unknown) => string;
/** List value */
lv: (v: unknown) => string;
/** List item */
li: (k: unknown, v: unknown) => string;
/** Unordered list */
ul: (list: Array<[unknown, unknown]>) => string;
/** Paragraph */
p: (v: unknown) => string;
/** Anchor */
a: (msg: string) => string;
/** Bold */
b: (msg: unknown) => string;
/** Badge */
badge: (msg: unknown) => string;
/** Line / sepator */
hr: (title?: string, titleAlign?: Line["titleAlign"], dim?: boolean) => string;
};
warn: {
icon: string | undefined;
/** Main title */
h1: (v: unknown) => string;
/** General title */
h: (v: unknown) => string;
/** General text */
text: (v: unknown) => string;
msg: (t: string, msg?: unknown) => string;
code: ({ desc: descV, code: codeV, lang, readmore, }: {
desc: string;
code: string;
lang?: string;
readmore?: string;
}) => string;
/** List key */
lk: (v: unknown) => string;
/** List value */
lv: (v: unknown) => string;
/** List item */
li: (k: unknown, v: unknown) => string;
/** Unordered list */
ul: (list: Array<[unknown, unknown]>) => string;
/** Paragraph */
p: (v: unknown) => string;
/** Anchor */
a: (msg: string) => string;
/** Bold */
b: (msg: unknown) => string;
/** Badge */
badge: (msg: unknown) => string;
/** Line / sepator */
hr: (title?: string, titleAlign?: Line["titleAlign"], dim?: boolean) => string;
};
success: {
icon: string | undefined;
/** Main title */
h1: (v: unknown) => string;
/** General title */
h: (v: unknown) => string;
/** General text */
text: (v: unknown) => string;
msg: (t: string, msg?: unknown) => string;
code: ({ desc: descV, code: codeV, lang, readmore, }: {
desc: string;
code: string;
lang?: string;
readmore?: string;
}) => string;
/** List key */
lk: (v: unknown) => string;
/** List value */
lv: (v: unknown) => string;
/** List item */
li: (k: unknown, v: unknown) => string;
/** Unordered list */
ul: (list: Array<[unknown, unknown]>) => string;
/** Paragraph */
p: (v: unknown) => string;
/** Anchor */
a: (msg: string) => string;
/** Bold */
b: (msg: unknown) => string;
/** Badge */
badge: (msg: unknown) => string;
/** Line / sepator */
hr: (title?: string, titleAlign?: Line["titleAlign"], dim?: boolean) => string;
};
info: {
icon: string | undefined;
/** Main title */
h1: (v: unknown) => string;
/** General title */
h: (v: unknown) => string;
/** General text */
text: (v: unknown) => string;
msg: (t: string, msg?: unknown) => string;
code: ({ desc: descV, code: codeV, lang, readmore, }: {
desc: string;
code: string;
lang?: string;
readmore?: string;
}) => string;
/** List key */
lk: (v: unknown) => string;
/** List value */
lv: (v: unknown) => string;
/** List item */
li: (k: unknown, v: unknown) => string;
/** Unordered list */
ul: (list: Array<[unknown, unknown]>) => string;
/** Paragraph */
p: (v: unknown) => string;
/** Anchor */
a: (msg: string) => string;
/** Bold */
b: (msg: unknown) => string;
/** Badge */
badge: (msg: unknown) => string;
/** Line / sepator */
hr: (title?: string, titleAlign?: Line["titleAlign"], dim?: boolean) => string;
};
/**
* Anchor (LINK).
*/
a: (msg: string) => string;
/**
* Paragraph.
*/
p: (v: unknown) => string;
/**
* Badge.
*/
badge: (msg: unknown) => string;
/**
* Bold.
*/
b: (msg: unknown) => string;
table(data: Parameters<typeof table>[0], opts?: Parameters<typeof table>[1]): string;
box({ data, title, border, dim, }: {
data: Parameters<typeof box>[0];
title?: string;
border?: boolean;
dim?: boolean;
}): string;
code: ({ data, title, lang, borderColor, }: {
data: Parameters<typeof box>[0];
title?: string;
lang?: NonNullable<Parameters<typeof highlight>[1]>["language"];
borderColor?: NonNullable<Parameters<typeof box>[1]>["borderColor"];
}) => string;
}
type ArgvParsed = {
bin: string;
cmds?: Command$1;
opts?: Options;
utils: CommandSuper;
};
type Command$1 = (string | number)[];
type Options = {
[x: string]: unknown;
};
type Response<V> = Promise<V> | V;
type EmptyResponse = undefined | void;
type ConstValue = string | number | boolean | Record<string, unknown>;
type ConstConfig = Record<string, ConstValue | (() => Response<ConstValue>)>;
declare const PKG_NAME: string;
declare const BIN_NAME: string;
declare const VERSION: string;
declare const HOMEPAGE: string;
declare const HELP_URL: string;
declare const CMD: {
readonly CONSTANTS: "const";
readonly CHECK: "check";
readonly TRANSFORM: "transform";
readonly ALIASES: "alias";
readonly CONFIG: "config";
readonly ALIAS_EXEC: "x";
};
declare const CONFIG_EXTS: readonly ["js", "mjs", "cjs", "ts", "mts", "cts"];
declare const OPTIONS: {
readonly KEY: {
readonly key: "key";
readonly alias: "k";
};
};
declare const GLOBAL_OPTIONS: {
readonly VERSION: {
readonly key: "version";
readonly alias: "v";
};
readonly HELP: {
readonly key: "help";
readonly alias: "h";
};
readonly CONFIG: {
readonly key: "config";
readonly alias: "c";
};
readonly VERBOSE: {
readonly key: "verbose";
};
readonly QUIET: {
readonly key: "silent";
};
};
declare const PKG_MANAGER: {
readonly BUN: "bun";
readonly NPM: "npm";
readonly PNPM: "pnpm";
readonly YARN: "yarn";
};
declare const RUNTIME: {
readonly NODE: "node";
readonly BUN: "bun";
readonly DENO: "deno";
};
declare const consts_BIN_NAME: typeof BIN_NAME;
declare const consts_CMD: typeof CMD;
declare const consts_CONFIG_EXTS: typeof CONFIG_EXTS;
declare const consts_GLOBAL_OPTIONS: typeof GLOBAL_OPTIONS;
declare const consts_HELP_URL: typeof HELP_URL;
declare const consts_HOMEPAGE: typeof HOMEPAGE;
declare const consts_OPTIONS: typeof OPTIONS;
declare const consts_PKG_MANAGER: typeof PKG_MANAGER;
declare const consts_PKG_NAME: typeof PKG_NAME;
declare const consts_RUNTIME: typeof RUNTIME;
declare const consts_VERSION: typeof VERSION;
declare namespace consts {
export {
consts_BIN_NAME as BIN_NAME,
consts_CMD as CMD,
consts_CONFIG_EXTS as CONFIG_EXTS,
consts_GLOBAL_OPTIONS as GLOBAL_OPTIONS,
consts_HELP_URL as HELP_URL,
consts_HOMEPAGE as HOMEPAGE,
consts_OPTIONS as OPTIONS,
consts_PKG_MANAGER as PKG_MANAGER,
consts_PKG_NAME as PKG_NAME,
consts_RUNTIME as RUNTIME,
consts_VERSION as VERSION,
};
}
declare class Command<Opts = undefined> {
opts: Opts | undefined;
protected utils: CommandSuper;
schema: ValidateAnyType;
Error: {
new (message: string, data?: undefined): {
data: undefined;
name: string;
message: string;
stack?: string;
cause?: unknown;
};
isError(error: unknown): error is Error;
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
stackTraceLimit: number;
};
catchError: <T>(promise: Promise<T>) => Promise<[undefined, T] | [Error]>;
description: string;
protected consts: typeof consts;
constructor(opts: Opts | undefined, utils: CommandSuper);
protected setMainTitle(title: string, desc?: string): void;
protected setTitle(): void;
protected setTime(time: string): void;
protected validateSchema<D = unknown>(data: D): Promise<D>;
protected getKeysFromArgv(avaliableKeys: string[], argv?: ArgvParsed): string[] | undefined;
}
type AliasesConfig = {
[key in string]: {
/** Description of your alias */
desc: string;
/**
* Command of your alias..
*
* @example
* {
* cmd : 'dovenv check'
* }
* @example
* {
* cmd : async () => { console.log( 'Hello World' ) }
* }
* @example
* {
* cmd : async ({exec}) => await exec.command('node ./src/bin.js')
* }
* @example
* {
* cmd : async ({exec}) => await exec.runtime('./src/bin.js')
* }
*/
cmd: string | ((params: {
/** Dovenv Configuration */
utils: Command['utils'];
/** Options passed affter cmd */
opts: string[] | undefined;
/** Execute functions */
exec: {
/**
* Executes a given command in the shell.
*
* @param {string} command - The command to be executed.
* @returns {Promise<string>} - Resolves with the output of the command.
* @example
* command('ls -la')
*/
command: typeof exec;
/**
* Executes a command in the shell based in your current JS runtime.
*
* @param {string} runtime - The runtime (e.g., `node`) to use for execution.
* @returns {Promise<string>} - Resolves with the runtime execution result.
* @example
* runtime('./src/bin.js')
*/
runtime: typeof exec;
/**
* Executes a command in the shell based in your current JS manager.
*
* @param {string} pkgManager - The package manager (e.g., `npm`, `yarn`, `pnpm`) to use for execution.
* @returns {Promise<string>} - Resolves with the output of the package manager command.
*/
pkgManager: typeof exec;
/**
* Executes dovenv command in shell.
*
* @param {string} cmd - The command to execute.
* @returns {Promise<string>} - Resolves with the binary execution output.
* @example
* current('alias') // Return the dovenv aliases
*/
current: typeof exec;
/**
* Executes a command related to a package's binary.
*
* @type {Command['utils']['execPkgBin']}
*/
pkgBin: Command['utils']['execPkgBin'];
};
/** Workspace data to be used */
data: {
/**
* The runtime to be used (e.g., `node`).
*/
runtime: string;
/**
* The package manager to be used (e.g., `npm`, `yarn`, `pnpm`).
*/
pkgManager: string;
/**
* Some package manager commands.
*/
pkgManagerCmds: ReturnType<Command['utils']['getPkgManagerCmds']>;
/**
* Workspace is a monorepo?.
*/
isMonorepo: boolean;
/**
* The binary to be executed (e.g., `eslint`, `vite`).
*/
bin: string;
};
}) => Response<void>);
};
};
declare const TYPE: {
readonly DIR: "dir";
readonly FILE: "file";
readonly CUSTOM: "custom";
};
/**
* Prettify your type for better readability.
*/
type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
type CheckType = typeof TYPE[keyof typeof TYPE];
type CheckShared = {
/** Title of your check */
title?: string;
/** Description of your check */
desc?: string;
};
type Utils = Command['utils'];
type CheckDir = CheckShared & {
/** Glob patterns of dirs for check */
patterns: string[];
/** Validation function for all dirs */
validateAll?: (data: {
/** Paths of the dirs */
paths: string[];
/** Dovenv config */
utils: Utils;
}) => Response<void>;
/** Validation function called every time a dir path is read */
validate?: (data: {
/** Path of the dir */
path: string;
/** Dovenv config */
utils: Utils;
}) => Response<void>;
};
type CheckFile = CheckShared & {
/** Glob patterns of files for check */
patterns: string[];
/** Validation function for all dirs */
validateAll?: (data: {
/** Paths of the files */
paths: string[];
/** Dovenv config */
utils: Utils;
}) => Response<void>;
/**
* Validation function. It is called every time a file path is read.
*
* @example
* const validate = async ( {path, content} ) => {
* if ( !content ) throw new Error(`File [${path}] must exist`)
* else if( content === '' ) throw new Error(`File [${path}] is empty and must have content`)
* }
*/
validate?: (data: {
/** Path of the file */
path: string;
/** Content of the file */
content?: string;
/** Dovenv config */
utils: Utils;
}) => Response<void>;
};
type CheckCustom = CheckShared & {
fn: (data: {
utils: Utils;
run: {
file: (d: CheckFile) => Promise<void>;
dir: (d: CheckDir) => Promise<void>;
};
}) => Response<void>;
};
type CheckConfigValue<T extends CheckType, V extends object> = {
/** Type of check */
type: T;
} & V;
type CheckFileConfig = Prettify<CheckConfigValue<typeof TYPE.FILE, CheckFile>>;
type CheckDirConfig = Prettify<CheckConfigValue<typeof TYPE.DIR, CheckDir>>;
type CheckCustomConfig = Prettify<CheckConfigValue<typeof TYPE.CUSTOM, CheckCustom>>;
type CheckConfig = Record<string, CheckFileConfig | CheckDirConfig | CheckCustomConfig>;
type TransformConfig = {
[key in string]: {
/** Description */
desc?: string;
/** Array of input patterns */
input: string[];
/**
* Function for transform inputs.
*
* @example ({content}) => content.trim() === '' ? 'Default content' : content
*/
fn: (data: {
/** Paths of the dirs */
path: string;
/** Content of the file */
content: string;
/** Dovenv Configuration */
utils: Command['utils'];
}) => Response<string | EmptyResponse>;
};
};
type ShowHelpFn = (loglevel?: string) => void;
type Cli$1 = Awaited<ReturnType<typeof createCli>>;
type Opt = Parameters<Cli$1['option']>[0][number] & {
/** Description of the option */
desc: string;
};
type Cmd = {
/** Description of the command */
desc: string;
/** Options for the command if there are any */
opts?: {
[key in string]: Opt;
};
/** Commands for the command if there are any */
cmds?: {
[key in string]: Cmd;
};
/** Examples of the command */
examples?: {
/** Description of the example */
desc: string;
/** Command to use */
cmd: string;
}[];
};
type CommandFn = (data: ArgvParsed & {
/** Print the usage data using the console function consoleLevel for printing. */
showHelp: ShowHelpFn;
utils: CommandUtils;
}) => Response<void>;
type CustomConfig = {
[key in string]: Cmd & {
/** Function to run the command */
fn: CommandFn;
/** Settings for your custom command */
settings?: {
/**
* Wrap the console output with the app logger.
*
* @default true
*/
wrapConsole?: boolean;
/**
* Hide the command from the help menu.
*
* @default false
*/
hide?: boolean;
};
};
};
type Config = {
/**
* Name of the project.
*/
name?: string;
/**
* Description of the project.
*/
desc?: string;
/**
* Configuration for create `custom` commands.
*/
custom?: CustomConfig;
/**
* Configuration for the `check` command.
*/
[CMD.CHECK]?: CheckConfig;
/**
* Configuration for set the constants used in templates.
*/
[CMD.CONSTANTS]?: ConstConfig;
/**
* Configuration for the `transform` command.
*/
[CMD.TRANSFORM]?: TransformConfig;
/**
* Configuration for the `aliases`.
*/
[CMD.ALIASES]?: AliasesConfig;
};
type Params = {
/**
* Configuration for dovenv.
*
* @see https://dovenv.pigeonposse.com/guide/core/api#config
*/
config?: Config;
};
type ConfigConst = NonNullable<NonNullable<CommandSuper['config']>['const']>;
/**
* Class for setting up Dovenv command utilities.
*
* @example
* const utils = new CommandSuper({ const: { pkg: myPackage, wsDir: '/workspace' } });
* console.log(utils);
*/
declare class CommandSuper {
#private;
/**
* Logger utils.
*/
log: consola.ConsolaInstance;
/**
* Validate utils (zod wraper).
*/
validate: typeof validate;
/**
* Prompt utils.
*/
prompt: typeof promptLine;
/**
* Sett a group of prompts with a single call.
*/
promptGroup: typeof promptLineGroup;
/**
* Process utils ('node:process' wrapper).
*/
process: NodeJS.Process;
/**
* Styles of the application.
*/
style: CommandStyle;
/**
* Set performance.
*/
performance: () => {
stop: () => number;
prettyStop: () => string;
};
/**
* Create spinner.
*/
spinner: typeof ora.default;
/**
* The title of the command.
* Use in internal logs and functions.
*
*/
title: string;
/**
* The dovenv configuration.
*/
config: Config | undefined;
/**
* The dovenv configuration path.
*/
get configPath(): string;
/**
* Dovenv version.
*
*/
version: string;
/**
* Help url for your command.
*/
helpURL: string;
/**
* The package.json of the workspace.
*
* Getted from the dovenv configuration: `this.config.const.pkg`.
*/
pkg: PackageJSON | undefined;
/**
* The directory of the workspace.
*
* Getted from the dovenv configuration: `this.config.const.workspaceDir` | `this.config.const.wsDir` | `process.cwd()`.
*/
wsDir: string;
/**
* The messages of the application.
*
* @protected
*/
protected message: {
pkgError: string;
noRuntime: string;
};
/**
* Use this method to add debug logic.
* This method is called when the class is instantiated.
*
* @param {... Parameters<typeof console.debug>} args - The arguments to be passed to the console.debug method.
*/
onDebug: (...args: Parameters<typeof console.debug>) => void;
/**
* Use this method to add warn logic.
* This method is called when the class is instantiated.
*
* @param {... Parameters<typeof console.warn>} args - The arguments to be passed to the console.warn method.
*/
onWarn: (...args: Parameters<typeof console.warn>) => void;
/**
* Use this method to add error logic.
* This method is called when the class is instantiated.
*
* @param {... Parameters<typeof console.erro>} args - The arguments to be passed to the console.error method.
*/
onError: (...args: Parameters<typeof console.error>) => never;
/**
* Cancel the process with the prompt line style.
*/
onCancel: () => Promise<never>;
constructor(config?: Config);
/**
*
* Use dovenv `cache` system to create a caching mechanism for storing and retrieving values of your plugin.
*
* Caches values, and returns an object with methods to interact with the cache.
*
* @param {string} id - Unique identifier for the cache.
* @param {object} values - Values to cache.
* @returns {object} An object with methods to interact with the cache.
* @example
* const { get, set } = await command.cache( 'example-setting', {
* boolean : true,
* number : 10,
* string : 'en',
* array : [
* 1,
* 2,
* 3,
* ],
* arrayMulti : [
* 'string',
* 2,
* 3,
* ],
* } )
*
* const res = {
* boolean : get( 'boolean' ),
* number : get( 'number' ),
* string : get( 'string' ),
* array : get( 'array' ),
* arrayMulti : get( 'arrayMulti' ),
* }
*
* set( {
* boolean : false,
* number : 10,
* string : 'es',
* array : [
* 0,
* 1,
* 2,
* 3,
* ],
* } )
*
* const updatedRes = get()
* console.log( {
* initRes : res,
* updatedRes,
* } )
*/
cache<V extends Record<string, unknown>>(id: string, values: V): ReturnType<typeof cache<V>>;
get monorepo(): boolean;
get runtime(): RuntimeData;
get packageManager(): PackageManagerData;
/**
* Determines if the current package is part of a monorepo.
* Checks for the presence of the `workspaces` field in the package.json.
*
* @returns {boolean} True if the package is part of a monorepo, otherwise false.
* @deprecated
*/
isMonorepo(): boolean;
/**
* Gets the package manager name.
* Checks the "packageManager" property in the package.json.
* If it doesn't exist, returns "npm".
*
* @returns {string} The package manager name.
* @deprecated
*/
getPkgManager(): _dovenv_utils.PackageManager;
/**
* Retrieves the command mappings for the detected package manager.
*
* The returned object contains commands for various package management tasks,
* such as auditing, updating, installing, and executing packages.
*
* @returns {object} An object containing package manager commands.
* @deprecated
*/
getPkgManagerCmds(): _dovenv_utils.PackageManagerCmdsValue;
/**
* Determines the runtime of the current package.
* Checks the "engines" field in the package.json.
* If it doesn't exist, throws an error.
*
* @returns {string} The runtime name.
* @deprecated
*/
getRuntime(): _dovenv_utils.Runtime;
/**
* Gets the paths of the packages in the workspace.
* If the current package is part of a monorepo managed by pnpm, it reads the package paths from the "pnpm-workspace.yaml" file.
* Otherwise, it reads the package paths from the "workspaces" field in the package.json.
*
* @returns {Promise<string[]>} An array of paths to the package.json files of the packages in the workspace.
*/
getPkgPaths(): Promise<string[]>;
/**
* Retrieves an array of package data objects containing the package name, path to the package.json file, and the package data itself.
*
* @returns {Promise<object[]>} An array of package data objects.
*/
getPkgsData(): Promise<PackageData[]>;
/**
* Resolves and normalizes file paths based on the provided input and options.
* Ensures that all returned paths are absolute and within the workspace directory.
*
* @param {string[]} input - An array of file or directory paths to process.
* @param {Omit<Parameters<typeof getPaths>[1], 'cwd'>} [opts] - Optional configuration for path resolution,
* excluding the `cwd` property, which is automatically set to the workspace directory.
* @returns {Promise<string[]>} - A promise that resolves to an array of normalized absolute paths.
*/
getPaths(input: string[], opts?: Omit<Parameters<typeof getPaths>[1], 'cwd'>): Promise<string[]>;
/**
* Gets the absolute workspace path.
*
* If the given path is not inside the workspace directory, it prepends the workspace directory path.
*
* @param {string} path - The relative or absolute path.
* @returns {string} The resolved workspace path.
*/
getWsPath(path: string): string;
/**
* Executes a binary from a local package or falls back to the package manager if it's not installed.
*
* @param {string} name - The name of the package whose binary you want to execute.
* @param {string[]} [args] - An optional array of arguments to pass to the binary.
* @param {object} opts - Options-.
* @param {string} opts.path - Custom path.
* @param {boolean} opts.forceExec - Force execution with current runtime and not check if exists in 'node_modules'.
* @param {string} opts.remoteVersion - Set version of the package. Only is used when package is not in local enviroment.
* @returns {Promise<void>} A promise that resolves when the execution is complete.
* @throws {Error} If an error occurs during execution, it triggers the `onCancel` method.
* @example
* await execPkgBin('@changesets/cli', ['--help']);
*/
execPkgBin(name: string, args?: string[], opts?: {
/**
* Custom path from package root.
* Only affects when name no exists in node_modules.
*
* @experimental
*/
path?: string;
/**
* Force execution with current package manager and not check if exists in 'node_modules'.
*
* @default false
*/
forceExec?: boolean;
/**
* Set version of the package.
* Only is used when package is not in local enviroment.
*/
remoteVersion?: string;
}): Promise<void>;
/**
* Validate data against a schema.
*
* @param {ValidateAnyType} schema - The schema to validate with.
* @param {unknown} data - The data to validate.
* @param {object} opts - Options for function.
* @param {boolean} [opts.showValid] - Show valid schema data on Error. Default: false.
* @param {boolean} [opts.validSchema] - Set a custom valid schema
* @returns {unknown} The validated data.
* @throws If the data is invalid, an error is generated with a human-readable description.
*/
validateSchema<D = unknown>(schema: ValidateAnyType, data: D, opts?: {
showValid?: boolean;
validSchema?: ValidateAnyType;
}): Promise<D>;
/**
* Retrieves matching keys from a given list of values based on a pattern.
*
* @template K - An array of string keys.
* @param {object} props - The function parameters.
* @param {K} props.input - The list of available keys.
* @param {string[]} [props.pattern] - An optional pattern to filter the keys.
* @returns {K[number][] | undefined} The matched keys, or `undefined` if no matches are found.
*/
getKeys<K extends string[]>(props: {
input: K;
pattern?: string[];
}): K[number][] | undefined;
getKey<K extends string[], V extends string>(props: {
input: K;
value?: V;
}): V | undefined;
/**
*
* Ensure data.
*
* @param {object} data -.
* @param {Record<string, unknown>} data.input - Options, if passed and not empty, will return true.
* @param {string} data.name - Name to be used in the warning message. Default: this.title.
* @returns {Promise<boolean>} - If opts is not empty, will return true, else will return false and print a warning message to the console.
*/
ensureOpts<V extends Record<string, unknown> | undefined>(data: {
input: V;
name?: string;
}): Promise<boolean>;
getOptsKeys<V extends Record<string, unknown> | undefined, P extends string | string[] | undefined>(data: {
input: V;
pattern: P;
name?: string;
}): Promise<(P extends string[] ? (string[] | undefined) : P extends string ? (string | undefined) : undefined) | undefined>;
getConsts<K extends keyof ConfigConst | undefined>(key?: K): Promise<K extends keyof ConfigConst ? ConstValue : Record<keyof ConfigConst, ConstValue>>;
/**
* Exits the process with a status code of 1, indicating an error.
*/
exitWithError(): void;
logGroup(k?: string): {
info: (t: string, m?: string) => void;
success: (t: string, m?: string) => void;
warn: (t: string, m?: string) => void;
error: (t: string, m?: string) => void;
step: (m?: string) => void;
};
/**
* Executes a callback function in parallel for each key-value pair in the input object
* that matches a specified pattern.
*
* @template V - A record type representing the input object's key-value pairs.
* @template P - A string or array of strings used as a pattern to filter the keys.
* @template R - The type of the result returned by the callback function.
* @param {object} opts - The options object.
* @param {V} opts.input - The input object containing key-value pairs to process.
* @param {P} opts.pattern - An optional pattern to filter the keys to be processed.
* @param {Function} opts.cb - A callback function executed for each matching key-value pair.
* The callback receives an object containing the key, value, and a logger.
* @returns {Promise<{[K in keyof V]: R}>} A promise that resolves to an object containing the results
* of the callback execution for each key.
*/
mapOpts<V extends Record<string, unknown>, P extends string | string[] | undefined, R>(opts: {
input?: V;
pattern?: P;
/**
* A callback function executed for each matching key-value pair.
*/
cb: (<K extends keyof V>(opts: {
key: K;
value: V[K];
/**
* Logger
*/
log: ReturnType<CommandSuper['logGroup']>;
}) => Promise<R>);
}): Promise<{}>;
/**
* Catch Promise function.
*
* If error print in console and exit from process.
*
* @template T - The expected return type.
* @param {Promise<T>} fn - The Promise to handle.
* @param {string} [title] - Optional title for the error output.
* @returns {Promise<T>} The resolved value of the Promise.
*/
catchFn<Res>(fn: Promise<Res>, title?: string): Promise<Res | undefined>;
}
type CommandUtils = CommandSuper;
/**
* Retrieves command utilities for the given workspace directory.
* If a package.json object is not provided, it reads and parses it from the workspace directory.
*
* @param {object} data - Data.
* @param {string} [data.wsDir] - The workspace directory path. Default: `process.cwd()`.
* @param {Record<string, unknown>} [data.pkg] - Optional package.json content as an object.
* @returns {Promise<CommandUtils>} - A promise that resolves to the command utilities.
* @example
* const utils = await getCommandUtils();
* console.log(utils);
*/
declare const getCommandUtils: (data?: {
/**
* The workspace directory path.
*
* @default process.cwd()
*/
wsDir?: string;
/**
* Optional package.json content as an object.
*/
pkg?: Record<string, unknown>;
}) => Promise<CommandUtils>;
/**
* Instance `Dovenv`.
*
* This is the "dovenv" class that builds the command line interface.
*
* It is similar to the cli tool but for use in `js`|`ts` projects.
*
* Provides tools for managing configurations, constants, and path transformations etc.
* Supports custom configurations and predefined commands.
* Features:
* - Validate files or directories with custom rules.
* - Manage workspace constants efficiently.
* - Transform paths with configurable patterns.
* - Extend or override default behaviors with custom configurations.
*
* ---.
*
* @see https://dovenv.pigeonposse.com/guide/core
* @example
* // Create an instance with custom configurations
* const dovenv = new Dovenv({
* config: {
* check: {
* pkg: { include: ['src/**'], ... }
* },
* }
* });
*
* // Run a predefined action
* await dovenv.run(['check', '-k', 'pkg']);
*/
declare class Dovenv {
#private;
/**
* Configuration object for commands and options of the `Dovenv` instance.
*/
config: Params['config'];
/**
* Contains Dovenv config path.
*
* This property is used for user information purposes only.
*
* If the "config" option is added via the class constructor, this option will be undefined.
* In this case you can change its value, but this may alter the behavior of the class.
* Do so at your own risk.
*/
dovenvConfigPath: string | undefined;
/**
* Creates a new `Dovenv` instance.
*
* @param {Params} [params] - Optional initialization parameters.
* @param {Params['config']} [params.config] - Configuration object for commands and options.
*/
constructor(params?: Params);
/**
* Runs the build process with the given arguments.
*
* @param {string[]} args - Arguments to pass to the run process.
* @example
* const dovenv = new Dovenv({
* config: {
* check: {
* pkg: {...}
* },
* ...
* }
* })
* await dovenv.run(['check', '-k', 'pkg'])
*/
run(args?: string[]): Promise<void>;
}
type Cli = Parameters<Parameters<typeof createCli>[0]['fn']>[0];
type Argv = Awaited<Cli['argv']>;
type CreateCliContructorParams = {
/** CLI name */
name?: string;
/** CLI version */
version?: string;
/** CLI arguments */
args?: string[];
/** CLI global options */
opts?: CustomConfig[number]['opts'];
/** CLI examples */
examples?: CustomConfig[number]['examples'];
/**
* CLI Hook.
*
* `yargs` parser.
*/
hook?: <C extends Cli>(data: {
cli: C;
argv: Argv;
}) => Response<C>;
};
type CreateCliParams = CreateCliContructorParams & NonNullable<Parameters<typeof getCommandUtils>[0]> & {
/** CLI commands */
cmds?: CustomConfig;
};
declare const createCLI: (opts?: CreateCliParams) => Promise<yargs.Argv<{}>>;
/**
* Runs the build process with the given arguments.
*
* @param {string[]} args - Arguments to pass to the build process.
* @example
* import { run } from '@dovenv/core'
*
* await run(['-c', 'my/config.js', 'check'])
*/
declare const run: (args: string[]) => Promise<void>;
/**
* Defines and returns the given configuration object.
*
* @param {...(Config | Config[])} config - The configuration object to define.
* @returns {Config} - The defined configuration object.
* @see https://dovenv.pigeonposse.com/guide/core
*
* ---
* @example
* // Example 1: A single configuration object
* export default defineConfig(config1);
* @example
* // Example 2: Multiple configurations as arguments
* export default defineConfig(config1, config2);
* @example
* // Example 3: An array of configurations
* export default defineConfig([config1, config2]);
*/
declare const defineConfig: (...config: (Config | Config[])[]) => Config;
export { Dovenv, createCLI, defineConfig, getCommandUtils, run };
export type { CommandUtils, Config, Params };