diff --git a/src/argv/flags.ts b/src/argv/flags.ts index 668e22626..1aba5cb4d 100644 --- a/src/argv/flags.ts +++ b/src/argv/flags.ts @@ -39,6 +39,13 @@ export type FlagInput = FlagValues | string[] | readonly string[] | undefined * Get the appropriate log level based on flags. * Returns 'silent', 'error', 'warn', 'info', 'verbose', or 'debug'. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * getLogLevel() // 'info' (default) + * getLogLevel({ quiet: true }) // 'silent' + * getLogLevel(['--debug']) // 'debug' + * ``` */ export function getLogLevel(input?: FlagInput): string { if (isQuiet(input)) { @@ -56,6 +63,12 @@ export function getLogLevel(input?: FlagInput): string { /** * Check if all flag is set. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isAll({ all: true }) // true + * isAll(['--all']) // true + * ``` */ export function isAll(input?: FlagInput): boolean { if (!input) { @@ -70,6 +83,12 @@ export function isAll(input?: FlagInput): boolean { /** * Check if changed files mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isChanged({ changed: true }) // true + * isChanged(['--changed']) // true + * ``` */ export function isChanged(input?: FlagInput): boolean { if (!input) { @@ -85,6 +104,12 @@ export function isChanged(input?: FlagInput): boolean { * Check if coverage mode is enabled. * Checks both 'coverage' and 'cover' flags. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isCoverage({ coverage: true }) // true + * isCoverage(['--cover']) // true + * ``` */ export function isCoverage(input?: FlagInput): boolean { if (!input) { @@ -99,6 +124,12 @@ export function isCoverage(input?: FlagInput): boolean { /** * Check if debug mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isDebug({ debug: true }) // true + * isDebug(['--debug']) // true + * ``` */ export function isDebug(input?: FlagInput): boolean { if (!input) { @@ -113,6 +144,12 @@ export function isDebug(input?: FlagInput): boolean { /** * Check if dry-run mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isDryRun({ 'dry-run': true }) // true + * isDryRun(['--dry-run']) // true + * ``` */ export function isDryRun(input?: FlagInput): boolean { if (!input) { @@ -127,6 +164,12 @@ export function isDryRun(input?: FlagInput): boolean { /** * Check if fix/autofix mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isFix({ fix: true }) // true + * isFix(['--fix']) // true + * ``` */ export function isFix(input?: FlagInput): boolean { if (!input) { @@ -141,6 +184,12 @@ export function isFix(input?: FlagInput): boolean { /** * Check if force mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isForce({ force: true }) // true + * isForce(['--force']) // true + * ``` */ export function isForce(input?: FlagInput): boolean { if (!input) { @@ -155,6 +204,12 @@ export function isForce(input?: FlagInput): boolean { /** * Check if help flag is set. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isHelp({ help: true }) // true + * isHelp(['-h']) // true + * ``` */ export function isHelp(input?: FlagInput): boolean { if (!input) { @@ -169,6 +224,12 @@ export function isHelp(input?: FlagInput): boolean { /** * Check if JSON output is requested. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isJson({ json: true }) // true + * isJson(['--json']) // true + * ``` */ export function isJson(input?: FlagInput): boolean { if (!input) { @@ -183,6 +244,12 @@ export function isJson(input?: FlagInput): boolean { /** * Check if quiet/silent mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isQuiet({ quiet: true }) // true + * isQuiet(['--silent']) // true + * ``` */ export function isQuiet(input?: FlagInput): boolean { if (!input) { @@ -197,6 +264,12 @@ export function isQuiet(input?: FlagInput): boolean { /** * Check if staged files mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isStaged({ staged: true }) // true + * isStaged(['--staged']) // true + * ``` */ export function isStaged(input?: FlagInput): boolean { if (!input) { @@ -211,6 +284,12 @@ export function isStaged(input?: FlagInput): boolean { /** * Check if update mode is enabled (for snapshots, dependencies, etc). * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isUpdate({ update: true }) // true + * isUpdate(['-u']) // true + * ``` */ export function isUpdate(input?: FlagInput): boolean { if (!input) { @@ -225,6 +304,12 @@ export function isUpdate(input?: FlagInput): boolean { /** * Check if verbose mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isVerbose({ verbose: true }) // true + * isVerbose(['--verbose']) // true + * ``` */ export function isVerbose(input?: FlagInput): boolean { if (!input) { @@ -239,6 +324,12 @@ export function isVerbose(input?: FlagInput): boolean { /** * Check if watch mode is enabled. * Accepts FlagValues object, process.argv array, or undefined (uses process.argv). + * + * @example + * ```typescript + * isWatch({ watch: true }) // true + * isWatch(['-w']) // true + * ``` */ export function isWatch(input?: FlagInput): boolean { if (!input) { diff --git a/src/argv/parse.ts b/src/argv/parse.ts index e56b9ce4c..aea1be669 100644 --- a/src/argv/parse.ts +++ b/src/argv/parse.ts @@ -97,6 +97,17 @@ export interface ParsedArgs> { /** * Parse command-line arguments with a Node.js parseArgs-compatible API. * Uses yargs-parser internally for robust argument parsing. + * + * @example + * ```typescript + * const { values, positionals } = parseArgs({ + * args: ['--force', '--quiet', 'file.ts'], + * options: { + * force: { type: 'boolean' }, + * quiet: { type: 'boolean', short: 'q' }, + * }, + * }) + * ``` */ export function parseArgs>( config: ParseArgsConfig = {}, @@ -206,6 +217,14 @@ export function parseArgs>( /** * Parse command-line arguments with Socket defaults. * Provides sensible defaults for Socket CLI applications. + * + * @example + * ```typescript + * const { values, positionals } = parseArgsWithDefaults({ + * args: ['--force', 'file.ts'], + * options: { force: { type: 'boolean' } }, + * }) + * ``` */ export function parseArgsWithDefaults>( config: ParseArgsConfig = {}, @@ -239,6 +258,12 @@ export const commonParseArgsConfig: ParseArgsConfig = { /** * Extract positional arguments from process.argv. * Useful for commands that accept file paths or other positional parameters. + * + * @example + * ```typescript + * // process.argv = ["node", "script.js", "src", "lib", "--verbose"] + * getPositionalArgs() // ["src", "lib"] + * ``` */ export function getPositionalArgs(startIndex = 2): string[] { const args = process.argv.slice(startIndex) @@ -260,6 +285,12 @@ export function getPositionalArgs(startIndex = 2): string[] { /** * Check if a specific flag is present in argv. + * + * @example + * ```typescript + * hasFlag('verbose') // true if --verbose is in process.argv + * hasFlag('force', ['--force', '--quiet']) // true + * ``` */ export function hasFlag(flag: string, argv = process.argv): boolean { return argv.includes(`--${flag}`) diff --git a/src/cacache.ts b/src/cacache.ts index 2d9f26405..1238629fd 100644 --- a/src/cacache.ts +++ b/src/cacache.ts @@ -41,6 +41,12 @@ export interface RemoveOptions { /** * Get the cacache module for cache operations. + * + * @example + * ```typescript + * const cacache = getCacache() + * const entries = await cacache.ls(cacheDir) + * ``` */ export function getCacache() { // cacache is imported at the top @@ -167,6 +173,12 @@ export async function clear( * Get data from the Socket shared cache by key. * @throws {Error} When cache entry is not found. * @throws {TypeError} If key contains wildcards (*) + * + * @example + * ```typescript + * const entry = await get('socket-sdk:scans:abc123') + * console.log(entry.data.toString('utf8')) + * ``` */ export async function get( key: string, @@ -186,6 +198,11 @@ export async function get( * Put data into the Socket shared cache with a key. * * @throws {TypeError} If key contains wildcards (*) + * + * @example + * ```typescript + * await put('socket-sdk:scans:abc123', Buffer.from('result data')) + * ``` */ export async function put( key: string, @@ -206,6 +223,11 @@ export async function put( * Remove an entry from the Socket shared cache by key. * * @throws {TypeError} If key contains wildcards (*) + * + * @example + * ```typescript + * await remove('socket-sdk:scans:abc123') + * ``` */ export async function remove(key: string): Promise { if (key.includes('*')) { @@ -220,6 +242,14 @@ export async function remove(key: string): Promise { /** * Get data from the Socket shared cache by key without throwing. + * + * @example + * ```typescript + * const entry = await safeGet('socket-sdk:scans:abc123') + * if (entry) { + * console.log(entry.data.toString('utf8')) + * } + * ``` */ export async function safeGet( key: string, @@ -234,6 +264,14 @@ export async function safeGet( /** * Execute a callback with a temporary directory for cache operations. + * + * @example + * ```typescript + * const result = await withTmp(async (tmpDir) => { + * // Use tmpDir for temporary cache work + * return 'done' + * }) + * ``` */ export async function withTmp( callback: (tmpDirPath: string) => Promise, diff --git a/src/cover/formatters.ts b/src/cover/formatters.ts index 940c03d65..dedf6a0b3 100644 --- a/src/cover/formatters.ts +++ b/src/cover/formatters.ts @@ -23,6 +23,12 @@ const COVERAGE_EMOJI_THRESHOLDS = [ /** * Get emoji for coverage percentage. + * + * @example + * ```typescript + * getCoverageEmoji(95) // ' \u{1F3AF}' + * getCoverageEmoji(50) // ' \u{1F528}' + * ``` */ export function getCoverageEmoji(percent: number): string { const entry = COVERAGE_EMOJI_THRESHOLDS.find( @@ -33,6 +39,18 @@ export function getCoverageEmoji(percent: number): string { /** * Format coverage data for console output. + * + * @example + * ```typescript + * const output = formatCoverage({ + * code: { + * statements: { percent: '85.00' }, + * branches: { percent: '80.00' }, + * functions: { percent: '90.00' }, + * lines: { percent: '88.00' }, + * }, + * }) + * ``` */ export function formatCoverage(options: FormatCoverageOptions): string { const opts = { diff --git a/src/debug.ts b/src/debug.ts index da0734557..db4d55369 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -360,6 +360,12 @@ function debugCacheNs( /** * Cache debug function with caller info. + * + * @example + * ```typescript + * debugCache('hit', 'socket-sdk:scans:abc123') + * debugCache('miss', 'socket-sdk:scans:xyz', { ttl: 60000 }) + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function debugCache( diff --git a/src/effects/pulse-frames.ts b/src/effects/pulse-frames.ts index bdffae7b2..25c7f653d 100644 --- a/src/effects/pulse-frames.ts +++ b/src/effects/pulse-frames.ts @@ -28,6 +28,12 @@ export type SocketFramesOptions = { * Returns a spinner definition compatible with cli-spinners format. * * @see https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json + * + * @example + * ```typescript + * const { frames, interval } = generateSocketSpinnerFrames() + * console.log(frames.length, interval) // 18 50 + * ``` */ export function generateSocketSpinnerFrames( options?: SocketFramesOptions | undefined, diff --git a/src/effects/text-shimmer.ts b/src/effects/text-shimmer.ts index de6818183..64ce99938 100644 --- a/src/effects/text-shimmer.ts +++ b/src/effects/text-shimmer.ts @@ -240,6 +240,15 @@ function pickDirection(direction: ShimmerDirection): 'ltr' | 'rtl' { * 4. Renders each character with appropriate brightness based on distance from wave * 5. Updates the animation state for the next frame * 6. Handles direction changes for bidirectional and random modes + * + * @example + * ```typescript + * const state = { step: 0, speed: 0.33, currentDir: 'ltr', mode: 'ltr' } + * const result = applyShimmer('Loading...', state, { + * color: [140, 82, 255], + * direction: 'ltr', + * }) + * ``` */ export function applyShimmer( text: string, diff --git a/src/effects/ultra.ts b/src/effects/ultra.ts index 4390351b6..c7cc91003 100644 --- a/src/effects/ultra.ts +++ b/src/effects/ultra.ts @@ -36,6 +36,12 @@ export const RAINBOW_GRADIENT: ShimmerColorGradient = [ /** * Generate rainbow gradient colors for any text length. * Colors are distributed evenly across the text by cycling through the gradient. + * + * @example + * ```typescript + * const colors = generateRainbowGradient('Hello'.length) + * console.log(colors.length) // 5 + * ``` */ export function generateRainbowGradient( textLength: number, diff --git a/src/env.ts b/src/env.ts index 296078532..a6c0a3274 100644 --- a/src/env.ts +++ b/src/env.ts @@ -175,6 +175,20 @@ export function createEnvProxy( /** * Convert an environment variable value to a boolean. + * + * @param value - The value to convert + * @param defaultValue - Default when value is null/undefined (default: `false`) + * @returns `true` if value is '1' or 'true' (case-insensitive), `false` otherwise + * + * @example + * ```typescript + * import { envAsBoolean } from '@socketsecurity/lib/env' + * + * envAsBoolean('true') // true + * envAsBoolean('1') // true + * envAsBoolean('false') // false + * envAsBoolean(undefined) // false + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function envAsBoolean(value: unknown, defaultValue = false): boolean { @@ -190,6 +204,19 @@ export function envAsBoolean(value: unknown, defaultValue = false): boolean { /** * Convert an environment variable value to a number. + * + * @param value - The value to convert + * @param defaultValue - Default when value is not a finite number (default: `0`) + * @returns The parsed integer, or the default value if parsing fails + * + * @example + * ```typescript + * import { envAsNumber } from '@socketsecurity/lib/env' + * + * envAsNumber('3000') // 3000 + * envAsNumber('abc') // 0 + * envAsNumber(undefined) // 0 + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function envAsNumber(value: unknown, defaultValue = 0): number { @@ -203,6 +230,19 @@ export function envAsNumber(value: unknown, defaultValue = 0): number { /** * Convert an environment variable value to a trimmed string. + * + * @param value - The value to convert + * @param defaultValue - Default when value is null/undefined (default: `''`) + * @returns The trimmed string value, or the default value + * + * @example + * ```typescript + * import { envAsString } from '@socketsecurity/lib/env' + * + * envAsString(' hello ') // 'hello' + * envAsString(undefined) // '' + * envAsString(null, 'n/a') // 'n/a' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function envAsString(value: unknown, defaultValue = ''): string { diff --git a/src/env/ci.ts b/src/env/ci.ts index 00f642925..4dfb01867 100644 --- a/src/env/ci.ts +++ b/src/env/ci.ts @@ -5,6 +5,20 @@ import { isInEnv } from './rewire' +/** + * Returns whether the CI environment variable is set. + * + * @returns `true` if running in a CI environment, `false` otherwise + * + * @example + * ```typescript + * import { getCI } from '@socketsecurity/lib/env/ci' + * + * if (getCI()) { + * console.log('Running in CI') + * } + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getCI(): boolean { return isInEnv('CI') diff --git a/src/env/debug.ts b/src/env/debug.ts index dcdca89c0..4b0d416b3 100644 --- a/src/env/debug.ts +++ b/src/env/debug.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the DEBUG environment variable. + * + * @returns The debug filter string, or `undefined` if not set + * + * @example + * ```typescript + * import { getDebug } from '@socketsecurity/lib/env/debug' + * + * const debug = getDebug() + * // e.g. 'socket:*' or undefined + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getDebug(): string | undefined { return getEnvValue('DEBUG') diff --git a/src/env/github.ts b/src/env/github.ts index 049751e03..c12e8da10 100644 --- a/src/env/github.ts +++ b/src/env/github.ts @@ -8,6 +8,16 @@ import { getEnvValue } from './rewire' /** * GITHUB_API_URL environment variable. * GitHub API URL (e.g., https://api.github.com). + * + * @returns The GitHub API URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubApiUrl } from '@socketsecurity/lib/env/github' + * + * const apiUrl = getGithubApiUrl() + * // e.g. 'https://api.github.com' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubApiUrl(): string | undefined { @@ -17,6 +27,16 @@ export function getGithubApiUrl(): string | undefined { /** * GITHUB_BASE_REF environment variable. * GitHub pull request base branch. + * + * @returns The pull request base branch name, or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubBaseRef } from '@socketsecurity/lib/env/github' + * + * const baseRef = getGithubBaseRef() + * // e.g. 'main' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubBaseRef(): string | undefined { @@ -26,6 +46,16 @@ export function getGithubBaseRef(): string | undefined { /** * GITHUB_REF_NAME environment variable. * GitHub branch or tag name. + * + * @returns The branch or tag name, or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubRefName } from '@socketsecurity/lib/env/github' + * + * const refName = getGithubRefName() + * // e.g. 'feature/my-branch' or 'v1.0.0' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubRefName(): string | undefined { @@ -35,6 +65,16 @@ export function getGithubRefName(): string | undefined { /** * GITHUB_REF_TYPE environment variable. * GitHub ref type (branch or tag). + * + * @returns The ref type ('branch' or 'tag'), or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubRefType } from '@socketsecurity/lib/env/github' + * + * const refType = getGithubRefType() + * // e.g. 'branch' or 'tag' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubRefType(): string | undefined { @@ -44,6 +84,16 @@ export function getGithubRefType(): string | undefined { /** * GITHUB_REPOSITORY environment variable. * GitHub repository name in owner/repo format. + * + * @returns The repository name, or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubRepository } from '@socketsecurity/lib/env/github' + * + * const repo = getGithubRepository() + * // e.g. 'SocketDev/socket-cli' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubRepository(): string | undefined { @@ -53,6 +103,16 @@ export function getGithubRepository(): string | undefined { /** * GITHUB_SERVER_URL environment variable. * GitHub server URL (e.g., https://github.com). + * + * @returns The GitHub server URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubServerUrl } from '@socketsecurity/lib/env/github' + * + * const serverUrl = getGithubServerUrl() + * // e.g. 'https://github.com' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubServerUrl(): string | undefined { @@ -62,6 +122,16 @@ export function getGithubServerUrl(): string | undefined { /** * GITHUB_TOKEN environment variable. * GitHub authentication token for API access. + * + * @returns The GitHub token, or `undefined` if not set + * + * @example + * ```typescript + * import { getGithubToken } from '@socketsecurity/lib/env/github' + * + * const token = getGithubToken() + * // e.g. 'ghp_abc123...' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGithubToken(): string | undefined { @@ -71,6 +141,16 @@ export function getGithubToken(): string | undefined { /** * GH_TOKEN environment variable. * Alternative GitHub authentication token for API access (used by GitHub CLI). + * + * @returns The GH CLI token, or `undefined` if not set + * + * @example + * ```typescript + * import { getGhToken } from '@socketsecurity/lib/env/github' + * + * const token = getGhToken() + * // e.g. 'gho_abc123...' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGhToken(): string | undefined { diff --git a/src/env/helpers.ts b/src/env/helpers.ts index d1c308a73..90a47280e 100644 --- a/src/env/helpers.ts +++ b/src/env/helpers.ts @@ -2,6 +2,22 @@ * @fileoverview Environment variable type conversion helpers. */ +/** + * Convert an environment variable string to a boolean. + * + * @param value - The environment variable value to convert + * @returns `true` if value is 'true', '1', or 'yes' (case-insensitive), `false` otherwise + * + * @example + * ```typescript + * import { envAsBoolean } from '@socketsecurity/lib/env/helpers' + * + * envAsBoolean('true') // true + * envAsBoolean('1') // true + * envAsBoolean('yes') // true + * envAsBoolean(undefined) // false + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function envAsBoolean(value: string | undefined): boolean { if (!value) { @@ -11,6 +27,21 @@ export function envAsBoolean(value: string | undefined): boolean { return lower === 'true' || lower === '1' || lower === 'yes' } +/** + * Convert an environment variable string to a number. + * + * @param value - The environment variable value to convert + * @returns The parsed number, or `0` if the value is undefined or not a valid number + * + * @example + * ```typescript + * import { envAsNumber } from '@socketsecurity/lib/env/helpers' + * + * envAsNumber('3000') // 3000 + * envAsNumber(undefined) // 0 + * envAsNumber('abc') // 0 + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function envAsNumber(value: string | undefined): number { if (!value) { @@ -20,6 +51,20 @@ export function envAsNumber(value: string | undefined): number { return Number.isNaN(num) ? 0 : num } +/** + * Convert an environment variable value to a string. + * + * @param value - The environment variable value to convert + * @returns The string value, or an empty string if undefined + * + * @example + * ```typescript + * import { envAsString } from '@socketsecurity/lib/env/helpers' + * + * envAsString('hello') // 'hello' + * envAsString(undefined) // '' + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function envAsString(value: string | undefined): string { return value || '' diff --git a/src/env/home.ts b/src/env/home.ts index 1a8e9a224..56d155e5f 100644 --- a/src/env/home.ts +++ b/src/env/home.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the HOME environment variable. + * + * @returns The user's home directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getHome } from '@socketsecurity/lib/env/home' + * + * const home = getHome() + * // e.g. '/tmp/user' or undefined + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getHome(): string | undefined { return getEnvValue('HOME') diff --git a/src/env/locale.ts b/src/env/locale.ts index 45b2965e9..f7987f49b 100644 --- a/src/env/locale.ts +++ b/src/env/locale.ts @@ -8,6 +8,16 @@ import { getEnvValue } from './rewire' /** * LANG environment variable. * System locale and language settings. + * + * @returns The system locale string, or `undefined` if not set + * + * @example + * ```typescript + * import { getLang } from '@socketsecurity/lib/env/locale' + * + * const lang = getLang() + * // e.g. 'en_US.UTF-8' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getLang(): string | undefined { @@ -17,6 +27,16 @@ export function getLang(): string | undefined { /** * LC_ALL environment variable. * Override for all locale settings. + * + * @returns The locale override string, or `undefined` if not set + * + * @example + * ```typescript + * import { getLcAll } from '@socketsecurity/lib/env/locale' + * + * const lcAll = getLcAll() + * // e.g. 'C' or 'en_US.UTF-8' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getLcAll(): string | undefined { @@ -26,6 +46,16 @@ export function getLcAll(): string | undefined { /** * LC_MESSAGES environment variable. * Locale setting for message translations. + * + * @returns The messages locale string, or `undefined` if not set + * + * @example + * ```typescript + * import { getLcMessages } from '@socketsecurity/lib/env/locale' + * + * const lcMessages = getLcMessages() + * // e.g. 'en_US.UTF-8' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getLcMessages(): string | undefined { diff --git a/src/env/node-auth-token.ts b/src/env/node-auth-token.ts index 89ff48af2..9f4ada3ae 100644 --- a/src/env/node-auth-token.ts +++ b/src/env/node-auth-token.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the NODE_AUTH_TOKEN environment variable. + * + * @returns The Node.js registry auth token, or `undefined` if not set + * + * @example + * ```typescript + * import { getNodeAuthToken } from '@socketsecurity/lib/env/node-auth-token' + * + * const token = getNodeAuthToken() + * // e.g. 'npm_abc123...' or undefined + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getNodeAuthToken(): string | undefined { return getEnvValue('NODE_AUTH_TOKEN') diff --git a/src/env/node-env.ts b/src/env/node-env.ts index 4364d4b0d..024edfb0c 100644 --- a/src/env/node-env.ts +++ b/src/env/node-env.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the NODE_ENV environment variable. + * + * @returns The Node.js environment mode, or `undefined` if not set + * + * @example + * ```typescript + * import { getNodeEnv } from '@socketsecurity/lib/env/node-env' + * + * const env = getNodeEnv() + * // e.g. 'production', 'development', 'test', or undefined + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getNodeEnv(): string | undefined { return getEnvValue('NODE_ENV') diff --git a/src/env/npm.ts b/src/env/npm.ts index 6e5bda52a..6d72b48ec 100644 --- a/src/env/npm.ts +++ b/src/env/npm.ts @@ -8,6 +8,16 @@ import { getEnvValue } from './rewire' /** * npm_config_registry environment variable. * NPM registry URL configured by package managers. + * + * @returns The configured NPM registry URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getNpmConfigRegistry } from '@socketsecurity/lib/env/npm' + * + * const registry = getNpmConfigRegistry() + * // e.g. 'https://registry.npmjs.org/' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getNpmConfigRegistry(): string | undefined { @@ -17,6 +27,16 @@ export function getNpmConfigRegistry(): string | undefined { /** * npm_config_user_agent environment variable. * User agent string set by npm/pnpm/yarn package managers. + * + * @returns The package manager user agent string, or `undefined` if not set + * + * @example + * ```typescript + * import { getNpmConfigUserAgent } from '@socketsecurity/lib/env/npm' + * + * const ua = getNpmConfigUserAgent() + * // e.g. 'pnpm/9.0.0 npm/? node/v20.0.0 darwin arm64' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getNpmConfigUserAgent(): string | undefined { @@ -26,6 +46,16 @@ export function getNpmConfigUserAgent(): string | undefined { /** * npm_lifecycle_event environment variable. * The name of the npm lifecycle event that's currently running. + * + * @returns The current lifecycle event name, or `undefined` if not set + * + * @example + * ```typescript + * import { getNpmLifecycleEvent } from '@socketsecurity/lib/env/npm' + * + * const event = getNpmLifecycleEvent() + * // e.g. 'install', 'postinstall', or 'test' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getNpmLifecycleEvent(): string | undefined { @@ -35,6 +65,16 @@ export function getNpmLifecycleEvent(): string | undefined { /** * NPM_REGISTRY environment variable. * NPM registry URL override. + * + * @returns The NPM registry URL override, or `undefined` if not set + * + * @example + * ```typescript + * import { getNpmRegistry } from '@socketsecurity/lib/env/npm' + * + * const registry = getNpmRegistry() + * // e.g. 'https://registry.npmjs.org/' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getNpmRegistry(): string | undefined { @@ -44,6 +84,16 @@ export function getNpmRegistry(): string | undefined { /** * NPM_TOKEN environment variable. * Authentication token for NPM registry access. + * + * @returns The NPM auth token, or `undefined` if not set + * + * @example + * ```typescript + * import { getNpmToken } from '@socketsecurity/lib/env/npm' + * + * const token = getNpmToken() + * // e.g. 'npm_abc123...' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getNpmToken(): string | undefined { diff --git a/src/env/path.ts b/src/env/path.ts index 2f7b4508e..2db879cf8 100644 --- a/src/env/path.ts +++ b/src/env/path.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the PATH environment variable. + * + * @returns The system executable search paths, or `undefined` if not set + * + * @example + * ```typescript + * import { getPath } from '@socketsecurity/lib/env/path' + * + * const path = getPath() + * // e.g. '/usr/local/bin:/usr/bin:/bin' or undefined + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getPath(): string | undefined { return getEnvValue('PATH') diff --git a/src/env/pre-commit.ts b/src/env/pre-commit.ts index 83509061c..69fc44c8d 100644 --- a/src/env/pre-commit.ts +++ b/src/env/pre-commit.ts @@ -6,6 +6,20 @@ import { envAsBoolean } from './helpers' import { getEnvValue } from './rewire' +/** + * Returns whether the PRE_COMMIT environment variable is set to a truthy value. + * + * @returns `true` if running in a pre-commit hook, `false` otherwise + * + * @example + * ```typescript + * import { getPreCommit } from '@socketsecurity/lib/env/pre-commit' + * + * if (getPreCommit()) { + * console.log('Running in pre-commit hook') + * } + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getPreCommit(): boolean { return envAsBoolean(getEnvValue('PRE_COMMIT')) diff --git a/src/env/rewire.ts b/src/env/rewire.ts index 025e97ec5..db78cccf5 100644 --- a/src/env/rewire.ts +++ b/src/env/rewire.ts @@ -54,6 +54,16 @@ const sharedOverrides: Map | undefined = /** * Clear a specific environment variable override. + * + * @param key - The environment variable name to clear + * + * @example + * ```typescript + * import { setEnv, clearEnv } from '@socketsecurity/lib/env/rewire' + * + * setEnv('CI', '1') + * clearEnv('CI') + * ``` */ export function clearEnv(key: string): void { sharedOverrides?.delete(key) @@ -68,6 +78,14 @@ export function clearEnv(key: string): void { * 3. process.env (including vi.stubEnv modifications) * * @internal Used by env getters to support test rewiring + * + * @example + * ```typescript + * import { getEnvValue } from '@socketsecurity/lib/env/rewire' + * + * const value = getEnvValue('NODE_ENV') + * // e.g. 'production' or undefined + * ``` */ export function getEnvValue(key: string): string | undefined { // Check isolated overrides first (highest priority - temporary via withEnv) @@ -87,6 +105,18 @@ export function getEnvValue(key: string): string | undefined { /** * Check if an environment variable has been overridden. + * + * @param key - The environment variable name to check + * @returns `true` if the variable has been overridden, `false` otherwise + * + * @example + * ```typescript + * import { setEnv, hasOverride } from '@socketsecurity/lib/env/rewire' + * + * hasOverride('CI') // false + * setEnv('CI', '1') + * hasOverride('CI') // true + * ``` */ export function hasOverride(key: string): boolean { const isolatedOverrides = isolatedOverridesStorage.getStore() @@ -102,6 +132,14 @@ export function hasOverride(key: string): boolean { * 3. process.env (including vi.stubEnv modifications) * * @internal Used by env getters to check for key presence (not value truthiness) + * + * @example + * ```typescript + * import { isInEnv } from '@socketsecurity/lib/env/rewire' + * + * isInEnv('PATH') // true (usually set) + * isInEnv('MISSING') // false + * ``` */ export function isInEnv(key: string): boolean { // Check isolated overrides first (highest priority - temporary via withEnv) diff --git a/src/env/shell.ts b/src/env/shell.ts index 72023e93c..7ade797cd 100644 --- a/src/env/shell.ts +++ b/src/env/shell.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the SHELL environment variable. + * + * @returns The user's default shell path, or `undefined` if not set + * + * @example + * ```typescript + * import { getShell } from '@socketsecurity/lib/env/shell' + * + * const shell = getShell() + * // e.g. '/bin/zsh' or '/bin/bash' + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getShell(): string | undefined { return getEnvValue('SHELL') diff --git a/src/env/socket-cli-shadow.ts b/src/env/socket-cli-shadow.ts index 5e14170b6..c0bc9990a 100644 --- a/src/env/socket-cli-shadow.ts +++ b/src/env/socket-cli-shadow.ts @@ -10,6 +10,15 @@ import { getEnvValue } from './rewire' * Controls Socket CLI shadow mode risk acceptance. * * @returns Whether to accept all risks in shadow mode + * + * @example + * ```typescript + * import { getSocketCliShadowAcceptRisks } from '@socketsecurity/lib/env/socket-cli-shadow' + * + * if (getSocketCliShadowAcceptRisks()) { + * console.log('Shadow mode risks accepted') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliShadowAcceptRisks(): boolean { @@ -20,6 +29,14 @@ export function getSocketCliShadowAcceptRisks(): boolean { * API token for Socket CLI shadow mode. * * @returns Shadow mode API token or undefined + * + * @example + * ```typescript + * import { getSocketCliShadowApiToken } from '@socketsecurity/lib/env/socket-cli-shadow' + * + * const token = getSocketCliShadowApiToken() + * // e.g. 'sk_shadow_abc123...' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliShadowApiToken(): string | undefined { @@ -30,6 +47,14 @@ export function getSocketCliShadowApiToken(): string | undefined { * Binary path for Socket CLI shadow mode. * * @returns Shadow mode binary path or undefined + * + * @example + * ```typescript + * import { getSocketCliShadowBin } from '@socketsecurity/lib/env/socket-cli-shadow' + * + * const bin = getSocketCliShadowBin() + * // e.g. '/usr/local/bin/socket-shadow' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliShadowBin(): string | undefined { @@ -40,6 +65,15 @@ export function getSocketCliShadowBin(): string | undefined { * Controls Socket CLI shadow mode progress display. * * @returns Whether to show progress in shadow mode + * + * @example + * ```typescript + * import { getSocketCliShadowProgress } from '@socketsecurity/lib/env/socket-cli-shadow' + * + * if (getSocketCliShadowProgress()) { + * console.log('Shadow mode progress enabled') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliShadowProgress(): boolean { @@ -50,6 +84,15 @@ export function getSocketCliShadowProgress(): boolean { * Controls Socket CLI shadow mode silent operation. * * @returns Whether shadow mode should operate silently + * + * @example + * ```typescript + * import { getSocketCliShadowSilent } from '@socketsecurity/lib/env/socket-cli-shadow' + * + * if (getSocketCliShadowSilent()) { + * console.log('Shadow mode is silent') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliShadowSilent(): boolean { diff --git a/src/env/socket-cli.ts b/src/env/socket-cli.ts index 99992f509..b493bf102 100644 --- a/src/env/socket-cli.ts +++ b/src/env/socket-cli.ts @@ -10,6 +10,15 @@ import { getEnvValue } from './rewire' * Whether to accept all Socket CLI risks (alternative name). * * @returns Whether to accept all risks + * + * @example + * ```typescript + * import { getSocketCliAcceptRisks } from '@socketsecurity/lib/env/socket-cli' + * + * if (getSocketCliAcceptRisks()) { + * console.log('All risks accepted') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliAcceptRisks(): boolean { @@ -21,6 +30,14 @@ export function getSocketCliAcceptRisks(): boolean { * Checks SOCKET_CLI_API_BASE_URL first, then falls back to legacy SOCKET_SECURITY_API_BASE_URL. * * @returns API base URL or undefined + * + * @example + * ```typescript + * import { getSocketCliApiBaseUrl } from '@socketsecurity/lib/env/socket-cli' + * + * const baseUrl = getSocketCliApiBaseUrl() + * // e.g. 'https://api.socket.dev' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliApiBaseUrl(): string | undefined { @@ -36,6 +53,14 @@ export function getSocketCliApiBaseUrl(): string | undefined { * Follows the same precedence as v1.x: HTTPS_PROXY → https_proxy → HTTP_PROXY → http_proxy. * * @returns API proxy URL or undefined + * + * @example + * ```typescript + * import { getSocketCliApiProxy } from '@socketsecurity/lib/env/socket-cli' + * + * const proxy = getSocketCliApiProxy() + * // e.g. 'http://proxy.example.com:8080' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliApiProxy(): string | undefined { @@ -53,6 +78,14 @@ export function getSocketCliApiProxy(): string | undefined { * Timeout in milliseconds for Socket CLI API requests (alternative name). * * @returns API timeout in milliseconds + * + * @example + * ```typescript + * import { getSocketCliApiTimeout } from '@socketsecurity/lib/env/socket-cli' + * + * const timeout = getSocketCliApiTimeout() + * // e.g. 30000 or 0 if not set + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliApiTimeout(): number { @@ -65,6 +98,14 @@ export function getSocketCliApiTimeout(): number { * Maintains full v1.x backward compatibility. * * @returns API token or undefined + * + * @example + * ```typescript + * import { getSocketCliApiToken } from '@socketsecurity/lib/env/socket-cli' + * + * const token = getSocketCliApiToken() + * // e.g. a Socket API token string or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliApiToken(): string | undefined { @@ -81,6 +122,14 @@ export function getSocketCliApiToken(): string | undefined { * Set by bootstrap wrappers to pass dlx cache location to CLI. * * @returns Bootstrap cache directory or undefined + * + * @example + * ```typescript + * import { getSocketCliBootstrapCacheDir } from '@socketsecurity/lib/env/socket-cli' + * + * const cacheDir = getSocketCliBootstrapCacheDir() + * // e.g. '/tmp/.socket-cli-cache' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliBootstrapCacheDir(): string | undefined { @@ -92,6 +141,14 @@ export function getSocketCliBootstrapCacheDir(): string | undefined { * Set by bootstrap wrappers (SEA/smol/npm) to pass package spec to CLI. * * @returns Bootstrap package spec or undefined + * + * @example + * ```typescript + * import { getSocketCliBootstrapSpec } from '@socketsecurity/lib/env/socket-cli' + * + * const spec = getSocketCliBootstrapSpec() + * // e.g. '@socketsecurity/cli@^2.0.11' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliBootstrapSpec(): string | undefined { @@ -102,6 +159,14 @@ export function getSocketCliBootstrapSpec(): string | undefined { * Socket CLI configuration file path (alternative name). * * @returns Config file path or undefined + * + * @example + * ```typescript + * import { getSocketCliConfig } from '@socketsecurity/lib/env/socket-cli' + * + * const config = getSocketCliConfig() + * // e.g. '/tmp/project/socket.yml' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliConfig(): string | undefined { @@ -112,6 +177,14 @@ export function getSocketCliConfig(): string | undefined { * Controls Socket CLI fix mode. * * @returns Fix mode value or undefined + * + * @example + * ```typescript + * import { getSocketCliFix } from '@socketsecurity/lib/env/socket-cli' + * + * const fix = getSocketCliFix() + * // e.g. 'true' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliFix(): string | undefined { @@ -123,6 +196,14 @@ export function getSocketCliFix(): string | undefined { * Checks SOCKET_CLI_GITHUB_TOKEN, SOCKET_SECURITY_GITHUB_PAT, then falls back to GITHUB_TOKEN. * * @returns GitHub token or undefined + * + * @example + * ```typescript + * import { getSocketCliGithubToken } from '@socketsecurity/lib/env/socket-cli' + * + * const token = getSocketCliGithubToken() + * // e.g. 'ghp_abc123...' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliGithubToken(): string | undefined { @@ -137,6 +218,15 @@ export function getSocketCliGithubToken(): string | undefined { * Whether to skip Socket CLI API token requirement (alternative name). * * @returns Whether to skip API token requirement + * + * @example + * ```typescript + * import { getSocketCliNoApiToken } from '@socketsecurity/lib/env/socket-cli' + * + * if (getSocketCliNoApiToken()) { + * console.log('API token requirement skipped') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliNoApiToken(): boolean { @@ -147,6 +237,15 @@ export function getSocketCliNoApiToken(): boolean { * Controls Socket CLI optimization mode. * * @returns Whether optimization mode is enabled + * + * @example + * ```typescript + * import { getSocketCliOptimize } from '@socketsecurity/lib/env/socket-cli' + * + * if (getSocketCliOptimize()) { + * console.log('Optimization mode enabled') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliOptimize(): boolean { @@ -158,6 +257,14 @@ export function getSocketCliOptimize(): boolean { * Checks SOCKET_CLI_ORG_SLUG first, then falls back to SOCKET_ORG_SLUG. * * @returns Organization slug or undefined + * + * @example + * ```typescript + * import { getSocketCliOrgSlug } from '@socketsecurity/lib/env/socket-cli' + * + * const slug = getSocketCliOrgSlug() + * // e.g. 'my-org' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliOrgSlug(): string | undefined { @@ -168,6 +275,15 @@ export function getSocketCliOrgSlug(): string | undefined { * Whether to view all Socket CLI risks (alternative name). * * @returns Whether to view all risks + * + * @example + * ```typescript + * import { getSocketCliViewAllRisks } from '@socketsecurity/lib/env/socket-cli' + * + * if (getSocketCliViewAllRisks()) { + * console.log('Viewing all risks') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCliViewAllRisks(): boolean { diff --git a/src/env/socket.ts b/src/env/socket.ts index 88f743a21..90ebc222d 100644 --- a/src/env/socket.ts +++ b/src/env/socket.ts @@ -8,6 +8,17 @@ import { getEnvValue } from './rewire' /** * SOCKET_ACCEPT_RISKS environment variable getter. * Whether to accept all Socket Security risks. + * + * @returns `true` if risks are accepted, `false` otherwise + * + * @example + * ```typescript + * import { getSocketAcceptRisks } from '@socketsecurity/lib/env/socket' + * + * if (getSocketAcceptRisks()) { + * console.log('All risks accepted') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketAcceptRisks(): boolean { @@ -17,6 +28,16 @@ export function getSocketAcceptRisks(): boolean { /** * SOCKET_API_BASE_URL environment variable getter. * Socket Security API base URL. + * + * @returns The API base URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketApiBaseUrl } from '@socketsecurity/lib/env/socket' + * + * const baseUrl = getSocketApiBaseUrl() + * // e.g. 'https://api.socket.dev' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketApiBaseUrl(): string | undefined { @@ -26,6 +47,16 @@ export function getSocketApiBaseUrl(): string | undefined { /** * SOCKET_API_PROXY environment variable getter. * Proxy URL for Socket Security API requests. + * + * @returns The API proxy URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketApiProxy } from '@socketsecurity/lib/env/socket' + * + * const proxy = getSocketApiProxy() + * // e.g. 'http://proxy.example.com:8080' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketApiProxy(): string | undefined { @@ -35,6 +66,16 @@ export function getSocketApiProxy(): string | undefined { /** * SOCKET_API_TIMEOUT environment variable getter. * Timeout in milliseconds for Socket Security API requests. + * + * @returns The timeout in milliseconds, or `0` if not set + * + * @example + * ```typescript + * import { getSocketApiTimeout } from '@socketsecurity/lib/env/socket' + * + * const timeout = getSocketApiTimeout() + * // e.g. 30000 or 0 if not set + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketApiTimeout(): number { @@ -44,6 +85,16 @@ export function getSocketApiTimeout(): number { /** * SOCKET_API_TOKEN environment variable getter. * Socket Security API authentication token. + * + * @returns The API token, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketApiToken } from '@socketsecurity/lib/env/socket' + * + * const token = getSocketApiToken() + * // e.g. a Socket API token string or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketApiToken(): string | undefined { @@ -53,6 +104,16 @@ export function getSocketApiToken(): string | undefined { /** * SOCKET_CACACHE_DIR environment variable getter. * Overrides the default Socket cacache directory location. + * + * @returns The cacache directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketCacacheDir } from '@socketsecurity/lib/env/socket' + * + * const dir = getSocketCacacheDir() + * // e.g. '/tmp/.socket-cache' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketCacacheDir(): string | undefined { @@ -62,6 +123,16 @@ export function getSocketCacacheDir(): string | undefined { /** * SOCKET_CONFIG environment variable getter. * Socket Security configuration file path. + * + * @returns The config file path, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketConfig } from '@socketsecurity/lib/env/socket' + * + * const config = getSocketConfig() + * // e.g. '/tmp/project/socket.yml' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketConfig(): string | undefined { @@ -71,6 +142,16 @@ export function getSocketConfig(): string | undefined { /** * SOCKET_DEBUG environment variable getter. * Controls Socket-specific debug output. + * + * @returns The Socket debug filter, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketDebug } from '@socketsecurity/lib/env/socket' + * + * const debug = getSocketDebug() + * // e.g. '*' or 'api' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketDebug(): string | undefined { @@ -80,6 +161,16 @@ export function getSocketDebug(): string | undefined { /** * SOCKET_DLX_DIR environment variable getter. * Overrides the default Socket DLX directory location. + * + * @returns The DLX directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketDlxDirEnv } from '@socketsecurity/lib/env/socket' + * + * const dlxDir = getSocketDlxDirEnv() + * // e.g. '/tmp/.socket-dlx' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketDlxDirEnv(): string | undefined { @@ -89,6 +180,16 @@ export function getSocketDlxDirEnv(): string | undefined { /** * SOCKET_HOME environment variable getter. * Socket Security home directory path. + * + * @returns The Socket home directory, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketHome } from '@socketsecurity/lib/env/socket' + * + * const home = getSocketHome() + * // e.g. '/tmp/.socket' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketHome(): string | undefined { @@ -98,6 +199,17 @@ export function getSocketHome(): string | undefined { /** * SOCKET_NO_API_TOKEN environment variable getter. * Whether to skip Socket Security API token requirement. + * + * @returns `true` if the API token requirement is skipped, `false` otherwise + * + * @example + * ```typescript + * import { getSocketNoApiToken } from '@socketsecurity/lib/env/socket' + * + * if (getSocketNoApiToken()) { + * console.log('API token requirement skipped') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketNoApiToken(): boolean { @@ -107,6 +219,16 @@ export function getSocketNoApiToken(): boolean { /** * SOCKET_NPM_REGISTRY environment variable getter. * Socket NPM registry URL (alternative name). + * + * @returns The Socket NPM registry URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketNpmRegistry } from '@socketsecurity/lib/env/socket' + * + * const registry = getSocketNpmRegistry() + * // e.g. 'https://npm.socket.dev/' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketNpmRegistry(): string | undefined { @@ -116,6 +238,16 @@ export function getSocketNpmRegistry(): string | undefined { /** * SOCKET_ORG_SLUG environment variable getter. * Socket Security organization slug identifier. + * + * @returns The organization slug, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketOrgSlug } from '@socketsecurity/lib/env/socket' + * + * const slug = getSocketOrgSlug() + * // e.g. 'my-org' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketOrgSlug(): string | undefined { @@ -125,6 +257,16 @@ export function getSocketOrgSlug(): string | undefined { /** * SOCKET_REGISTRY_URL environment variable getter. * Socket Registry URL for package installation. + * + * @returns The Socket registry URL, or `undefined` if not set + * + * @example + * ```typescript + * import { getSocketRegistryUrl } from '@socketsecurity/lib/env/socket' + * + * const registryUrl = getSocketRegistryUrl() + * // e.g. 'https://registry.socket.dev/' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketRegistryUrl(): string | undefined { @@ -134,6 +276,17 @@ export function getSocketRegistryUrl(): string | undefined { /** * SOCKET_VIEW_ALL_RISKS environment variable getter. * Whether to view all Socket Security risks. + * + * @returns `true` if viewing all risks, `false` otherwise + * + * @example + * ```typescript + * import { getSocketViewAllRisks } from '@socketsecurity/lib/env/socket' + * + * if (getSocketViewAllRisks()) { + * console.log('Viewing all risks') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getSocketViewAllRisks(): boolean { diff --git a/src/env/temp-dir.ts b/src/env/temp-dir.ts index 902361876..72b14753f 100644 --- a/src/env/temp-dir.ts +++ b/src/env/temp-dir.ts @@ -8,6 +8,16 @@ import { getEnvValue } from './rewire' /** * TEMP environment variable. * Windows temporary directory path. + * + * @returns The Windows temp directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getTemp } from '@socketsecurity/lib/env/temp-dir' + * + * const temp = getTemp() + * // e.g. 'C:\\Windows\\Temp' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getTemp(): string | undefined { @@ -17,6 +27,16 @@ export function getTemp(): string | undefined { /** * TMP environment variable. * Alternative temporary directory path. + * + * @returns The alternative temp directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getTmp } from '@socketsecurity/lib/env/temp-dir' + * + * const tmp = getTmp() + * // e.g. '/tmp' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getTmp(): string | undefined { @@ -26,6 +46,16 @@ export function getTmp(): string | undefined { /** * TMPDIR environment variable. * Unix/macOS temporary directory path. + * + * @returns The Unix/macOS temp directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getTmpdir } from '@socketsecurity/lib/env/temp-dir' + * + * const tmpdir = getTmpdir() + * // e.g. '/tmp' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getTmpdir(): string | undefined { diff --git a/src/env/term.ts b/src/env/term.ts index b6583d32b..de0e2f6c1 100644 --- a/src/env/term.ts +++ b/src/env/term.ts @@ -5,6 +5,19 @@ import { getEnvValue } from './rewire' +/** + * Returns the value of the TERM environment variable. + * + * @returns The terminal type identifier, or `undefined` if not set + * + * @example + * ```typescript + * import { getTerm } from '@socketsecurity/lib/env/term' + * + * const term = getTerm() + * // e.g. 'xterm-256color' or undefined + * ``` + */ /*@__NO_SIDE_EFFECTS__*/ export function getTerm(): string | undefined { return getEnvValue('TERM') diff --git a/src/env/test.ts b/src/env/test.ts index 10bf31163..f6ed9ed4f 100644 --- a/src/env/test.ts +++ b/src/env/test.ts @@ -10,6 +10,16 @@ import { getEnvValue } from './rewire' /** * JEST_WORKER_ID environment variable. * Set when running tests with Jest. + * + * @returns The Jest worker ID string, or empty string if not set + * + * @example + * ```typescript + * import { getJestWorkerId } from '@socketsecurity/lib/env/test' + * + * const workerId = getJestWorkerId() + * // e.g. '1' when running in Jest, or '' + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getJestWorkerId(): string { @@ -19,6 +29,17 @@ export function getJestWorkerId(): string { /** * VITEST environment variable. * Set when running tests with Vitest. + * + * @returns `true` if running in Vitest, `false` otherwise + * + * @example + * ```typescript + * import { getVitest } from '@socketsecurity/lib/env/test' + * + * if (getVitest()) { + * console.log('Running in Vitest') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getVitest(): boolean { @@ -28,6 +49,17 @@ export function getVitest(): boolean { /** * Check if code is running in a test environment. * Checks NODE_ENV, VITEST, and JEST_WORKER_ID. + * + * @returns `true` if running in a test environment, `false` otherwise + * + * @example + * ```typescript + * import { isTest } from '@socketsecurity/lib/env/test' + * + * if (isTest()) { + * console.log('Running in test environment') + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function isTest(): boolean { diff --git a/src/env/windows.ts b/src/env/windows.ts index 35efc4821..fc05dfe14 100644 --- a/src/env/windows.ts +++ b/src/env/windows.ts @@ -8,6 +8,16 @@ import { getEnvValue } from './rewire' /** * APPDATA environment variable. * Points to the Application Data directory on Windows. + * + * @returns The Windows AppData roaming directory, or `undefined` if not set + * + * @example + * ```typescript + * import { getAppdata } from '@socketsecurity/lib/env/windows' + * + * const appdata = getAppdata() + * // e.g. 'C:\\Users\\Public\\AppData\\Roaming' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getAppdata(): string | undefined { @@ -17,6 +27,16 @@ export function getAppdata(): string | undefined { /** * COMSPEC environment variable. * Points to the Windows command processor (typically cmd.exe). + * + * @returns The path to the command processor, or `undefined` if not set + * + * @example + * ```typescript + * import { getComspec } from '@socketsecurity/lib/env/windows' + * + * const comspec = getComspec() + * // e.g. 'C:\\Windows\\system32\\cmd.exe' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getComspec(): string | undefined { @@ -26,6 +46,16 @@ export function getComspec(): string | undefined { /** * LOCALAPPDATA environment variable. * Points to the Local Application Data directory on Windows. + * + * @returns The Windows local AppData directory, or `undefined` if not set + * + * @example + * ```typescript + * import { getLocalappdata } from '@socketsecurity/lib/env/windows' + * + * const localAppdata = getLocalappdata() + * // e.g. 'C:\\Users\\Public\\AppData\\Local' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getLocalappdata(): string | undefined { @@ -35,6 +65,16 @@ export function getLocalappdata(): string | undefined { /** * USERPROFILE environment variable. * Windows user home directory path. + * + * @returns The Windows user profile directory, or `undefined` if not set + * + * @example + * ```typescript + * import { getUserprofile } from '@socketsecurity/lib/env/windows' + * + * const userprofile = getUserprofile() + * // e.g. 'C:\\Users\\Public' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getUserprofile(): string | undefined { diff --git a/src/env/xdg.ts b/src/env/xdg.ts index 00c81b546..d63c05f18 100644 --- a/src/env/xdg.ts +++ b/src/env/xdg.ts @@ -8,6 +8,16 @@ import { getEnvValue } from './rewire' /** * XDG_CACHE_HOME environment variable. * XDG Base Directory specification cache directory. + * + * @returns The XDG cache directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getXdgCacheHome } from '@socketsecurity/lib/env/xdg' + * + * const cacheDir = getXdgCacheHome() + * // e.g. '/tmp/.cache' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getXdgCacheHome(): string | undefined { @@ -17,6 +27,16 @@ export function getXdgCacheHome(): string | undefined { /** * XDG_CONFIG_HOME environment variable. * XDG Base Directory specification config directory. + * + * @returns The XDG config directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getXdgConfigHome } from '@socketsecurity/lib/env/xdg' + * + * const configDir = getXdgConfigHome() + * // e.g. '/tmp/.config' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getXdgConfigHome(): string | undefined { @@ -26,6 +46,16 @@ export function getXdgConfigHome(): string | undefined { /** * XDG_DATA_HOME environment variable. * Points to the user's data directory on Unix systems. + * + * @returns The XDG data directory path, or `undefined` if not set + * + * @example + * ```typescript + * import { getXdgDataHome } from '@socketsecurity/lib/env/xdg' + * + * const dataDir = getXdgDataHome() + * // e.g. '/tmp/.local/share' or undefined + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getXdgDataHome(): string | undefined { diff --git a/src/globs.ts b/src/globs.ts index 8e7776528..db645adfd 100644 --- a/src/globs.ts +++ b/src/globs.ts @@ -109,6 +109,14 @@ export const defaultIgnore = ObjectFreeze([ /** * Create a stream of license file paths matching glob patterns. + * + * @example + * ```typescript + * const stream = globStreamLicenses('/tmp/my-package') + * for await (const licensePath of stream) { + * console.log(licensePath) + * } + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function globStreamLicenses( @@ -162,6 +170,13 @@ function evictLRUMatcher() { /** * Get a cached glob matcher function. + * + * @example + * ```typescript + * const isMatch = getGlobMatcher('*.ts') + * isMatch('index.ts') // true + * isMatch('index.js') // false + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function getGlobMatcher( @@ -221,6 +236,12 @@ export function getGlobMatcher( /** * Asynchronously find files matching glob patterns. * Wrapper around fast-glob. + * + * @example + * ```typescript + * const files = await glob('src/*.ts', { cwd: '/tmp/project' }) + * console.log(files) // ['src/index.ts', 'src/utils.ts'] + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function glob( @@ -235,6 +256,12 @@ export function glob( /** * Synchronously find files matching glob patterns. * Wrapper around fast-glob.sync. + * + * @example + * ```typescript + * const files = globSync('*.json', { cwd: '/tmp/project' }) + * console.log(files) // ['package.json', 'tsconfig.json'] + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function globSync( diff --git a/src/http-request.ts b/src/http-request.ts index 008713a7e..8f9bb3cfb 100644 --- a/src/http-request.ts +++ b/src/http-request.ts @@ -502,6 +502,13 @@ export interface HttpResponse { * `httpRequest()` (e.g., multipart form-data uploads via `http.request()`, * or responses from third-party HTTP libraries) and need to convert it * into the standard HttpResponse interface. + * + * @example + * ```typescript + * const raw = await makeRawRequest('https://example.com/api') + * const response = await readIncomingResponse(raw) + * console.log(response.status, response.body.toString('utf8')) + * ``` */ export async function readIncomingResponse( msg: IncomingResponse, @@ -1076,6 +1083,15 @@ async function httpDownloadAttempt( /** * Build an enriched error message based on the error code. * Generic guidance (no product-specific branding). + * + * @example + * ```typescript + * try { + * await fetch('https://api.example.com') + * } catch (err) { + * console.error(enrichErrorMessage('https://api.example.com', 'GET', err)) + * } + * ``` */ export function enrichErrorMessage( url: string, diff --git a/src/json/format.ts b/src/json/format.ts index 5e5193451..780ca231e 100644 --- a/src/json/format.ts +++ b/src/json/format.ts @@ -96,6 +96,12 @@ export function extractFormatting(json: string): JsonFormatting { * Get default formatting for JSON files. * * @returns Default formatting (2 spaces, LF line endings) + * + * @example + * ```typescript + * const fmt = getDefaultFormatting() + * // { indent: 2, newline: '\n' } + * ``` */ export function getDefaultFormatting(): JsonFormatting { return { @@ -162,6 +168,12 @@ export function stringifyWithFormatting( * * @param content - Content object with potential symbol properties * @returns Object with symbols removed + * + * @example + * ```typescript + * const obj = { key: "value", [Symbol.for("indent")]: 2 } + * stripFormattingSymbols(obj) // { key: "value" } + * ``` */ export function stripFormattingSymbols( content: Record, @@ -179,6 +191,12 @@ export function stripFormattingSymbols( * * @param content - Content object with Symbol.for('indent') and Symbol.for('newline') * @returns Formatting metadata, or defaults if symbols not present + * + * @example + * ```typescript + * const content = { [Symbol.for("indent")]: 4, [Symbol.for("newline")]: "\r\n" } + * getFormattingFromContent(content) // { indent: 4, newline: "\r\n" } + * ``` */ export function getFormattingFromContent( content: Record, diff --git a/src/memoization.ts b/src/memoization.ts index dd37ebb25..f41e75d65 100644 --- a/src/memoization.ts +++ b/src/memoization.ts @@ -319,6 +319,11 @@ export function Memoize(options: MemoizeOptions = {}) { /** * Clear all memoization caches. * Useful for testing or when you need to force recomputation. + * + * @example + * ```typescript + * clearAllMemoizationCaches() + * ``` */ export function clearAllMemoizationCaches(): void { debugLog('[memoize:all] clear', { action: 'clear-all-caches' }) diff --git a/src/releases/github.ts b/src/releases/github.ts index 6f9d27e72..25c8b6dad 100644 --- a/src/releases/github.ts +++ b/src/releases/github.ts @@ -145,6 +145,13 @@ function getPath() { * * @param pattern - Pattern to match (string glob, prefix/suffix object, or RegExp) * @returns Function that tests if a string matches the pattern + * + * @example + * ```typescript + * const isMatch = createAssetMatcher('tool-*-linux-x64') + * isMatch('tool-v1.0-linux-x64') // true + * isMatch('tool-v1.0-darwin-arm64') // false + * ``` */ export function createAssetMatcher( pattern: string | { prefix: string; suffix: string } | RegExp, @@ -169,6 +176,16 @@ export function createAssetMatcher( * * @param config - Download configuration * @returns Path to the downloaded binary + * + * @example + * ```typescript + * const binaryPath = await downloadGitHubRelease({ + * owner: 'SocketDev', repo: 'socket-btm', + * toolName: 'lief', toolPrefix: 'lief-', + * assetName: 'lief-linux-x64', binaryName: 'lief', + * platformArch: 'linux-x64', + * }) + * ``` */ export async function downloadGitHubRelease( config: DownloadGitHubReleaseConfig, @@ -284,6 +301,14 @@ export async function downloadGitHubRelease( * @param outputPath - Path to write the downloaded file * @param repoConfig - Repository configuration (owner/repo) * @param options - Additional options + * + * @example + * ```typescript + * await downloadReleaseAsset( + * 'v1.0.0', 'tool-linux-x64', '/tmp/tool', + * { owner: 'SocketDev', repo: 'socket-btm' }, + * ) + * ``` */ export async function downloadReleaseAsset( tag: string, @@ -328,6 +353,12 @@ export async function downloadReleaseAsset( * Checks GH_TOKEN or GITHUB_TOKEN environment variables. * * @returns Headers object with Authorization header if token exists. + * + * @example + * ```typescript + * const headers = getAuthHeaders() + * // { Accept: 'application/vnd.github+json', Authorization: 'Bearer ...' } + * ``` */ export function getAuthHeaders(): Record { const token = process.env['GH_TOKEN'] || process.env['GITHUB_TOKEN'] @@ -350,6 +381,14 @@ export function getAuthHeaders(): Record { * @param options - Additional options * @param options.assetPattern - Optional pattern to filter releases by matching asset * @returns Latest release tag or null if not found + * + * @example + * ```typescript + * const tag = await getLatestRelease('lief-', { + * owner: 'SocketDev', repo: 'socket-btm', + * }) + * console.log(tag) // 'lief-2025-01-15-abc1234' + * ``` */ export async function getLatestRelease( toolPrefix: string, @@ -465,6 +504,14 @@ export async function getLatestRelease( * @param repoConfig - Repository configuration (owner/repo) * @param options - Additional options * @returns Browser download URL for the asset + * + * @example + * ```typescript + * const url = await getReleaseAssetUrl( + * 'v1.0.0', 'tool-linux-x64', + * { owner: 'SocketDev', repo: 'socket-btm' }, + * ) + * ``` */ export async function getReleaseAssetUrl( tag: string, @@ -556,6 +603,14 @@ export async function getReleaseAssetUrl( * @param options.quiet - Suppress log messages * @param options.cleanup - Remove downloaded zip file after extraction (default: true) * @returns Path to the extraction directory + * + * @example + * ```typescript + * const outputDir = await downloadAndExtractZip( + * 'v1.0.0', 'models-*.zip', '/tmp/models', + * { owner: 'SocketDev', repo: 'socket-btm' }, + * ) + * ``` */ export async function downloadAndExtractZip( tag: string, @@ -629,6 +684,14 @@ export async function downloadAndExtractZip( * @param options.strip - Strip leading path components (like tar --strip-components) * @param options.format - Archive format (auto-detected if not specified) * @returns Path to the extraction directory + * + * @example + * ```typescript + * const outputDir = await downloadAndExtractArchive( + * 'v1.0.0', 'data-*.tar.gz', '/tmp/data', + * { owner: 'SocketDev', repo: 'socket-btm' }, + * ) + * ``` */ export async function downloadAndExtractArchive( tag: string, diff --git a/src/releases/socket-btm.ts b/src/releases/socket-btm.ts index bb5b2b0d6..157843c01 100644 --- a/src/releases/socket-btm.ts +++ b/src/releases/socket-btm.ts @@ -124,6 +124,12 @@ function getFs() { * Returns undefined for non-Linux platforms. * * @returns 'musl', 'glibc', or undefined (for non-Linux) + * + * @example + * ```typescript + * const libc = detectLibc() + * console.log(libc) // 'glibc', 'musl', or undefined + * ``` */ export function detectLibc(): Libc | undefined { if (getPlatform() !== 'linux') { @@ -161,6 +167,13 @@ export function detectLibc(): Libc | undefined { * @param tool - Tool/package name for release matching (e.g., 'lief', 'curl') * @param options - Download configuration * @returns Path to the downloaded file + * + * @example + * ```typescript + * const binPath = await downloadSocketBtmRelease('lief', { + * downloadDir: '/tmp/build/downloaded', + * }) + * ``` */ export async function downloadSocketBtmRelease( tool: string, @@ -303,6 +316,12 @@ export async function downloadSocketBtmRelease( * @param arch - Target architecture * @param libc - Linux libc variant (optional) * @returns Asset name (e.g., 'binject-darwin-arm64', 'node-linux-x64-musl') + * + * @example + * ```typescript + * getBinaryAssetName('lief', 'linux', 'x64', 'musl') + * // 'lief-linux-x64-musl' + * ``` */ export function getBinaryAssetName( binaryBaseName: string, @@ -337,6 +356,12 @@ export function getBinaryAssetName( * @param binaryBaseName - Binary basename (e.g., 'node', 'binject') * @param platform - Target platform * @returns Binary filename (e.g., 'node', 'node.exe') + * + * @example + * ```typescript + * getBinaryName('node', 'win32') // 'node.exe' + * getBinaryName('node', 'linux') // 'node' + * ``` */ export function getBinaryName( binaryBaseName: string, @@ -353,6 +378,12 @@ export function getBinaryName( * @param arch - Target architecture * @param libc - Linux libc variant (optional) * @returns Platform-arch identifier (e.g., 'darwin-arm64', 'linux-x64-musl', 'win-x64') + * + * @example + * ```typescript + * getPlatformArch('linux', 'x64', 'musl') // 'linux-x64-musl' + * getPlatformArch('darwin', 'arm64') // 'darwin-arm64' + * ``` */ export function getPlatformArch( platform: Platform, diff --git a/src/sea.ts b/src/sea.ts index d6e677454..b97cf09aa 100644 --- a/src/sea.ts +++ b/src/sea.ts @@ -15,6 +15,14 @@ let _isSea: boolean | undefined /** * Get the current SEA binary path. * Only valid when running as a SEA binary. + * + * @example + * ```typescript + * const binPath = getSeaBinaryPath() + * if (binPath) { + * console.log(`Running as SEA binary: ${binPath}`) + * } + * ``` */ export function getSeaBinaryPath(): string | undefined { return isSeaBinary() && process.argv[0] @@ -25,6 +33,13 @@ export function getSeaBinaryPath(): string | undefined { /** * Detect if the current process is running as a SEA binary. * Uses Node.js 24+ native API with caching for performance. + * + * @example + * ```typescript + * if (isSeaBinary()) { + * console.log('Running as a Single Executable Application') + * } + * ``` */ export function isSeaBinary(): boolean { if (_isSea === undefined) { diff --git a/src/shadow.ts b/src/shadow.ts index a500d6abc..4af905e82 100644 --- a/src/shadow.ts +++ b/src/shadow.ts @@ -22,6 +22,13 @@ export interface ShadowInstallationOptions { * @param options.cwd - Current working directory path to check * @param options.win32 - Whether running on Windows * @returns true if shadow installation should be skipped + * + * @example + * ```typescript + * if (shouldSkipShadow(binPath, { cwd: process.cwd() })) { + * console.log('Skipping shadow binary installation') + * } + * ``` */ export function shouldSkipShadow( binPath: string, diff --git a/src/signal-exit.ts b/src/signal-exit.ts index 24c4e18f8..6ac10b5a6 100644 --- a/src/signal-exit.ts +++ b/src/signal-exit.ts @@ -144,6 +144,12 @@ let loaded = false /** * Load signal handlers and hook into process exit events. + * + * @example + * ```typescript + * load() + * // Signal handlers are now active + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function load(): void { @@ -234,6 +240,15 @@ export interface OnExitOptions { /** * Register a callback to run on process exit or signal. + * + * @example + * ```typescript + * const remove = onExit((code, signal) => { + * console.log(`Exiting with code ${code}, signal ${signal}`) + * }) + * // Later, to unregister: + * remove() + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function onExit( @@ -273,6 +288,12 @@ export function onExit( let _signals: string[] | undefined /** * Get the list of signals that are currently being monitored. + * + * @example + * ```typescript + * const sigs = signals() + * console.log(sigs) // ['SIGABRT', 'SIGALRM', 'SIGHUP', ...] + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function signals() { @@ -302,6 +323,12 @@ export function signals() { /** * Unload signal handlers and restore original process behavior. + * + * @example + * ```typescript + * unload() + * // Signal handlers are now removed + * ``` */ /*@__NO_SIDE_EFFECTS__*/ export function unload(): void { diff --git a/src/stdio/mask.ts b/src/stdio/mask.ts index 976015d72..446312a86 100644 --- a/src/stdio/mask.ts +++ b/src/stdio/mask.ts @@ -148,6 +148,12 @@ export interface OutputMask { * Create an output mask for controlling command output visibility. * The mask tracks whether output should be shown or hidden (buffered). * When hidden, output is buffered and a spinner is shown instead. + * + * @example + * ```typescript + * const mask = createOutputMask({ showOutput: false }) + * console.log(mask.verbose) // false + * ``` */ export function createOutputMask(options: OutputMaskOptions = {}): OutputMask { const { showOutput = false } = options @@ -166,6 +172,13 @@ export function createOutputMask(options: OutputMaskOptions = {}): OutputMask { * - ctrl+o: Toggle between showing and hiding output. * - ctrl+c: Cancel the running process. * The handler manipulates terminal state using ANSI escape sequences. + * + * @example + * ```typescript + * const handler = createKeyboardHandler(mask, childProcess, { + * message: 'Testing...', + * }) + * ``` */ type ReadlineKey = { ctrl?: boolean; name?: string } export function createKeyboardHandler( @@ -241,6 +254,12 @@ export function createKeyboardHandler( * - Buffers stdout/stderr when not in verbose mode. * - Shows a spinner when output is masked. * - Allows toggling between masked and unmasked output with ctrl+o. + * + * @example + * ```typescript + * const child = spawn("pnpm", ["test"], { stdio: ["inherit", "pipe", "pipe"] }) + * const exitCode = await attachOutputMask(child, { message: 'Running tests' }) + * ``` */ export function attachOutputMask( child: ChildProcess, @@ -384,6 +403,13 @@ export function attachOutputMask( * Convenience wrapper around spawn + attachOutputMask. * Spawns a child process and attaches the output masking system to it. * stdin is inherited, stdout and stderr are piped for masking control. + * + * @example + * ```typescript + * const exitCode = await runWithMask('pnpm', ['test'], { + * message: 'Running tests', + * }) + * ``` */ export async function runWithMask( command: string, diff --git a/src/suppress-warnings.ts b/src/suppress-warnings.ts index 6e7d3c277..e93df1e76 100644 --- a/src/suppress-warnings.ts +++ b/src/suppress-warnings.ts @@ -117,6 +117,13 @@ export function setMaxEventTargetListeners( /** * Restore the original process.emitWarning function. * Call this to re-enable all warnings after suppressing them. + * + * @example + * ```typescript + * suppressMaxListenersWarning() + * // ... do work ... + * restoreWarnings() // Re-enable all warnings + * ``` */ export function restoreWarnings(): void { if (originalEmitWarning) { diff --git a/src/temporary-executor.ts b/src/temporary-executor.ts index 731ac2b8f..f9cc85f7e 100644 --- a/src/temporary-executor.ts +++ b/src/temporary-executor.ts @@ -14,6 +14,13 @@ import { normalizePath } from './paths/normalize' * When package managers run commands via exec/npx/dlx, they execute in temporary directories * that are cleaned up after execution. Creating persistent shadows or modifying PATH * in these contexts can break subsequent package manager commands. + * + * @example + * ```typescript + * if (isRunningInTemporaryExecutor()) { + * console.log('Running in a temporary executor context') + * } + * ``` */ export function isRunningInTemporaryExecutor(cwd = process.cwd()): boolean { // Check environment variable for exec/npx/dlx indicators.