@j-o-r/sh
Version:
Execute shell commands on Linux-based systems from javascript
192 lines (191 loc) • 6.35 kB
TypeScript
export type ArgsObject = {
[x: string]: string;
};
export type RejectCallback = Function;
export type ResolveCallback = Function;
export type SHOptions = import("./SHDispatch.js").SHOptions;
export type AbortableInput = {
/**
* - Promise that resolves to user input or void if aborted.
*/
input: Promise<string | void>;
/**
* - Function to abort input collection.
*/
abort: () => void;
};
export type ExpBackoffGenerator = Object;
/**
* Template tag for building and executing shell commands.
*
* Returns an {@link SHDispatch} instance for configuration (.options()) and execution (.run(), .runSync()).
*
* Interpolation rules:
* - Arrays: Elements trimmed, newlines/tabs escaped, shell-special chars single-quoted with '\'' escape.
* - Other values: String(value) inserted as-is (NOT auto-escaped; use {@link bashEscape} for safety).
*
* SH acts as both template tag and options setter: `SH.timeout = 5000; SH`cmd``
*
* @param {TemplateStringsArray} pieces - String literals from template.
* @param {...unknown[]} args - Values to interpolate.
* @returns {SHDispatch} Command dispatcher.
* @throws {Error} If pieces contain undefined.
* @example
* const cmd = SH`echo ${'Hello'}`;
* await cmd.run(); // Executes: echo Hello
*
* // Array interpolation
* SH`ls ${['-la', '/']}`.run(); // ls '-la' '/'
*/
export const SH: any;
/**
* Changes the current working directory.
*
* @param {string} dir - Path to new directory.
* @example
* cd('/tmp');
*/
export function cd(dir: string): void;
/**
* Sleeps for a specified duration.
*
* @param {string|number} duration - Duration as '5s', '100ms', or ms number.
* @returns {Promise<void>}
* @example
* await sleep('2s');
*/
export function sleep(duration: string | number): Promise<void>;
/**
* Retries an async function up to N times with optional delays.
*
* Delay can be fixed ('1s'), generator (expBackoff()), or none.
*
* @param {number} count - Number of attempts.
* @param {string|number|ExpBackoffGenerator|Function} delayOrFn - Delay or callback if no separate fn.
* @param {Function} [fn] - Callback to retry (if delayOrFn not function).
* @returns {Promise<any>} Successful result.
* @throws {Error} Last error if all attempts fail.
* @example
* await retry(3, '1s', () => SH`curl http://unreliable`.run());
* await retry(3, expBackoff(), () => flakyOp());
*/
export function retry(count: number, a: any, b: any): Promise<any>;
/**
* Reads entire stdin as UTF-8 string. Resolves to empty string if TTY (no pipe).
*
* @returns {Promise<string|undefined>} Stdin content or undefined if TTY.
* @example
* const input = await readIn(); // Use in piped scripts
*/
export function readIn(): Promise<string | undefined>;
/**
* Prompts user for input on stdin with custom prompt.
*
* Supports aborting input collection.
*
* @param {string} prompt - Prompt text to display.
* @returns {AbortableInput} Object with input Promise and abort function.
* @example
* const {input, abort} = userIn('Enter name: ');
* const name = await input;
* // abort(); // Cancel anytime
*/
export function userIn(prompt: string): AbortableInput;
/**
* Executes a callback in a new async context (fresh callstack).
*
* Useful for parallel operations without nesting.
*
* @param {() => Promise<any>} callback - Async function to execute.
* @returns {Promise<any>} Result of callback.
* @example
* const results = await within(async () => {
* return Promise.all([SH`sleep 1; echo 1`.run(), sleep(2)]);
* });
*/
export function within(callback: () => Promise<any>): Promise<any>;
/**
* Generator for exponential backoff delays with jitter.
*
* @generator
* @param {string} [max='60s'] - Max backoff duration.
* @param {string} [rand='100ms'] - Max jitter.
* @yields {number} Next backoff ms.
* @example
* const backoff = expBackoff();
* await sleep(backoff.next().value);
*/
export function expBackoff(max?: string, rand?: string): Generator<number, void, unknown>;
/**
* Parses CLI arguments into an object.
*
* Supports --key value, -k value (no shorts grouped).
* Bares go to _[]. Duplicates error. No = syntax.
*
* Defaults to process.argv.slice(2).
*
* @param {string[]} [args=process.argv.slice(2)] - Args array.
* @returns {ArgsObject}
* @throws {Error} On invalid/dupe args.
* @example
* parseArgs(['--port', '8080', 'file.txt']); // { port: '8080', _: ['file.txt'] }
*/
export function parseArgs(args?: string[]): ArgsObject;
/**
* @typedef {Object.<string, string>} ArgsObject
* @property {string[]} _ - Array of strings, unnamed parameters
* @property {string} [key: string] - Any string key maps to a string value
* @description Parsed parameters result.
*/
/**
* @typedef {Function} RejectCallback
* @param {Error} error - The error object passed to the callback.
*/
/**
* @typedef {Function} ResolveCallback
* @param {any} [param] - Optional callback any value
*/
/**
* @typedef {import('./SHDispatch.js').SHOptions} SHOptions
*/
/**
* @typedef {Object} AbortableInput
* @property {Promise<string|void>} input - Promise that resolves to user input or void if aborted.
* @property {() => void} abort - Function to abort input collection.
*/
/**
* @typedef {Object} ExpBackoffGenerator
* @generator
* @yields {number} Backoff time in ms.
*/
/**
* Utility to determine the JavaScript type of a value.
*
* @param {any} fn - Any value to inspect.
* @returns {string} The "real" object type name (e.g., 'Array', 'Promise') or primitive typeof.
* @example
* jsType([]); // 'Array'
* jsType(Promise.resolve()); // 'Promise'
*/
export function jsType(fn: any): string;
/**
* Checks if an object has a specific own property (code-safe).
*
* @param {any} o - Object to examine.
* @param {string} p - Property name to check.
* @returns {boolean} True if the object has the own property.
*/
export function hasProp(o: any, p: string): boolean;
import Test from './Test.js';
import assert from 'node:assert';
import AsyncTracker from './AsyncTracker.js';
/**
* Escapes a string for safe use as a bash command-line argument.
*
* Handles quotes, backticks, $, newlines, etc.
*
* @param {string} x - Input string to escape.
* @returns {string} Bash-escaped string.
*/
export function bashEscape(x: string): string;
export { Test, assert, AsyncTracker };