@appium/support
Version:
Support libs used across Appium packages
216 lines • 10.1 kB
TypeScript
import B from 'bluebird';
import { parse as shellParse } from 'shell-quote';
export { shellParse };
export { v1 as uuidV1, v3 as uuidV3, v4 as uuidV4, v5 as uuidV5 } from 'uuid';
import type { Element } from '@appium/types';
/** W3C WebDriver element identifier key used in element objects. */
export declare const W3C_WEB_ELEMENT_IDENTIFIER = "element-6066-11e4-a52e-4f735466cecf";
/** Size of one kibibyte in bytes (1024). */
export declare const KiB = 1024;
/** Size of one mebibyte in bytes (1024 * 1024). */
export declare const MiB: number;
/** Size of one gibibyte in bytes (1024 * 1024 * 1024). */
export declare const GiB: number;
/** A string which is never `''`. */
export type NonEmptyString<T extends string = string> = T extends '' ? never : T;
/**
* Type guard: returns true if the value is a non-empty string.
*
* @param val - Value to check
* @returns `true` if `val` is a string with at least one character
*/
export declare function hasContent(val: unknown): val is NonEmptyString;
/**
* Type guard: returns true if the value is not `undefined`, `null`, or `NaN`.
*
* @param val - Value to check
* @returns `true` if `val` is non-null and non-undefined (and not NaN for numbers)
*/
export declare function hasValue<T>(val: T): val is NonNullable<T>;
/**
* Escapes spaces in a string for use in command-line arguments (e.g. ` ` → `\ `).
*
* @param str - String that may contain spaces
* @returns String with spaces escaped by a backslash
*/
export declare function escapeSpace(str: string): string;
/**
* Escapes special characters in a string (backslash, slash, quotes, control chars).
* If `quoteEscape` is provided, that character is also escaped.
*
* @param str - String to escape, or non-string value (returned unchanged)
* @param quoteEscape - Optional character to escape, or `false` to skip
* @returns Escaped string, or original value if `str` is not a string
*/
export declare function escapeSpecialChars(str: string | unknown, quoteEscape?: string | false): string | unknown;
/**
* Returns the first non-internal IPv4 address of the machine, if any.
*
* @returns The local IPv4 address, or `undefined` if none found
*/
export declare function localIp(): string | undefined;
/**
* Creates a promise that resolves after a delay and can be cancelled via `.cancel()`.
*
* @param ms - Delay in milliseconds before the promise resolves
* @returns A Bluebird promise with a `cancel()` method; cancel rejects with CancellationError
*/
export declare function cancellableDelay(ms: number): B<void> & {
cancel: () => void;
};
/**
* Resolves each root path with the given path segments, returning an array of absolute paths.
*
* @param roots - Base directory paths to resolve against
* @param args - Path segments to join with each root (e.g. 'foo', 'bar' → root/foo/bar)
* @returns Array of absolute paths, one per root
*/
export declare function multiResolve(roots: string[], ...args: string[]): string[];
/**
* Parses a value as JSON if it is a string; otherwise returns the value as-is.
*
* @param obj - String (to parse) or other value (returned unchanged)
* @returns Parsed object or original value
*/
export declare function safeJsonParse<T>(obj: unknown): T;
/**
* Stringifies an object to JSON, converting Buffers to strings for readable output.
*
* @param obj - Object to serialize
* @param replacer - Optional replacer function (same as JSON.stringify)
* @param space - Indentation for pretty-printing. Defaults to 2
* @returns JSON string
*/
export declare function jsonStringify(obj: unknown, replacer?: ((key: string, value: unknown) => unknown) | null, space?: number | string): string;
/**
* Extracts the element ID from a W3C or JSONWP element object, or returns the string if already an ID.
*
* @param el - Element object (with ELEMENT or W3C identifier) or raw element ID string
* @returns The element ID string
*/
export declare function unwrapElement(el: Element | string): string;
/**
* Wraps an element ID string in an element object compatible with both W3C and JSONWP.
*
* @param elementId - The element ID to wrap
* @returns Element object with both ELEMENT and W3C identifier keys
*/
export declare function wrapElement(elementId: string): Element;
/**
* Returns a copy of the object containing only properties that pass the predicate.
* If the predicate is missing, removes properties whose values are undefined.
* If the predicate is a scalar, keeps only properties whose value equals that scalar.
* If the predicate is a function, calls it for each (value, obj) and keeps properties where it returns true.
*
* @param obj - Source object to filter
* @param predicate - Optional filter: undefined (drop undefined values), scalar (value match), or function
* @returns New object with only the properties that pass the predicate
*/
export declare function filterObject<T extends Record<string, unknown>>(obj: T, predicate?: ((value: unknown, obj: T) => boolean) | unknown): Partial<T>;
/**
* Converts a byte count to a human-readable size string (e.g. "1.50 MB").
*
* @param bytes - Number of bytes (or string coercible to a number)
* @returns Formatted string like "123 B", "1.50 KB", "2.00 MB", "3.00 GB"
* @throws {Error} If bytes cannot be converted to a non-negative integer
*/
export declare function toReadableSizeString(bytes: number | string): string;
/**
* Checks whether the given path is a subpath of the given root folder.
*
* @param originalPath - The absolute file or folder path to test
* @param root - The absolute root folder path
* @param forcePosix - If true, interpret paths in POSIX format (e.g. on Windows)
* @returns `true` if `originalPath` is under `root`
* @throws {Error} If either path is not absolute
*/
export declare function isSubPath(originalPath: string, root: string, forcePosix?: boolean | null): boolean;
/**
* Checks whether the given paths refer to the same file system entity (same inode).
* All paths must exist.
*
* @param path1 - First path
* @param path2 - Second path
* @param pathN - Additional paths to compare
* @returns `true` if all paths resolve to the same file/directory
*/
export declare function isSameDestination(path1: string, path2: string, ...pathN: string[]): Promise<boolean>;
/**
* Coerces a value to a valid semver string (e.g. "1.0" → "1.0.0").
*
* @param ver - Version string or number to coerce
* @param strict - If true, throws when coercion fails; if false, returns null
* @returns Valid semver string, or null when strict is false and coercion fails
* @throws {Error} When strict is true and ver cannot be coerced
*/
export declare function coerceVersion(ver: string, strict: true): string;
export declare function coerceVersion(ver: string, strict?: false): string | null;
/**
* Compares two version strings using the given operator.
*
* @param ver1 - First version string
* @param operator - One of: ==, !=, >, <, >=, <=, =
* @param ver2 - Second version string
* @returns `true` if ver1 operator ver2 holds (e.g. "2.0.0" >= "1.0.0")
* @throws {Error} If operator is unsupported or either version cannot be coerced
*/
export declare function compareVersions(ver1: string, operator: string, ver2: string): boolean;
/**
* Quotes and escapes command-line arguments so they can be safely passed to a shell.
*
* @param args - Single argument or array of arguments to quote
* @returns Quoted string suitable for shell parsing
*/
export declare function quote(args: string | string[]): string;
/** Options for pluralize(). */
export interface PluralizeOptions {
/** If true, prefix the result with the count (e.g. "3 ducks"). */
inclusive?: boolean;
}
/**
* Returns the plural or singular form of a word appropriate to the count (e.g. "duck" + 1 → "duck", + 2 → "ducks").
*
* @param word - The word to pluralize (or singularize when count is 1)
* @param count - The count used to choose singular vs plural
* @param options - Options object or boolean: use `inclusive: true` (or `true`) to prefix with the number (e.g. "3 ducks")
* @returns The correctly inflected word, optionally prefixed with the count
*/
export declare function pluralize(word: string, count: number, options?: PluralizeOptions | boolean): string;
/** Options for toInMemoryBase64(). */
export interface EncodingOptions {
/** Maximum size of the resulting buffer in bytes. Default 1GB. */
maxSize?: number;
}
/**
* Reads a file and returns its contents as a base64-encoded buffer.
*
* @param srcPath - Full path to the file to encode
* @param opts - Encoding options (e.g. maxSize to cap buffer size)
* @returns Buffer containing the base64-encoded file content
* @throws {Error} If the file does not exist, is a directory, cannot be read, or exceeds maxSize
*/
export declare function toInMemoryBase64(srcPath: string, opts?: EncodingOptions): Promise<Buffer>;
/** Options for getLockFileGuard(). */
export interface LockFileOptions {
/** Max time in seconds to wait for the lock. Default 120. */
timeout?: number;
/** If true, attempt to unlock and retry once if the first acquisition times out (e.g. stale lock). */
tryRecovery?: boolean;
}
/** Guard function that runs the given behavior under the lock. */
type LockFileGuardFn<T> = (behavior: () => Promise<T> | T) => Promise<T>;
/** Return type of getLockFileGuard: guard function with a .check() method. */
type LockFileGuard<T> = LockFileGuardFn<T> & {
check: () => Promise<boolean>;
};
/**
* Creates a guard that serializes access to a critical section using a lock file.
* The returned function acquires the lock, runs the given behavior, then releases the lock.
* Also exposes `.check()` to test whether the lock is currently held.
*
* @param lockFile - Full path to the lock file
* @param opts - Options (see {@link LockFileOptions})
* @returns Async function that accepts a callback to run under the lock, plus a `.check()` method
*/
export declare function getLockFileGuard<T>(lockFile: string, opts?: LockFileOptions): LockFileGuard<T>;
//# sourceMappingURL=util.d.ts.map