@dovenv/utils
Version:
Utilities for dovenv
1,310 lines (1,289 loc) • 119 kB
TypeScript
import { rgbToHex, rgbToCIELab, rgbToHsl, rgbToXyz, xyzToCIELab, hslToRgb, hexToRgb } from '@vibrant/color';
import chromaJS from 'chroma-js';
import chalk from 'chalk';
import { highlight as highlight$1 } from 'cli-highlight';
import figlet from 'figlet';
import ansiAlign from 'ansi-align';
import columnify from 'columnify';
import { Options } from 'boxen';
import { TableUserConfig } from 'table/dist/src/types/api';
import * as fs from 'fs';
import { globby, globbyStream } from 'globby';
import { writeFile as writeFile$1, readFile as readFile$1 } from 'node:fs/promises';
import { LocalStorage } from 'node-localstorage';
import * as o from 'open';
import * as zod_to_json_schema from 'zod-to-json-schema';
import { Options as Options$1 } from 'zod-to-json-schema';
import { ZodType, z, ZodError } from 'zod';
import { zerialize, dezerialize } from 'zodex';
import { toZod } from 'tozod';
import { compile, Options as Options$3 } from 'json-schema-to-typescript-lite';
import { Options as Options$2 } from 'json-schema-to-zod';
import { Config } from 'ts-json-schema-generator';
import { npmRunPathEnv } from 'npm-run-path';
import { hideBin as hideBin$1 } from 'yargs/helpers';
import { Argv } from 'yargs';
import Enquirer from 'enquirer';
import * as p from '@clack/prompts';
import * as consola from 'consola';
import ora from 'ora';
import { matcher } from 'matcher';
import { markedTerminal } from 'marked-terminal';
import * as _schemastore_package from '@schemastore/package';
import { JSONSchemaForNPMPackageJsonFiles } from '@schemastore/package';
export { createWriteStream } from 'node:fs';
export { fileURLToPath } from 'node:url';
export { default as process } from 'node:process';
export { default as terminalSize } from 'terminal-size';
export { default as stringWidth } from 'string-width';
import { deepmergeCustom } from 'deepmerge-ts';
export { deepmerge, deepmergeCustom } from 'deepmerge-ts';
import { Options as Options$4 } from 'csv-parse';
import { Options as Options$5 } from 'csv-stringify';
import { parse, stringify } from 'svgson';
import { Root } from 'mdast';
import { makeBadge, Format } from 'badge-maker';
type Color$1 = typeof chalk;
type HighlightOpts = Parameters<typeof highlight$1>[1];
type Fonts = figlet.Fonts;
type GradientColors = string[] | {
color: string;
pos: number;
}[];
type GradientOpts = {
/**
The gradient can be generated using RGB or HSV interpolation. HSV usually produces brighter colors. Interpolation can be set to rgb for RGB interpolation, orhsv for HSV interpolation.
Defaults to rgb. Case insentitive.
*/
interpolation?: 'rgb' | 'hsv';
/**
Used only in the case of HSV interpolation.
Because hue can be considered as a circle, there are two ways to go from a color to another color.
HsvSpin can be either short or long, depending on if you want to take the shortest or the longest way between two colors.
Defaults to short. Case insensitive.
*/
hsvSpin?: 'short' | 'long';
};
declare const chroma: typeof chromaJS;
declare const colorConversion: {
rgb2hex: typeof rgbToHex;
rgb2CIELab: typeof rgbToCIELab;
rgb2sl: typeof rgbToHsl;
rgb2xyz: typeof rgbToXyz;
xyz2CIELab: typeof xyzToCIELab;
hslToRgb: typeof hslToRgb;
hex2rgb: typeof hexToRgb;
};
/**
* Highlights the given code using CLI highlighting.
* @param {string} code - The code to highlight.
* @param {HighlightOpts} [opts] - Optional options for highlighting.
* @param {string} [opts.language] - The language of the code to highlight. Defaults to 'auto'.
* @param {string} [opts.theme] - The theme to use for highlighting. Defaults to 'github'.
* @returns {string} - The highlighted code.
* @example
* const code = `
* function greet(name) {
* return 'Hello, ' + name + '!';
* }
* console.log(greet('World'));
* `;
*
* const highlightedCode = highlight(code, { language: 'javascript' });
* console.log(highlightedCode);
*/
declare const highlight: (code: string, opts?: HighlightOpts) => string;
/**
* Provides colors for terminal output.
* @type {object}
* @example
* console.log(color.green('This text is green'));
*/
declare const color: Color$1;
/**
* Generates a gradient string with the specified colors.
* @param {string} txt - The text to apply the gradient to.
* @param {GradientColors} colors - An array of color names or hex values.
* @param {GradientOpts} [opts] - Custom opts.
* @returns {string} - The text with the applied gradient.
* @example
* // Example usage:
* const gradientText = gradient('Gradient Text', ['red', 'yellow', 'green']);
* console.log(gradientText);
*/
declare const gradient: (txt: string, colors: GradientColors, opts?: GradientOpts) => string;
/**
* Unicode symbols with fallbacks for older terminals.
* @see https://github.com/sindresorhus/figures/blob/main/index.js
* @example
* console.log(
* icon.warning,
* icon.cross,
* icon.arrowDown,
* icon.bullet
* )
*/
declare const icon: {
readonly tick: string;
readonly info: string;
readonly warning: string;
readonly cross: string;
readonly square: string;
readonly squareSmall: string;
readonly squareSmallFilled: string;
readonly squareDarkShade: string;
readonly squareMediumShade: string;
readonly squareLightShade: string;
readonly squareTop: string;
readonly squareBottom: string;
readonly squareLeft: string;
readonly squareRight: string;
readonly squareCenter: string;
readonly circle: string;
readonly circleFilled: string;
readonly circleDotted: string;
readonly circleDouble: string;
readonly circleCircle: string;
readonly circleCross: string;
readonly circlePipe: string;
readonly circleQuestionMark: string;
readonly radioOn: string;
readonly radioOff: string;
readonly checkboxOn: string;
readonly checkboxOff: string;
readonly checkboxCircleOn: string;
readonly checkboxCircleOff: string;
readonly questionMarkPrefix: string;
readonly bullet: string;
readonly dot: string;
readonly ellipsis: string;
readonly pointer: string;
readonly pointerSmall: string;
readonly triangleUp: string;
readonly triangleUpSmall: string;
readonly triangleUpOutline: string;
readonly triangleDown: string;
readonly triangleDownSmall: string;
readonly triangleLeft: string;
readonly triangleLeftSmall: string;
readonly triangleRight: string;
readonly triangleRightSmall: string;
readonly lozenge: string;
readonly lozengeOutline: string;
readonly home: string;
readonly hamburger: string;
readonly smiley: string;
readonly mustache: string;
readonly heart: string;
readonly star: string;
readonly play: string;
readonly musicNote: string;
readonly musicNoteBeamed: string;
readonly nodejs: string;
readonly arrowUp: string;
readonly arrowDown: string;
readonly arrowLeft: string;
readonly arrowRight: string;
readonly arrowLeftRight: string;
readonly arrowUpDown: string;
readonly almostEqual: string;
readonly notEqual: string;
readonly lessOrEqual: string;
readonly greaterOrEqual: string;
readonly identical: string;
readonly infinity: string;
readonly subscriptZero: string;
readonly subscriptOne: string;
readonly subscriptTwo: string;
readonly subscriptThree: string;
readonly subscriptFour: string;
readonly subscriptFive: string;
readonly subscriptSix: string;
readonly subscriptSeven: string;
readonly subscriptEight: string;
readonly subscriptNine: string;
readonly oneHalf: string;
readonly oneThird: string;
readonly oneQuarter: string;
readonly oneFifth: string;
readonly oneSixth: string;
readonly oneSeventh: string;
readonly oneEighth: string;
readonly oneNinth: string;
readonly oneTenth: string;
readonly twoThirds: string;
readonly twoFifths: string;
readonly threeQuarters: string;
readonly threeFifths: string;
readonly threeEighths: string;
readonly fourFifths: string;
readonly fiveSixths: string;
readonly fiveEighths: string;
readonly sevenEighth: string;
readonly line: string;
readonly lineBold: string;
readonly lineDouble: string;
readonly lineDashed0: string;
readonly lineDashed1: string;
readonly lineDashed2: string;
readonly lineDashed3: string;
readonly lineDashed4: string;
readonly lineDashed5: string;
readonly lineDashed6: string;
readonly lineDashed7: string;
readonly lineDashed8: string;
readonly lineDashed9: string;
readonly lineDashed10: string;
readonly lineDashed11: string;
readonly lineDashed12: string;
readonly lineDashed13: string;
readonly lineDashed14: string;
readonly lineDashed15: string;
readonly lineVertical: string;
readonly lineVerticalBold: string;
readonly lineVerticalDouble: string;
readonly lineVerticalDashed0: string;
readonly lineVerticalDashed1: string;
readonly lineVerticalDashed2: string;
readonly lineVerticalDashed3: string;
readonly lineVerticalDashed4: string;
readonly lineVerticalDashed5: string;
readonly lineVerticalDashed6: string;
readonly lineVerticalDashed7: string;
readonly lineVerticalDashed8: string;
readonly lineVerticalDashed9: string;
readonly lineVerticalDashed10: string;
readonly lineVerticalDashed11: string;
readonly lineDownLeft: string;
readonly lineDownLeftArc: string;
readonly lineDownBoldLeftBold: string;
readonly lineDownBoldLeft: string;
readonly lineDownLeftBold: string;
readonly lineDownDoubleLeftDouble: string;
readonly lineDownDoubleLeft: string;
readonly lineDownLeftDouble: string;
readonly lineDownRight: string;
readonly lineDownRightArc: string;
readonly lineDownBoldRightBold: string;
readonly lineDownBoldRight: string;
readonly lineDownRightBold: string;
readonly lineDownDoubleRightDouble: string;
readonly lineDownDoubleRight: string;
readonly lineDownRightDouble: string;
readonly lineUpLeft: string;
readonly lineUpLeftArc: string;
readonly lineUpBoldLeftBold: string;
readonly lineUpBoldLeft: string;
readonly lineUpLeftBold: string;
readonly lineUpDoubleLeftDouble: string;
readonly lineUpDoubleLeft: string;
readonly lineUpLeftDouble: string;
readonly lineUpRight: string;
readonly lineUpRightArc: string;
readonly lineUpBoldRightBold: string;
readonly lineUpBoldRight: string;
readonly lineUpRightBold: string;
readonly lineUpDoubleRightDouble: string;
readonly lineUpDoubleRight: string;
readonly lineUpRightDouble: string;
readonly lineUpDownLeft: string;
readonly lineUpBoldDownBoldLeftBold: string;
readonly lineUpBoldDownBoldLeft: string;
readonly lineUpDownLeftBold: string;
readonly lineUpBoldDownLeftBold: string;
readonly lineUpDownBoldLeftBold: string;
readonly lineUpDownBoldLeft: string;
readonly lineUpBoldDownLeft: string;
readonly lineUpDoubleDownDoubleLeftDouble: string;
readonly lineUpDoubleDownDoubleLeft: string;
readonly lineUpDownLeftDouble: string;
readonly lineUpDownRight: string;
readonly lineUpBoldDownBoldRightBold: string;
readonly lineUpBoldDownBoldRight: string;
readonly lineUpDownRightBold: string;
readonly lineUpBoldDownRightBold: string;
readonly lineUpDownBoldRightBold: string;
readonly lineUpDownBoldRight: string;
readonly lineUpBoldDownRight: string;
readonly lineUpDoubleDownDoubleRightDouble: string;
readonly lineUpDoubleDownDoubleRight: string;
readonly lineUpDownRightDouble: string;
readonly lineDownLeftRight: string;
readonly lineDownBoldLeftBoldRightBold: string;
readonly lineDownLeftBoldRightBold: string;
readonly lineDownBoldLeftRight: string;
readonly lineDownBoldLeftBoldRight: string;
readonly lineDownBoldLeftRightBold: string;
readonly lineDownLeftRightBold: string;
readonly lineDownLeftBoldRight: string;
readonly lineDownDoubleLeftDoubleRightDouble: string;
readonly lineDownDoubleLeftRight: string;
readonly lineDownLeftDoubleRightDouble: string;
readonly lineUpLeftRight: string;
readonly lineUpBoldLeftBoldRightBold: string;
readonly lineUpLeftBoldRightBold: string;
readonly lineUpBoldLeftRight: string;
readonly lineUpBoldLeftBoldRight: string;
readonly lineUpBoldLeftRightBold: string;
readonly lineUpLeftRightBold: string;
readonly lineUpLeftBoldRight: string;
readonly lineUpDoubleLeftDoubleRightDouble: string;
readonly lineUpDoubleLeftRight: string;
readonly lineUpLeftDoubleRightDouble: string;
readonly lineUpDownLeftRight: string;
readonly lineUpBoldDownBoldLeftBoldRightBold: string;
readonly lineUpDownBoldLeftBoldRightBold: string;
readonly lineUpBoldDownLeftBoldRightBold: string;
readonly lineUpBoldDownBoldLeftRightBold: string;
readonly lineUpBoldDownBoldLeftBoldRight: string;
readonly lineUpBoldDownLeftRight: string;
readonly lineUpDownBoldLeftRight: string;
readonly lineUpDownLeftBoldRight: string;
readonly lineUpDownLeftRightBold: string;
readonly lineUpBoldDownBoldLeftRight: string;
readonly lineUpDownLeftBoldRightBold: string;
readonly lineUpBoldDownLeftBoldRight: string;
readonly lineUpBoldDownLeftRightBold: string;
readonly lineUpDownBoldLeftBoldRight: string;
readonly lineUpDownBoldLeftRightBold: string;
readonly lineUpDoubleDownDoubleLeftDoubleRightDouble: string;
readonly lineUpDoubleDownDoubleLeftRight: string;
readonly lineUpDownLeftDoubleRightDouble: string;
readonly lineCross: string;
readonly lineBackslash: string;
readonly lineSlash: string;
};
/**
* Generates ASCII art text using the specified font.
* @param {string} txt - The text to render as ASCII art.
* @param {Fonts} [font] - The font to use for rendering. Defaults to 'Standard'.
* @returns {string} - The ASCII art text.
* @example
* const asciiText = asciiFont('Hello, World!', '3-D');
* console.log(asciiText);
*/
declare const asciiFont: (txt: string, font?: Fonts) => string;
/**
* Creates a clickable hyperlink in the terminal, if supported.
* If terminal doesn't support clickable links, returns the URL string.
* @param {string} text - The text to display as the link.
* @param {string} url - The URL to link to.
* @returns {string} - The clickable hyperlink or URL string.
* @example
* const linkedText = link('Visit Clippo docs', 'https://clippo.pigeonposse.com');
* console.log(linkedText);
*/
declare const link: (text: string, url: string) => string;
/**
* Aligns text in the terminal.
*/
declare const align: typeof ansiAlign;
type TableData = unknown[][];
type TableOpts = TableUserConfig;
type BoxOpts = Options;
type ColumnOpts = columnify.GlobalOptions;
type ColumnData = Record<string, unknown> | Record<string, unknown>[];
/**
* Generates a text-based table from the provided data array.
* @param {TableData} data - The data to display in the table.
* @param {TableOpts} [options] - Optional configuration options for the table.
* @returns {string} - The text-based table.
* @see https://www.npmjs.com/package/table
* @example
* const data = [
* ['Name', 'Age', 'Country'],
* ['John', 30, 'USA'],
* ['Alice', 25, 'UK'],
* ['Bob', 35, 'Canada'],
* ];
* const tableText = table(data);
* console.log(tableText);
*/
declare const table: (data: TableData, options?: TableOpts) => string;
/**
* Creates a styled box around the provided text.
* @param {string} text - The text to display inside the box.
* @param {BoxOpts} [options] - Optional configuration options for the box.
* @returns {string} - The text with the styled box around it.
* @see https://www.npmjs.com/package/boxen
* @example
* const boxedText = box('This is a boxed text', { padding: 1 });
* console.log(boxedText);
*/
declare const box: (text: string, options?: BoxOpts) => string;
/**
* Formats data into aligned columns for better readability.
* @param {ColumnData} data - The data to format into columns.
* @param {ColumnOpts} [options] - Optional configuration options for column formatting.
* @returns {string} - The text with the data formatted into columns.
* @see https://www.npmjs.com/package/columnify
* @example
* // data for columns
* const data = [
* {
* name: 'mod1',
* description: 'some description which happens to be far larger than the max',
* version: '0.0.1',
* },
* {
* name: 'module-two',
* description: 'another description larger than the max',
* version: '0.2.0',
* }
* ];
*
* // set columns with custom config
* const columnText = columns(data, {
* showHeaders: false,
* minWidth: 20,
* config: {
* description: {
* maxWidth: 30
* }
* }
* });
*
* // print columns
* console.log(columnText);
*/
declare const columns: <Data extends ColumnData>(data: Data, options?: ColumnOpts) => string;
type LineAlign = 'left' | 'center' | 'right';
type TitleAlign = `${LineAlign}` | `top-${LineAlign}` | `bottom-${LineAlign}`;
type Color = NonNullable<Parameters<typeof box>[1]>['borderColor'];
type LineProps = {
title?: string;
lineChar?: string;
lineColor?: Color;
lineDim?: boolean;
align?: LineAlign;
titleAlign?: TitleAlign;
width?: number;
};
/**
* Generates a line with a title and customizable alignment for both the title and line.
* @param {LineProps} props - Options object
* @returns {string} Formatted line
* @throws {Error} If `width` is not between 1 and 100
*/
declare const line: (props?: LineProps) => string;
declare const resolvePath: (...paths: string[]) => string;
declare const relativePath: (from: string, to: string) => string;
declare const getExtName: (path: string) => string;
declare const getDirName: (path: string) => string;
declare const getBaseName: (path: string, suffix?: string) => string;
declare const isAbsolutePath: (path: string) => boolean;
declare const normalizePath: (path: string) => string;
declare const writeFile: typeof writeFile$1;
/**
* Find files and directories using glob patterns.
* @example const paths = await getPaths(['*', '!src']);
* console.log(paths);
* //=> ['pigeon', 'rainbow']
*/
declare const getPaths: typeof globby;
/**
* Find files and directories using glob patterns.
* @example
* for await (const path of getPathsStream('*.tmp')) {
* console.log(paths);
* }
*/
declare const getPathsStream: typeof globbyStream;
/**
* Checks if two file paths are equal after normalization.
* Normalization ensures that differences like trailing slashes or redundant path segments are ignored.
*
* ---
* @param {string} path1 - The first file path to compare.
* @param {string} path2 - The second file path to compare.
* @returns {boolean} `true` if the paths are equal, `false` otherwise.
*/
declare const arePathsEqual: (path1: string, path2: string) => boolean;
/**
* Check if a string is a valid path.
* @example
* isPath('..') // true
* isPath('foo bar') // false
* isPath('C:\\') // true
* isPath('foo\\bar') // true
* isPath('foo/bar') // true
* isPath('foo bar/baz') // false
* @param {string} str - The string to test.
* @returns {boolean} True if the string is a valid path.
*/
declare const isPath: (str: string) => boolean;
/**
* Creates a directory if it does not exist.
* @param {string} path - Path to the directory to create.
* @returns {Promise<void>} - A promise that resolves when the directory has been created.
* @example
* await ensureDir('./path/to/directory')
*/
declare const ensureDir: (path: string) => Promise<void>;
/**
* Reads the contents of a directory.
* @param {string} path - Path to the directory to read.
* @returns {Promise<import('node:fs').Dirent[]>} - A promise that resolves to an array of {@link https://nodejs.org/api/fs.html#class-fs-dirent | fs.Dirent} objects.
* @example
* const dirItems = await readDir('./path/to/directory')
*/
declare const readDir: (path: string) => Promise<fs.Dirent[]>;
/**
* Gets the file names in a directory and filters them by extension.
* @param {object} props - Function props.
* @param {string} props.path - Path to the directory.
* @param {string[]} props.extensions - Array of extensions to filter by, e.g., ['.md', '.txt'].
* @returns {Promise<string[]>} - A promise that resolves with an array of file names without extensions.
*/
declare function getFilteredFileNames({ path, extensions, }: {
path: string;
extensions: string[];
}): Promise<string[]>;
/**
* Gets the current directory.
* @param {string} [path] - An optional path to resolve the directory from.
* @returns {string} - The current directory.
* @example getCurrentDir()
*/
declare const getCurrentDir: (path?: string) => string;
/**
* Joins path segments.
* @param {...string} paths - Path segments to join.
* @returns {string} - The joined path.
* @example joinPath('user', 'pigeonposse')
*/
declare function joinPath(...paths: string[]): string;
/**
* Resolves path segments into an absolute path.
* @param {...string} paths - Path segments to resolve.
* @returns {string} - The resolved absolute path.
*/
declare const getAbsolutePath: (...paths: string[]) => string;
/**
* Validates and resolves a path with home directory replacement.
* @param {string} path - The path to validate and resolve.
* @returns {string} - The validated and resolved absolute path.
* @example
* import { validateHomeDir } from '@dovenv/utils'
*
* const path = validateHomeDir('~/Documents')
*
* console.log(path) // returns: /users/{username}/Documents
*
* const path = validateHomeDir('/Home')
*
* console.log(path) // returns same: /Home
*/
declare function validateHomeDir(path: string): string;
/**
* Reads the content of a file at the specified path.
* @param {string} path - The path of the file to read.
* @returns {Promise<string | Buffer>} - A promise that resolves to the content of the file as a string or buffer.
* @throws {Error} If an error occurs while reading the file.
* @example import { readFile } from '@dovenv/utils'
*
* try {
* const content = await readFile('./example.txt');
* console.log(content);
* } catch (error) {
* console.error('Error reading file:', error);
* }
*/
declare const readFile: typeof readFile$1;
/**
* Removes a directory and its contents if it exists.
* @param {string} path - The path of the directory to remove.
* @throws {Error} If an error occurs while removing the directory.
* @example import { removeDir } from '@dovenv/utils'
*
* try {
* await removeDir('./my/path')
* } catch (e) {
* console.log(e)
* }
*/
declare function removeDir(path: string): Promise<void>;
/**
* Removes a directory and its contents if it exists.
* @param {string} path - The path of the directory to remove.
* @throws {Error} If an error occurs while removing the directory.
* @example import { removeDirIfExist } from '@dovenv/utils'
*
* await removeDirIfExist('./my/path')
*/
declare function removeDirIfExist(path: string): Promise<void>;
/**
* Removes a file or directory if it exists.
* @param {string} path - The path of the file or directory to remove.
* @throws {Error} If an error occurs while removing the file or directory.
* @example
* try {
* await removePathIfExist('./my/path')
* } catch (e) {
* console.log(e)
* }
*/
declare function removePathIfExist(path: string): Promise<void>;
/**
* Removes a file if it exists.
* @param {string} path - The path of the file to remove.
* @throws {Error} If an error occurs while removing the file.
* @example
* try {
* await removeFile('./my/path')
* } catch (e) {
* console.log(e)
* }
*/
declare function removeFileIfExist(path: string): Promise<void>;
/**
* Removes a file.
* @param {string} path - The path of the file to remove.
* @throws {Error} If an error occurs while removing the file.
* @example
* try {
* await removeFile('./my/path')
* } catch (e) {
* console.log(e)
* }
*/
declare function removeFile(path: string): Promise<void>;
/**
* Checks if the given path points to a directory.
* @param {string} path - The path to check.
* @returns {Promise<boolean>} - A promise that resolves to true if the path points to a directory, otherwise false.
* @example import { isDirectory } from '@dovenv/utils'
*
* const isDir = await isDirectory('./my/path')
*/
declare function isDirectory(path: string): Promise<boolean>;
/**
* Creates a directory at the specified path.
* @param {string} path - The path of the directory to create.
* @throws {Error} If an error occurs while creating the directory.
* @example import { createDir } from '@dovenv/utils'
* await createDir('./my/dir')
*/
declare function createDir(path: string): Promise<void>;
/**
* Checks if a directory exists at the specified path.
* @param {string} path - The path to check.
* @returns {Promise<boolean>} - A promise that resolves to true if a directory exists at the specified path, otherwise false.
* @example import { existsDir } from '@dovenv/utils'
* const exist = await existsDir('./my/dir')
*/
declare function existsDir(path: string): Promise<boolean>;
/**
* Checks if a file exists at the specified path.
* @param {string} path - The path to the file.
* @returns {Promise<boolean>} - A promise that resolves to true if the file exists, otherwise false.
* @throws {Error} If an error occurs while checking the existence of the file.
* @example import { existsFile } from '@dovenv/utils'
*
* const existPKG = await existsFile('./package.json')
*/
declare function existsFile(path: string): Promise<boolean>;
/**
* Writes content to a file at the specified path.
* @param {string} path - The path of the file to write to.
* @param {string | Buffer} content - The content to write to the file.
* @throws {Error} If an error occurs while writing to the file.
* @example import { writeFileContent } from '@dovenv/utils'
*
* await writeFileContent('./greetFile.txt', 'Hello')
*/
declare function writeFileContent(path: string, content: string | Buffer): Promise<void>;
/**
* Checks if a file or directory exists at the specified path.
* @param {string} path - The path to check.
* @returns {Promise<boolean>} - A promise that resolves to true if a file or directory exists at the specified path, otherwise false.
* @throws {Error} If an error occurs while checking the existence of the path.
* @example import { existsPath } from '@dovenv/utils'
*
* const existPKG = await existsPath('./package.json')
*/
declare function existsPath(path: string): Promise<boolean>;
/**
* Copy a file from input path to output path.
* @param {{input: string, output: string}} options - Options object with input and output paths.
* @returns {Promise<void>} - Resolves when the file has been copied.
* @throws {Error} If there is an error copying the file.
* @example import { copyFile } from '@dovenv/utils'
*
* const copyResult = await copyFile({
* input : '/path/to/source.txt',
* output: '/path/to/destination.txt',
* })
*/
declare const copyFile: ({ input, output, }: {
input: string;
output: string;
}) => Promise<void>;
/**
* Copy a directory from input path to output path.
* @param {{input: string, output: string}} options - Options object with input and output paths.
* @returns {Promise<void>} - Resolves when the directory has been copied.
* @throws {Error} If there is an error copying the directory.
* @example
*
* const copyResult = await copyDir({
* input : '/path/to/sourceDir',
* output: '/path/to/destinationDir',
* })
*/
declare const copyDir: ({ input, output, }: {
input: string;
output: string;
}) => Promise<void>;
/**
* Creates a symbolic link from the input path to the output path.
* @param {{input: string, output: string}} options - Options object with input and output paths.
* @returns {Promise<void>} - Resolves when the symbolic link has been created.
* @throws {Error} If there is an error creating the symbolic link.
* @example import { createSymlink } from '@dovenv/utils'
*
* const symlinkResult = await createSymlink({
* input : '/path/to/source',
* output: '/path/to/destination',
* })
*/
declare const createSymlink: ({ input, output, }: {
input: string;
output: string;
}) => Promise<void>;
/**
* Creates a new instance of LocalStorage with the specified location.
* @param {string} location - The location where the local storage data will be stored.
* @returns {LocalStorage} - A new instance of LocalStorage.
* @example import { localStorage } from "@dovenv/utils"
*
* // Creates a local storage instance in the './myStorage' directory
* const storage = localStorage('./myStorage');
* // Sets an item in the local storage
* storage.setItem('key', 'value');
* // Retrieves the value of the item from the local storage
* const value = storage.getItem('key');
*/
declare function localStorage(location: string): LocalStorage;
/**
* Opens a system file or URL.
* @param {string} target - The file path or URL to open.
* @example import { open } from "@dovenv/utils"
*
* // Opens the image in the default image viewer.
* await open('pigeon.png', {wait: true});
*/
declare const open: typeof o.default;
/**
* Open an app. Cross-platform.
* @param {string} name - The app you want to open. Can be either builtin supported apps names or other name supported in platform.
* @example import { openApp } from "@dovenv/utils"
*
* // Open Xcode
* await openApp('xcode');
*/
declare const openApp: typeof o.openApp;
/**
* Resolves the directory path of a specified module entry.
* @param {object} opts - An object with options for resolving the module path.
* @param {string} opts.id - The module entry name to resolve, such as a package name.
* @param {string[]} opts.path - Optional additional path segments to join with the resolved module directory.
* @param {string} opts.from - The path to resolve the module from. Defaults to the current working directory.
* @returns {string} - The resolved directory path of the module.
* @throws {Error} If the module cannot be found in the lookup paths.
* @example
*
* const moduleDir = await getModulePath({ id: '@dovenv/utils' })
* console.log(moduleDir) // returns: {workspace}/node_modules/@dovenv/utils
*
* const moduleFile = await getModulePath({ id: '@dovenv/utils', path: ['dist','main.mjs'] })
* console.log(moduleFile) // returns: {workspace}/node_modules/@dovenv/utils/index.js
*/
declare const getModulePath: ({ from, id, path, }: {
/**
* The path to resolve the module from.
* @default process.cwd()
*/
from?: string;
/** The module entry name to resolve, such as a package name*/
id: string;
/** Optional additional path segments to join with the resolved module directory. */
path?: string[];
}) => Promise<string>;
declare const getFileText: (path: string) => Promise<string>;
/**
* Fetch content from a URL to string.
* @param {string} url - URL of the resource.
* @returns {Promise<string>} - The fetched content.
* @throws {Error} If there is an error fetching content from the URL.
* @example import { fetch2string } from '@dovenv/utils'
*
* const imageData = await fetch2string('https://source.unsplash.com/random')
* console.log(imageData)
*/
declare function fetch2string(url: string): Promise<string>;
/**
* Retrieves a string from either a file specified by path or a URL.
* Supports fetching remote content via URLs and reading local files.
* @param {string} input - Path to a file or URL of the resource.
* @returns {Promise<string>} - The string retrieved from the file or URL.
* @throws {Error} If there is an error fetching data or parsing the string.
* @example import { getStringFrom } from "@dovenv/utils"
*
* const stringFromYamlUrl = await getStringFrom( 'https://raw.githubusercontent.com/pigeonposse/super8/main/.pigeonposse.yml' )
* const stringFromJSON = await getStringFrom('/my/file.json')
*
* console.log( stringFromYamlUrl, stringFromJSON )
*/
declare const getStringFrom: (input: string) => Promise<string>;
/**
*
* Fetches all strings from a given patterns (URLs or paths).
* @param {string[]} patterns - An array of strings with URLs or paths.
* @returns {Promise<object[]>} - The fetched content.
* @throws {Error} If there is an error fetching content from the URLs or paths.
* @example import { getStringsFrom } from '@dovenv/utils'
*
* const patterns = [
* 'https://pigeonposse.com', // fetches and returns content as a string
* './docs/*.md', // reads files matching the pattern and returns content as strings
* 'Just a simple string' // returns the same string as provided
* ];
*
* const data = await getStringsFrom(patterns);
* console.log(data);
*/
declare const getStringsFrom: (patterns: string[]) => Promise<({
type: "path";
path: string;
id: string;
content: string;
} | {
type: "url";
path: string;
id: string;
content: string;
} | {
type: "text";
id: string;
content: string;
path?: undefined;
})[]>;
/**
* Creates a caching mechanism for storing and retrieving values.
* @param {object} params - Parameters for configuring the cache.
* @param {string} params.id - Unique identifier for the cache.
* @param {object} params.values - Initial values to cache.
* @param {string} params.projectName - Name of the project to use for configuration.
* @param {string } [params.cwd] - The current working directory. Defaults to process.
* @returns {object} - An object with methods to interact with the cache.
* @throws {Error} If the cache value is unexpected or not found.
* @example import { cache } from "@dovenv/utils"
*
* const { get, set } = await cache({
* projectName: 'myApp',
* id: 'userSettings',
* values: {
* theme: 'dark',
* language: 'en'
* },
* });
*
* // Set a new value in the cache
* set({ theme: 'light' });
*
* // Retrieve a value from the cache
* const theme = get('theme');
* console.log(theme); // Output: 'light'
*
* // Retrieve all cached values
* const allValues = get();
* console.log(allValues); // Output: { theme: 'light', language: 'en' }
*
* // Handle unexpected cache value
* try {
* const nonExistentValue = get('nonExistent');
* } catch (error) {
* console.error('Error:', error.message); // Output: Cache value is unexpected: nonExistent
* }
*/
declare const cache: <Values extends Record<string, unknown>>({ id, values, projectName, cwd, }: {
/**
* Project name for search cache.
* You can reuse the same cache for multiple instances.
*/
projectName: string;
/**
* Identifier for the values.
*/
id: string;
/**
* Cache Default Values.
*/
values: Values;
/**
* Directory to save cache file.
* Default: System default user config directory.
* You most likely don't need this. Please don't use it unless you really have to.
*/
cwd?: string;
}) => Promise<{
/**
* The default values for the cache.
*/
defaultValues: Values;
/**
* Retrieve a value from the cache.
* @example
* const theme = get('theme');
* console.log(theme); // Output: 'light'
*/
get: <ID extends ((keyof Values) | undefined) = undefined>(v?: ID) => ID extends (keyof Values) ? Values[ID] : Values;
/**
* Updates the cache with the provided values.
*
* Merges the existing cached values with the new partial values and updates the cache.
*/
set: (obj: Partial<Values>) => void;
/**
* Resets the cache to its default values.
* @example
* reset();
*/
reset: () => void;
/**
* The path to the cache file.
*/
path: string;
}>;
/**
* Returns the path to the operating system's temporary directory.
* @returns {string} The path to the operating system's temporary directory.
*/
declare const getTempDir: () => string;
/**
* Determines the operating system.
* @returns {'windows' | 'macos' | 'linux' | 'unknown'} - The operating system. Possible values are 'linux', 'macos', or 'windows'.
*/
declare const getPlatform: () => Promise<"windows" | "macos" | "linux" | "unknown">;
/**
* Returns the operating system CPU architecture.
* @returns {'arm64' | 'x64' | 'unknown'} - The operating system CPU architecture.
*/
declare function getArch(): 'arm64' | 'x64' | 'unknown';
type DecompresFileOptions = {
input: string;
output: string;
newName?: string;
remove?: boolean;
};
type ZipDirOptions = {
input: string;
output: string;
onDone?: (n: string) => void;
onError?: (n: string, err: Error) => void;
};
type ZipFileOptions = {
input: string;
output: string;
name?: string;
onDone?: (n: string) => void;
onError?: (n: string, err: Error) => void;
};
/**
* Decompresses an archive file (zip, tar, tgz) to a specified output directory.
* @param {object} options - The options object.
* @param {string} options.input - The path to the input compressed file.
* @param {string} options.output - The directory where the file should be decompressed.
* @param {string} [options.newName] - The new name for the decompressed file or directory.
* @param {boolean} [options.remove] - Whether to remove the original compressed file after decompression.
* @example decompressFile( {
input : resolve( 'downloads', 'example-file.zip' ), // Path to the compressed file
output : resolve( 'decompressed' ), // Directory where the file should be decompressed
newName : 'renamed-decompressed-file', // New name for the decompressed file or directory (optional)
remove : true, // Remove the original compressed file after decompression
} )
*/
declare function decompressFile({ input, output, newName, remove, }: DecompresFileOptions): Promise<void>;
/**
* Zips the specified file and saves it to the output directory.
* @param {ZipFileOptions} options - An object with properties.
* @param {string} options.input - The path to the file to be zipped.
* @param {string} options.output - The directory where the zip file should be saved.
* @param {string} [options.name] - The desired name for the zip file. If not provided, the original file name with `.zip` appended will be used.
* @param {Function} [options.onDone] - A callback to be called after the zip file is created. Takes a single argument of the zip file name.
* @param {Function} [options.onError] - A callback to be called if an error occurs during the zipping process. Takes two arguments: the zip file name, and the error.
* @returns {Promise<void>}
*/
declare const zipFile: ({ input, output, name, onDone, onError, }: ZipFileOptions) => Promise<void>;
/**
* Zips the files in the specified source directory and saves them to the output directory.
* @param {ZipDirOptions} options - An object with properties.
* @param {string} options.input - The path to the source directory containing files to zip.
* @param {string} options.output - The path to the output directory where zip files will be saved.
* @param {Function} [options.onDone] - A function to be called after each zip file is created. Takes a string argument of the created zip file name.
* @param {Function} [options.onError] - A function to be called if an error occurs. Takes two arguments: the zip file name, and the error.
* @returns {Promise<void>}
*/
declare const zipFilesInDirectory: ({ input, output, onDone, onError, }: ZipDirOptions) => Promise<void>;
type GetCharsAndWordsFromPathsOptions = {
input: string[];
opts?: Parameters<typeof getPaths>[1];
};
type GetCharsAndWordsFromUrlOptions = {
input: string[];
};
type GetCharsAndWordsFromContentOptions = {
input: string[];
};
type GetCharsAndWordsFromOptions = {
paths?: GetCharsAndWordsFromPathsOptions['input'];
url?: GetCharsAndWordsFromUrlOptions['input'];
content?: GetCharsAndWordsFromContentOptions['input'];
opts?: {
paths?: GetCharsAndWordsFromPathsOptions['opts'];
};
};
type GetCharsAndWordsFromResponse = {
chars: number;
words: number;
};
/**
* Gets the total number of characters and words in all files matching the given glob pattern.
* @param {GetCharsAndWordsFromPathsOptions} param0 - An object containing the input glob pattern and options.
* @returns {Promise<{ files: number, chars: number, words: number }>} - An object with properties for the number of files, the total number of characters, and the total number of words.
* @throws {Error} If there is an error while reading the files.
*/
declare const getCountFromPaths: ({ input, opts, }: GetCharsAndWordsFromPathsOptions) => Promise<{
files: number;
chars: number;
words: number;
}>;
/**
* Gets the total number of characters and words in all files matching the given glob pattern.
* @param {GetCharsAndWordsFromPathsOptions} param0 - An object containing the input glob pattern and options.
* @returns {Promise<GetCharsAndWordsFromResponse>} - An object with the total number of characters and words.
* @throws {Error} If an error occurs while reading the files.
* @example const result = await getCharsAndWordsFromPaths({ input: ['*.md'] });
* console.log(result.chars); // Total characters
* console.log(result.words); // Total words
*/
declare const getCharsAndWordsFromPaths: ({ input, opts, }: GetCharsAndWordsFromPathsOptions) => Promise<GetCharsAndWordsFromResponse>;
/**
* Gets the total number of characters and words from the given URLs.
* @param {GetCharsAndWordsFromPathsOptions} param0 - An object containing the input URLs.
* @returns {Promise<GetCharsAndWordsFromResponse>} - An object with the total number of characters and words.
* @throws {Error} If an error occurs while fetching the URLs.
* @example const result = await getCharsAndWordsFromUrl({ input: ['https://example.com'] });
* console.log(result.chars); // Total characters
* console.log(result.words); // Total words
*/
declare const getCharsAndWordsFromUrl: ({ input }: GetCharsAndWordsFromPathsOptions) => Promise<GetCharsAndWordsFromResponse>;
/**
* Calculates the total number of characters and words from a list of string content.
* @param {GetCharsAndWordsFromContentOptions} param0 - An object containing the input strings to analyze.
* @returns {Promise<GetCharsAndWordsFromResponse>} - An object with the total number of characters and words.
* @example
* const result = await getCharsAndWordsFromContent({ input: ['Hello world!', 'This is a test.'] });
* console.log(result.chars); // Total characters
* console.log(result.words); // Total words
*/
declare const getCharsAndWordsFromContent: ({ input }: GetCharsAndWordsFromContentOptions) => Promise<GetCharsAndWordsFromResponse>;
/**
* Gets the total number of characters and words from various sources: glob pattern, URL, or string content.
* @param {object} options - Options for processing content.
* @param {string[]} [options.paths] - Glob pattern to search for files.
* @param {string} [options.url] - URL to fetch content from.
* @param {string} [options.content] - Direct string content to analyze.
* @param {GetCharsAndWordsFromOptions['opts']}[options.opts] - Additional options for processing content.
* @returns {Promise<{ chars: number, words: number }>} - Total characters and words in the content.
* @throws {Error} If an error occurs while processing.
* @example
* const result = await getCharsAndWordsFrom({ pattern: ['*.md'] });
* console.log(result.chars); // Total characters
* console.log(result.words); // Total words
*
* const resultFromUrl = await getCharsAndWordsFrom({ url: 'https://example.com/file.txt' });
* console.log(resultFromUrl);
*
* const resultFromContent = await getCharsAndWordsFrom({ content: 'Direct string content' });
* console.log(resultFromContent);
*/
declare const getCharsAndWordsFrom: ({ paths, url, content, opts, }: GetCharsAndWordsFromOptions) => Promise<{
chars: number;
words: number;
paths: {
chars: number;
words: number;
};
url: {
chars: number;
words: number;
};
content: {
chars: number;
words: number;
};
}>;
/**
* Any Array type
* Same as `any[]` type. Used only for prevent ts errors
*/
type AnyArray = any[];
/**
* Any type
* Same as `any` type. Used only for prevent ts errors
*/
type Any = any;
/**
* Values of Object
*/
type ObjectValues<Values> = Values[keyof Values];
/**
* Keys of Object
*/
type ObjectKeys<Values> = keyof Values;
/**
* DeepPartial
*/
type DeepPartial<T> = T extends object ? {
[P in keyof T]?: DeepPartial<T[P]>;
} : T;
/**
* Prettify your type for better readability
*/
type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
/**
* NonUndefined
* @description Exclude undefined from set `A`
* @example
* // Expect: "string | null"
* SymmetricDifference<string | null | undefined>;
*/
type NonUndefined<A> = A extends undefined ? never : A;
/**
* FunctionKeys
* @description Get union type of keys that are functions in object type `T`
* @example
* type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;};
*
* // Expect: "setName | someFn"
* type Keys = FunctionKeys<MixedProps>;
*/
type FunctionKeys<T extends object> = {
[K in keyof T]-?: NonUndefined<T[K]> extends Function ? K : never;
}[keyof T];
/**
* NonFunctionKeys
* @description Get union type of keys that are non-functions in object type `T`
* @example
* type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;};
*
* // Expect: "name | someKey"
* type Keys = NonFunctionKeys<MixedProps>;
*/
type NonFunctionKeys<T extends object> = {
[K in keyof T]-?: NonUndefined<T[K]> extends Function ? never : K;
}[keyof T];
/**
* AssertEqual
* @description Checks if two types `T` and `U` are equal.
* @example
* type Test = AssertEqual<string, string>; // Expected: true
* type TestFail = AssertEqual<string, number>; // Expected: false
*/
type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends (<V>() => V extends U ? 1 : 2) ? true : false;
/**
* ExpectEqual
* @description Returns the type `T` if `T` and `U` are equal; otherwise, returns `never`.
* @example
* type Test = ExpectEqual<string, string>; // Expected: string
* type TestFail = ExpectEqual<string, number>; // Expected: never
*/
type ExpectEqual<T, U> = AssertEqual<T, U> extends true ? T : never;
/**
* DeepNonNullable
* @description NonNullable that works for deeply nested structure
* @example
* type NestedProps = {
* first?: null | {
* second?: null | {
* name?: string | null |
* undefined;
* };
* };
* };
* type RequiredNestedProps = DeepNonNullable<NestedProps>;
* // Expect: {
* // first: {
* // second: {
* // name: string;
* // };
* // };
* // }
*/
type DeepNonNullable<T> = Prettify<_DeepNonNullable<T>>;
type _DeepNonNullable<T> = T extends (...args: AnyArray) => Any ? T : T extends AnyArray ? Prettify<Array<_DeepNonNullable<NonNullable<T[number]>>>> : T extends object ? Prettify<{
[P in keyof T]-?: _DeepNonNullable<NonNullable<T[P]>>;
}> : Prettify<NonNullable<T>>;
type ReturnAwaitedType<T extends (...args: Any) => Any> = Awaited<ReturnType<T>>;
/**
* DeepRequired
* @description Required that works for deeply nested structure
* @example
* type NestedProps = {
* first?: {
* second?: {
* name?: string;
* };
* };
* };
* type RequiredNestedProps = DeepRequired<NestedProps>
* // Expect: {
* // first: {
* // second: {
* // name: string;
* // };
* // };
* // }
*/
type DeepRequired<T> = Prettify<_DeepRequired<T>>;
type _DeepRequired<T> = T extends (...args: AnyArray) => Any ? T : T extends AnyArray ? Prettify<_DeepRequiredArray<T[number]>> : T extends object ? Prettify<_DeepRequiredObject<T>> : T;
type _DeepRequiredArray<T> = Array<_DeepRequired<NonUndefined<T>>>;
type _DeepRequiredObject<T> = {
[P in keyof T]-?: _DeepRequired<NonUndefined<T[P]>>;
};
type PackageJSON = JSONSchemaForNPMPackageJsonFiles;
type SetDirTreeStyleParams = {
/** Name of the file or folder */
name: string;
/** Indentation level */
indent: number;
/** Whether it is the last item in the current level */
isLast: boolean;
/** Whether it is the first item in the current level */
isFirst: boolean;
/** Whether it is a folder */
isFolder: boolean;
};
type SetDirTree = {
structure: object;
name?: string;
style?: (opts: SetDirTreeStyleParams) => string;
};
type SharedStructure = {
/**
* The maximum number of directories to traverse.
*/
max?: number;
/**
* The order to traverse the directories.
* @default 'atoz'
*/
sort?: 'atoz' | 'ztoa';
};
type DirStructureParams = SharedStructure & {
/**
* The root path of the directory to read