@socketsecurity/lib 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.0.4] - 2025-10-21
9
+
10
+ ### Fixed
11
+
12
+ - Fixed external dependency paths in root-level source files (corrected require paths from `../external/` to `./external/` in bin, cacache, fs, globs, spawn, spinner, and streams modules)
13
+
8
14
  ## [1.0.3] - 2025-10-21
9
15
 
10
16
  ### Fixed
package/dist/bin.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/bin.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Binary path resolution and execution utilities for package managers.\n * Provides cross-platform bin path lookup, command execution, and path normalization.\n */\n\nimport { APPDATA } from '#env/appdata'\nimport { HOME } from '#env/home'\nimport { LOCALAPPDATA } from '#env/localappdata'\nimport { XDG_DATA_HOME } from '#env/xdg-data-home'\n\nimport { readJsonSync } from './fs'\nimport { getOwn } from './objects'\nimport { isPath, normalizePath } from './path'\nimport { spawn } from './spawn'\n\nlet _fs: typeof import('node:fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _fs!\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _path!\n}\n\nlet _which: typeof import('which') | undefined\n/**\n * Lazily load the which module for finding executables.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getWhich() {\n if (_which === undefined) {\n _which = /*@__PURE__*/ require('../external/which')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _which!\n}\n\n/**\n * Execute a binary with the given arguments.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function execBin(\n binPath: string,\n args?: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n // Resolve the binary path.\n const resolvedPath = isPath(binPath)\n ? resolveBinPathSync(binPath)\n : await whichBin(binPath)\n\n if (!resolvedPath) {\n const error = new Error(`Binary not found: ${binPath}`) as Error & {\n code: string\n }\n error.code = 'ENOENT'\n throw error\n }\n\n // Execute the binary directly.\n const binCommand = Array.isArray(resolvedPath)\n ? // biome-ignore lint/style/noNonNullAssertion: which always returns non-empty array.\n resolvedPath[0]!\n : resolvedPath\n return await spawn(binCommand, args ?? [], options)\n}\n\n/**\n * Find and resolve a binary in the system PATH asynchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport async function whichBin(\n binName: string,\n options?: import('which').Options,\n): Promise<string | string[] | undefined> {\n const which = getWhich()\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = await which?.(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (options?.all) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Find and resolve a binary in the system PATH synchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport function whichBinSync(\n binName: string,\n options?: import('which').Options,\n): string | string[] | undefined {\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = getWhich()?.sync(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (getOwn(options, 'all')) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Check if a directory path contains any shadow bin patterns.\n */\nexport function isShadowBinPath(dirPath: string | undefined): boolean {\n if (!dirPath) {\n return false\n }\n // Check for node_modules/.bin pattern (Unix and Windows)\n const normalized = dirPath.replace(/\\\\/g, '/')\n return normalized.includes('node_modules/.bin')\n}\n\n/**\n * Find the real executable for a binary, bypassing shadow bins.\n */\nexport function findRealBin(\n binName: string,\n commonPaths: string[] = [],\n): string | undefined {\n const fs = getFs()\n const path = getPath()\n const which = getWhich()\n\n // Try common locations first.\n for (const binPath of commonPaths) {\n if (fs?.existsSync(binPath)) {\n return binPath\n }\n }\n\n // Fall back to which.sync if no direct path found.\n const binPath = which?.sync(binName, { nothrow: true })\n if (binPath) {\n const binDir = path?.dirname(binPath)\n\n if (isShadowBinPath(binDir)) {\n // This is likely a shadowed binary, try to find the real one.\n const allPaths = which?.sync(binName, { all: true, nothrow: true }) || []\n // Ensure allPaths is an array.\n const pathsArray = Array.isArray(allPaths)\n ? allPaths\n : typeof allPaths === 'string'\n ? [allPaths]\n : []\n\n for (const altPath of pathsArray) {\n const altDir = path?.dirname(altPath)\n if (!isShadowBinPath(altDir)) {\n return altPath\n }\n }\n }\n return binPath\n }\n // If all else fails, return undefined to indicate binary not found.\n return undefined\n}\n\n/**\n * Find the real npm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealNpm(): string {\n const fs = getFs()\n const path = getPath()\n\n // Try to find npm in the same directory as the node executable.\n const nodeDir = path?.dirname(process.execPath)\n const npmInNodeDir = path?.join(nodeDir, 'npm')\n\n if (fs?.existsSync(npmInNodeDir)) {\n return npmInNodeDir\n }\n\n // Try common npm locations.\n const commonPaths = ['/usr/local/bin/npm', '/usr/bin/npm']\n const result = findRealBin('npm', commonPaths)\n\n // If we found a valid path, return it.\n if (result && fs?.existsSync(result)) {\n return result\n }\n\n // As a last resort, try to use whichBinSync to find npm.\n // This handles cases where npm is installed in non-standard locations.\n const npmPath = whichBinSync('npm', { nothrow: true })\n if (npmPath && typeof npmPath === 'string' && fs?.existsSync(npmPath)) {\n return npmPath\n }\n\n // Return the basic 'npm' and let the system resolve it.\n return 'npm'\n}\n\n/**\n * Find the real pnpm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealPnpm(): string {\n const WIN32 = require('../constants/platform').WIN32\n const path = getPath()\n\n // Try common pnpm locations.\n const commonPaths = WIN32\n ? [\n // Windows common paths.\n path?.join(APPDATA as string, 'npm', 'pnpm.cmd'),\n path?.join(APPDATA as string, 'npm', 'pnpm'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm.cmd'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm'),\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm.cmd',\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm',\n ].filter(Boolean)\n : [\n // Unix common paths.\n '/usr/local/bin/pnpm',\n '/usr/bin/pnpm',\n path?.join(\n (XDG_DATA_HOME as string) || `${HOME as string}/.local/share`,\n 'pnpm/pnpm',\n ),\n path?.join(HOME as string, '.pnpm/pnpm'),\n ].filter(Boolean)\n\n return findRealBin('pnpm', commonPaths) ?? ''\n}\n\n/**\n * Find the real yarn executable, bypassing any aliases and shadow bins.\n */\nexport function findRealYarn(): string {\n const path = getPath()\n\n // Try common yarn locations.\n const commonPaths = [\n '/usr/local/bin/yarn',\n '/usr/bin/yarn',\n path?.join(HOME as string, '.yarn/bin/yarn'),\n path?.join(HOME as string, '.config/yarn/global/node_modules/.bin/yarn'),\n ].filter(Boolean)\n\n return findRealBin('yarn', commonPaths) ?? ''\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Resolve a binary path to its actual executable file.\n * Handles Windows .cmd wrappers and Unix shell scripts.\n */\nexport function resolveBinPathSync(binPath: string): string {\n const fs = getFs()\n const path = getPath()\n\n // If it's not an absolute path, try to find it in PATH first\n if (!path?.isAbsolute(binPath)) {\n try {\n const resolved = whichBinSync(binPath)\n if (resolved) {\n // biome-ignore lint/style/noParameterAssign: Reassigning for normalization.\n binPath = resolved as string\n }\n } catch {}\n }\n\n // Normalize the path once for consistent pattern matching.\n // biome-ignore lint/style/noParameterAssign: Normalizing path for consistent handling.\n binPath = normalizePath(binPath)\n\n // Handle empty string that normalized to '.' (current directory)\n if (binPath === '.') {\n return binPath\n }\n\n const ext = path?.extname(binPath)\n const extLowered = ext.toLowerCase()\n const basename = path?.basename(binPath, ext)\n const voltaIndex =\n basename === 'node' ? -1 : (/(?<=\\/)\\.volta\\//i.exec(binPath)?.index ?? -1)\n if (voltaIndex !== -1) {\n const voltaPath = binPath.slice(0, voltaIndex)\n const voltaToolsPath = path?.join(voltaPath, 'tools')\n const voltaImagePath = path?.join(voltaToolsPath, 'image')\n const voltaUserPath = path?.join(voltaToolsPath, 'user')\n const voltaPlatform = readJsonSync(\n path?.join(voltaUserPath, 'platform.json'),\n { throws: false },\n ) as\n // biome-ignore lint/suspicious/noExplicitAny: Volta platform config structure is dynamic.\n any\n const voltaNodeVersion = voltaPlatform?.node?.runtime\n const voltaNpmVersion = voltaPlatform?.node?.npm\n let voltaBinPath = ''\n if (basename === 'npm' || basename === 'npx') {\n if (voltaNpmVersion) {\n const relCliPath = `bin/${basename}-cli.js`\n voltaBinPath = path?.join(\n voltaImagePath,\n `npm/${voltaNpmVersion}/${relCliPath}`,\n )\n if (voltaNodeVersion && !fs?.existsSync(voltaBinPath)) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n } else {\n const voltaUserBinPath = path?.join(voltaUserPath, 'bin')\n const binInfo = readJsonSync(\n path?.join(voltaUserBinPath, `${basename}.json`),\n { throws: false },\n ) as\n // biome-ignore lint/suspicious/noExplicitAny: Volta bin info structure is dynamic.\n any\n const binPackage = binInfo?.package\n if (binPackage) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `packages/${binPackage}/bin/${basename}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = `${voltaBinPath}.cmd`\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n }\n if (voltaBinPath) {\n try {\n return normalizePath(fs?.realpathSync.native(voltaBinPath))\n } catch {}\n return voltaBinPath\n }\n }\n const WIN32 = require('../constants/platform').WIN32\n if (WIN32) {\n const hasKnownExt =\n extLowered === '' ||\n extLowered === '.cmd' ||\n extLowered === '.exe' ||\n extLowered === '.ps1'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n if (hasKnownExt && isNpmOrNpx) {\n // The quick route assumes a bin path like: C:\\Program Files\\nodejs\\npm.cmd\n const quickPath = path?.join(\n path?.dirname(binPath),\n `node_modules/npm/bin/${basename}-cli.js`,\n )\n if (fs?.existsSync(quickPath)) {\n try {\n return fs?.realpathSync.native(quickPath)\n } catch {}\n return quickPath\n }\n }\n let relPath = ''\n if (\n hasKnownExt &&\n // Only parse shell scripts and batch files, not actual executables.\n // .exe files are already executables and don't need path resolution from wrapper scripts.\n extLowered !== '.exe' &&\n // Check if file exists before attempting to read it to avoid ENOENT errors.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n if (isNpmOrNpx) {\n if (extLowered === '.cmd') {\n // \"npm.cmd\" and \"npx.cmd\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.cmd\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.cmd\n relPath =\n basename === 'npm'\n ? /(?<=\"NPM_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=\"NPX_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"npm\" and \"npx\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n } else if (extLowered === '.ps1') {\n // \"npm.ps1\" and \"npx.ps1\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.ps1\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.ps1\n relPath =\n basename === 'npm'\n ? /(?<=\\$NPM_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n : /(?<=\\$NPX_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n }\n } else if (isPnpmOrYarn) {\n if (extLowered === '.cmd') {\n // pnpm.cmd and yarn.cmd can have different formats depending on installation method\n // Common formats include:\n // 1. Setup-pnpm action format: node \"%~dp0\\..\\pnpm\\bin\\pnpm.cjs\" %*\n // 2. npm install -g pnpm format: similar to cmd-shim\n // 3. Standalone installer format: various patterns\n\n // Try setup-pnpm/setup-yarn action format first\n relPath =\n /(?<=node\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(source)?.[1] || ''\n\n // Try alternative format: \"%~dp0\\node.exe\" \"%~dp0\\..\\package\\bin\\binary.js\" %*\n if (!relPath) {\n relPath =\n /(?<=\"%~dp0\\\\[^\"]*node[^\"]*\"\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(\n source,\n )?.[1] || ''\n }\n\n // Try cmd-shim format as fallback\n if (!relPath) {\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '') {\n // Extensionless pnpm/yarn - try common shebang formats\n // Handle pnpm installed via standalone installer or global install\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // Note: may have multiple spaces between arguments\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n if (!relPath) {\n // Also try: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=exec\\s+node\\s+\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n }\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n relPath = /(?<=\"\\$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.ps1') {\n // PowerShell format\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.cmd') {\n // \"bin.CMD\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L98:\n //\n // @ECHO off\n // GOTO start\n // :find_dp0\n // SET dp0=%~dp0\n // EXIT /b\n // :start\n // SETLOCAL\n // CALL :find_dp0\n //\n // IF EXIST \"%dp0%\\node.exe\" (\n // SET \"_prog=%dp0%\\node.exe\"\n // ) ELSE (\n // SET \"_prog=node\"\n // SET PATHEXT=%PATHEXT:;.JS;=;%\n // )\n //\n // endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\..\\<PACKAGE_NAME>\\path\\to\\bin.js\" %*\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"bin\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L138:\n //\n // #!/bin/sh\n // basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n //\n // case `uname` in\n // *CYGWIN*|*MINGW*|*MSYS*)\n // if command -v cygpath > /dev/null 2>&1; then\n // basedir=`cygpath -w \"$basedir\"`\n // fi\n // ;;\n // esac\n //\n // if [ -x \"$basedir/node\" ]; then\n // exec \"$basedir/node\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // else\n // exec node \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // fi\n relPath = /(?<=\"$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '.ps1') {\n // \"bin.PS1\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L192:\n //\n // #!/usr/bin/env pwsh\n // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n //\n // $exe=\"\"\n // if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n // # Fix case when both the Windows and Linux builds of Node\n // # are installed in the same directory\n // $exe=\".exe\"\n // }\n // $ret=0\n // if (Test-Path \"$basedir/node$exe\") {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // } else {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // }\n // exit $ret\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n if (relPath) {\n // biome-ignore lint/style/noParameterAssign: Resolving wrapper script target.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n } else {\n // Handle Unix shell scripts (non-Windows platforms)\n let hasNoExt = extLowered === ''\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n\n // Handle special case where pnpm path in CI has extra segments.\n // In setup-pnpm GitHub Action, the path might be malformed like:\n // /home/runner/setup-pnpm/node_modules/.bin/pnpm/bin/pnpm.cjs\n // This happens when the shell script contains a relative path that\n // when resolved, creates an invalid nested structure.\n if (isPnpmOrYarn && binPath.includes('/.bin/pnpm/bin/')) {\n // Extract the correct pnpm bin path.\n const binIndex = binPath.indexOf('/.bin/pnpm')\n if (binIndex !== -1) {\n // Get the base path up to /.bin/pnpm.\n const baseBinPath = binPath.slice(0, binIndex + '/.bin/pnpm'.length)\n // Check if the original shell script exists.\n try {\n const stats = fs?.statSync(baseBinPath)\n // Only use this path if it's a file (the shell script).\n if (stats.isFile()) {\n // biome-ignore lint/style/noParameterAssign: Fixing pnpm nested bin structure.\n binPath = normalizePath(baseBinPath)\n // Recompute hasNoExt since we changed the path.\n hasNoExt = !path?.extname(binPath)\n }\n } catch {\n // If stat fails, continue with the original path.\n }\n }\n }\n\n if (\n hasNoExt &&\n (isPnpmOrYarn || isNpmOrNpx) &&\n // For extensionless files (Unix shell scripts), verify existence before reading.\n // This prevents ENOENT errors when the bin path doesn't exist.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n let relPath = ''\n\n if (isPnpmOrYarn) {\n // Handle pnpm/yarn Unix shell scripts.\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // or: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n // Example: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n // ^^^^^^^^^^^^^^^^^^^^^ captures this part\n // This regex needs to be more careful to not match \"$@\" at the end.\n relPath =\n /(?<=\"\\$basedir\\/)[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n }\n // Special case for setup-pnpm GitHub Action which may use a different format.\n // The setup-pnpm action creates a shell script that references ../pnpm/bin/pnpm.cjs\n if (!relPath) {\n // Try to match: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n const match = /exec\\s+node\\s+\"?\\$basedir\\/([^\"]+)\"?\\s+\"\\$@\"/.exec(\n source,\n )\n if (match) {\n relPath = match[1] || ''\n }\n }\n // Check if the extracted path looks wrong (e.g., pnpm/bin/pnpm.cjs without ../).\n // This happens with setup-pnpm action when it creates a malformed shell script.\n if (relPath && basename === 'pnpm' && relPath.startsWith('pnpm/')) {\n // The path should be ../pnpm/... not pnpm/...\n // Prepend ../ to fix the relative path.\n relPath = `../${relPath}`\n }\n } else if (isNpmOrNpx) {\n // Handle npm/npx Unix shell scripts\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n }\n\n if (relPath) {\n // Resolve the relative path to handle .. segments properly.\n // biome-ignore lint/style/noParameterAssign: Resolving shell script target.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n }\n try {\n const realPath = fs?.realpathSync.native(binPath)\n return normalizePath(realPath)\n } catch {}\n // Return normalized path even if realpath fails.\n return normalizePath(binPath)\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAwB;AACxB,kBAAqB;AACrB,0BAA6B;AAC7B,2BAA8B;AAE9B,gBAA6B;AAC7B,qBAAuB;AACvB,kBAAsC;AACtC,mBAAsB;AAEtB,IAAI;AAAA;AAKJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAGrB,UAAoB,QAAQ,SAAS;AAAA,EACvC;AAEA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AAEA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,WAAW;AAClB,MAAI,WAAW,QAAW;AACxB,aAAuB,QAAQ,mBAAmB;AAAA,EACpD;AAEA,SAAO;AACT;AAAA;AAMA,eAAsB,QACpB,SACA,MACA,SACA;AAEA,QAAM,mBAAe,oBAAO,OAAO,IAC/B,mCAAmB,OAAO,IAC1B,MAAM,SAAS,OAAO;AAE1B,MAAI,CAAC,cAAc;AACjB,UAAM,QAAQ,IAAI,MAAM,qBAAqB,OAAO,EAAE;AAGtD,UAAM,OAAO;AACb,UAAM;AAAA,EACR;AAGA,QAAM,aAAa,MAAM,QAAQ,YAAY;AAAA;AAAA,IAEzC,aAAa,CAAC;AAAA,MACd;AACJ,SAAO,UAAM,oBAAM,YAAY,QAAQ,CAAC,GAAG,OAAO;AACpD;AAOA,eAAsB,SACpB,SACA,SACwC;AACxC,QAAM,QAAQ,yBAAS;AAEvB,QAAM,OAAO,E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OAAO;AAAA,UACnC;AAAA,QACF,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAEA,QACE,aACC,gBAAgB;AAAA;AAAA,IAGjB,IAAI,WAAW,OAAO,GACtB;AACA,YAAM,SAAS,IAAI,aAAa,SAAS,MAAM;AAC/C,UAAI,UAAU;AAEd,UAAI,cAAc;AAIhB,kBACE,+CAA+C,KAAK,MAAM,IAAI,CAAC,KAAK;AACtE,YAAI,CAAC,SAAS;AAKZ,oBACE,sCAAsC,KAAK,MAAM,IAAI,CAAC,KAAK;AAAA,QAC/D;AAGA,YAAI,CAAC,SAAS;AAEZ,gBAAM,QAAQ,+CAA+C;AAAA,YAC3D;AAAA,UACF;AACA,cAAI,OAAO;AACT,sBAAU,MAAM,CAAC,KAAK;AAAA,UACxB;AAAA,QACF;AAGA,YAAI,WAAW,aAAa,UAAU,QAAQ,WAAW,OAAO,GAAG;AAGjE,oBAAU,MAAM,OAAO;AAAA,QACzB;AAAA,MACF,WAAW,YAAY;AAErB,kBACE,aAAa,QACT,0CAA0C,KAAK,MAAM,IAAI,CAAC,KAAK,KAC/D,0CAA0C,KAAK,MAAM,IAAI,CAAC,KAAK;AAAA,MACvE;AAEA,UAAI,SAAS;AAGX,sBAAU,2BAAc,MAAM,QAAQ,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AACA,MAAI;AACF,UAAM,WAAW,IAAI,aAAa,OAAO,OAAO;AAChD,eAAO,2BAAc,QAAQ;AAAA,EAC/B,QAAQ;AAAA,EAAC;AAET,aAAO,2BAAc,OAAO;AAC9B;",
4
+ "sourcesContent": ["/**\n * @fileoverview Binary path resolution and execution utilities for package managers.\n * Provides cross-platform bin path lookup, command execution, and path normalization.\n */\n\nimport { APPDATA } from '#env/appdata'\nimport { HOME } from '#env/home'\nimport { LOCALAPPDATA } from '#env/localappdata'\nimport { XDG_DATA_HOME } from '#env/xdg-data-home'\n\nimport { readJsonSync } from './fs'\nimport { getOwn } from './objects'\nimport { isPath, normalizePath } from './path'\nimport { spawn } from './spawn'\n\nlet _fs: typeof import('node:fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _fs!\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _path!\n}\n\nlet _which: typeof import('which') | undefined\n/**\n * Lazily load the which module for finding executables.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getWhich() {\n if (_which === undefined) {\n _which = /*@__PURE__*/ require('./external/which')\n }\n // biome-ignore lint/style/noNonNullAssertion: Initialized above.\n return _which!\n}\n\n/**\n * Execute a binary with the given arguments.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function execBin(\n binPath: string,\n args?: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n // Resolve the binary path.\n const resolvedPath = isPath(binPath)\n ? resolveBinPathSync(binPath)\n : await whichBin(binPath)\n\n if (!resolvedPath) {\n const error = new Error(`Binary not found: ${binPath}`) as Error & {\n code: string\n }\n error.code = 'ENOENT'\n throw error\n }\n\n // Execute the binary directly.\n const binCommand = Array.isArray(resolvedPath)\n ? // biome-ignore lint/style/noNonNullAssertion: which always returns non-empty array.\n resolvedPath[0]!\n : resolvedPath\n return await spawn(binCommand, args ?? [], options)\n}\n\n/**\n * Find and resolve a binary in the system PATH asynchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport async function whichBin(\n binName: string,\n options?: import('which').Options,\n): Promise<string | string[] | undefined> {\n const which = getWhich()\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = await which?.(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (options?.all) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Find and resolve a binary in the system PATH synchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport function whichBinSync(\n binName: string,\n options?: import('which').Options,\n): string | string[] | undefined {\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = getWhich()?.sync(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (getOwn(options, 'all')) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Check if a directory path contains any shadow bin patterns.\n */\nexport function isShadowBinPath(dirPath: string | undefined): boolean {\n if (!dirPath) {\n return false\n }\n // Check for node_modules/.bin pattern (Unix and Windows)\n const normalized = dirPath.replace(/\\\\/g, '/')\n return normalized.includes('node_modules/.bin')\n}\n\n/**\n * Find the real executable for a binary, bypassing shadow bins.\n */\nexport function findRealBin(\n binName: string,\n commonPaths: string[] = [],\n): string | undefined {\n const fs = getFs()\n const path = getPath()\n const which = getWhich()\n\n // Try common locations first.\n for (const binPath of commonPaths) {\n if (fs?.existsSync(binPath)) {\n return binPath\n }\n }\n\n // Fall back to which.sync if no direct path found.\n const binPath = which?.sync(binName, { nothrow: true })\n if (binPath) {\n const binDir = path?.dirname(binPath)\n\n if (isShadowBinPath(binDir)) {\n // This is likely a shadowed binary, try to find the real one.\n const allPaths = which?.sync(binName, { all: true, nothrow: true }) || []\n // Ensure allPaths is an array.\n const pathsArray = Array.isArray(allPaths)\n ? allPaths\n : typeof allPaths === 'string'\n ? [allPaths]\n : []\n\n for (const altPath of pathsArray) {\n const altDir = path?.dirname(altPath)\n if (!isShadowBinPath(altDir)) {\n return altPath\n }\n }\n }\n return binPath\n }\n // If all else fails, return undefined to indicate binary not found.\n return undefined\n}\n\n/**\n * Find the real npm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealNpm(): string {\n const fs = getFs()\n const path = getPath()\n\n // Try to find npm in the same directory as the node executable.\n const nodeDir = path?.dirname(process.execPath)\n const npmInNodeDir = path?.join(nodeDir, 'npm')\n\n if (fs?.existsSync(npmInNodeDir)) {\n return npmInNodeDir\n }\n\n // Try common npm locations.\n const commonPaths = ['/usr/local/bin/npm', '/usr/bin/npm']\n const result = findRealBin('npm', commonPaths)\n\n // If we found a valid path, return it.\n if (result && fs?.existsSync(result)) {\n return result\n }\n\n // As a last resort, try to use whichBinSync to find npm.\n // This handles cases where npm is installed in non-standard locations.\n const npmPath = whichBinSync('npm', { nothrow: true })\n if (npmPath && typeof npmPath === 'string' && fs?.existsSync(npmPath)) {\n return npmPath\n }\n\n // Return the basic 'npm' and let the system resolve it.\n return 'npm'\n}\n\n/**\n * Find the real pnpm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealPnpm(): string {\n const WIN32 = require('../constants/platform').WIN32\n const path = getPath()\n\n // Try common pnpm locations.\n const commonPaths = WIN32\n ? [\n // Windows common paths.\n path?.join(APPDATA as string, 'npm', 'pnpm.cmd'),\n path?.join(APPDATA as string, 'npm', 'pnpm'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm.cmd'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm'),\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm.cmd',\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm',\n ].filter(Boolean)\n : [\n // Unix common paths.\n '/usr/local/bin/pnpm',\n '/usr/bin/pnpm',\n path?.join(\n (XDG_DATA_HOME as string) || `${HOME as string}/.local/share`,\n 'pnpm/pnpm',\n ),\n path?.join(HOME as string, '.pnpm/pnpm'),\n ].filter(Boolean)\n\n return findRealBin('pnpm', commonPaths) ?? ''\n}\n\n/**\n * Find the real yarn executable, bypassing any aliases and shadow bins.\n */\nexport function findRealYarn(): string {\n const path = getPath()\n\n // Try common yarn locations.\n const commonPaths = [\n '/usr/local/bin/yarn',\n '/usr/bin/yarn',\n path?.join(HOME as string, '.yarn/bin/yarn'),\n path?.join(HOME as string, '.config/yarn/global/node_modules/.bin/yarn'),\n ].filter(Boolean)\n\n return findRealBin('yarn', commonPaths) ?? ''\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Resolve a binary path to its actual executable file.\n * Handles Windows .cmd wrappers and Unix shell scripts.\n */\nexport function resolveBinPathSync(binPath: string): string {\n const fs = getFs()\n const path = getPath()\n\n // If it's not an absolute path, try to find it in PATH first\n if (!path?.isAbsolute(binPath)) {\n try {\n const resolved = whichBinSync(binPath)\n if (resolved) {\n // biome-ignore lint/style/noParameterAssign: Reassigning for normalization.\n binPath = resolved as string\n }\n } catch {}\n }\n\n // Normalize the path once for consistent pattern matching.\n // biome-ignore lint/style/noParameterAssign: Normalizing path for consistent handling.\n binPath = normalizePath(binPath)\n\n // Handle empty string that normalized to '.' (current directory)\n if (binPath === '.') {\n return binPath\n }\n\n const ext = path?.extname(binPath)\n const extLowered = ext.toLowerCase()\n const basename = path?.basename(binPath, ext)\n const voltaIndex =\n basename === 'node' ? -1 : (/(?<=\\/)\\.volta\\//i.exec(binPath)?.index ?? -1)\n if (voltaIndex !== -1) {\n const voltaPath = binPath.slice(0, voltaIndex)\n const voltaToolsPath = path?.join(voltaPath, 'tools')\n const voltaImagePath = path?.join(voltaToolsPath, 'image')\n const voltaUserPath = path?.join(voltaToolsPath, 'user')\n const voltaPlatform = readJsonSync(\n path?.join(voltaUserPath, 'platform.json'),\n { throws: false },\n ) as\n // biome-ignore lint/suspicious/noExplicitAny: Volta platform config structure is dynamic.\n any\n const voltaNodeVersion = voltaPlatform?.node?.runtime\n const voltaNpmVersion = voltaPlatform?.node?.npm\n let voltaBinPath = ''\n if (basename === 'npm' || basename === 'npx') {\n if (voltaNpmVersion) {\n const relCliPath = `bin/${basename}-cli.js`\n voltaBinPath = path?.join(\n voltaImagePath,\n `npm/${voltaNpmVersion}/${relCliPath}`,\n )\n if (voltaNodeVersion && !fs?.existsSync(voltaBinPath)) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n } else {\n const voltaUserBinPath = path?.join(voltaUserPath, 'bin')\n const binInfo = readJsonSync(\n path?.join(voltaUserBinPath, `${basename}.json`),\n { throws: false },\n ) as\n // biome-ignore lint/suspicious/noExplicitAny: Volta bin info structure is dynamic.\n any\n const binPackage = binInfo?.package\n if (binPackage) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `packages/${binPackage}/bin/${basename}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = `${voltaBinPath}.cmd`\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n }\n if (voltaBinPath) {\n try {\n return normalizePath(fs?.realpathSync.native(voltaBinPath))\n } catch {}\n return voltaBinPath\n }\n }\n const WIN32 = require('../constants/platform').WIN32\n if (WIN32) {\n const hasKnownExt =\n extLowered === '' ||\n extLowered === '.cmd' ||\n extLowered === '.exe' ||\n extLowered === '.ps1'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n if (hasKnownExt && isNpmOrNpx) {\n // The quick route assumes a bin path like: C:\\Program Files\\nodejs\\npm.cmd\n const quickPath = path?.join(\n path?.dirname(binPath),\n `node_modules/npm/bin/${basename}-cli.js`,\n )\n if (fs?.existsSync(quickPath)) {\n try {\n return fs?.realpathSync.native(quickPath)\n } catch {}\n return quickPath\n }\n }\n let relPath = ''\n if (\n hasKnownExt &&\n // Only parse shell scripts and batch files, not actual executables.\n // .exe files are already executables and don't need path resolution from wrapper scripts.\n extLowered !== '.exe' &&\n // Check if file exists before attempting to read it to avoid ENOENT errors.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n if (isNpmOrNpx) {\n if (extLowered === '.cmd') {\n // \"npm.cmd\" and \"npx.cmd\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.cmd\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.cmd\n relPath =\n basename === 'npm'\n ? /(?<=\"NPM_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=\"NPX_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"npm\" and \"npx\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n } else if (extLowered === '.ps1') {\n // \"npm.ps1\" and \"npx.ps1\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.ps1\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.ps1\n relPath =\n basename === 'npm'\n ? /(?<=\\$NPM_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n : /(?<=\\$NPX_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n }\n } else if (isPnpmOrYarn) {\n if (extLowered === '.cmd') {\n // pnpm.cmd and yarn.cmd can have different formats depending on installation method\n // Common formats include:\n // 1. Setup-pnpm action format: node \"%~dp0\\..\\pnpm\\bin\\pnpm.cjs\" %*\n // 2. npm install -g pnpm format: similar to cmd-shim\n // 3. Standalone installer format: various patterns\n\n // Try setup-pnpm/setup-yarn action format first\n relPath =\n /(?<=node\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(source)?.[1] || ''\n\n // Try alternative format: \"%~dp0\\node.exe\" \"%~dp0\\..\\package\\bin\\binary.js\" %*\n if (!relPath) {\n relPath =\n /(?<=\"%~dp0\\\\[^\"]*node[^\"]*\"\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(\n source,\n )?.[1] || ''\n }\n\n // Try cmd-shim format as fallback\n if (!relPath) {\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '') {\n // Extensionless pnpm/yarn - try common shebang formats\n // Handle pnpm installed via standalone installer or global install\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // Note: may have multiple spaces between arguments\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n if (!relPath) {\n // Also try: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=exec\\s+node\\s+\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n }\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n relPath = /(?<=\"\\$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.ps1') {\n // PowerShell format\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.cmd') {\n // \"bin.CMD\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L98:\n //\n // @ECHO off\n // GOTO start\n // :find_dp0\n // SET dp0=%~dp0\n // EXIT /b\n // :start\n // SETLOCAL\n // CALL :find_dp0\n //\n // IF EXIST \"%dp0%\\node.exe\" (\n // SET \"_prog=%dp0%\\node.exe\"\n // ) ELSE (\n // SET \"_prog=node\"\n // SET PATHEXT=%PATHEXT:;.JS;=;%\n // )\n //\n // endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\..\\<PACKAGE_NAME>\\path\\to\\bin.js\" %*\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"bin\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L138:\n //\n // #!/bin/sh\n // basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n //\n // case `uname` in\n // *CYGWIN*|*MINGW*|*MSYS*)\n // if command -v cygpath > /dev/null 2>&1; then\n // basedir=`cygpath -w \"$basedir\"`\n // fi\n // ;;\n // esac\n //\n // if [ -x \"$basedir/node\" ]; then\n // exec \"$basedir/node\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // else\n // exec node \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // fi\n relPath = /(?<=\"$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '.ps1') {\n // \"bin.PS1\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L192:\n //\n // #!/usr/bin/env pwsh\n // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n //\n // $exe=\"\"\n // if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n // # Fix case when both the Windows and Linux builds of Node\n // # are installed in the same directory\n // $exe=\".exe\"\n // }\n // $ret=0\n // if (Test-Path \"$basedir/node$exe\") {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // } else {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // }\n // exit $ret\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n if (relPath) {\n // biome-ignore lint/style/noParameterAssign: Resolving wrapper script target.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n } else {\n // Handle Unix shell scripts (non-Windows platforms)\n let hasNoExt = extLowered === ''\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n\n // Handle special case where pnpm path in CI has extra segments.\n // In setup-pnpm GitHub Action, the path might be malformed like:\n // /home/runner/setup-pnpm/node_modules/.bin/pnpm/bin/pnpm.cjs\n // This happens when the shell script contains a relative path that\n // when resolved, creates an invalid nested structure.\n if (isPnpmOrYarn && binPath.includes('/.bin/pnpm/bin/')) {\n // Extract the correct pnpm bin path.\n const binIndex = binPath.indexOf('/.bin/pnpm')\n if (binIndex !== -1) {\n // Get the base path up to /.bin/pnpm.\n const baseBinPath = binPath.slice(0, binIndex + '/.bin/pnpm'.length)\n // Check if the original shell script exists.\n try {\n const stats = fs?.statSync(baseBinPath)\n // Only use this path if it's a file (the shell script).\n if (stats.isFile()) {\n // biome-ignore lint/style/noParameterAssign: Fixing pnpm nested bin structure.\n binPath = normalizePath(baseBinPath)\n // Recompute hasNoExt since we changed the path.\n hasNoExt = !path?.extname(binPath)\n }\n } catch {\n // If stat fails, continue with the original path.\n }\n }\n }\n\n if (\n hasNoExt &&\n (isPnpmOrYarn || isNpmOrNpx) &&\n // For extensionless files (Unix shell scripts), verify existence before reading.\n // This prevents ENOENT errors when the bin path doesn't exist.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n let relPath = ''\n\n if (isPnpmOrYarn) {\n // Handle pnpm/yarn Unix shell scripts.\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // or: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n // Example: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n // ^^^^^^^^^^^^^^^^^^^^^ captures this part\n // This regex needs to be more careful to not match \"$@\" at the end.\n relPath =\n /(?<=\"\\$basedir\\/)[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n }\n // Special case for setup-pnpm GitHub Action which may use a different format.\n // The setup-pnpm action creates a shell script that references ../pnpm/bin/pnpm.cjs\n if (!relPath) {\n // Try to match: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n const match = /exec\\s+node\\s+\"?\\$basedir\\/([^\"]+)\"?\\s+\"\\$@\"/.exec(\n source,\n )\n if (match) {\n relPath = match[1] || ''\n }\n }\n // Check if the extracted path looks wrong (e.g., pnpm/bin/pnpm.cjs without ../).\n // This happens with setup-pnpm action when it creates a malformed shell script.\n if (relPath && basename === 'pnpm' && relPath.startsWith('pnpm/')) {\n // The path should be ../pnpm/... not pnpm/...\n // Prepend ../ to fix the relative path.\n relPath = `../${relPath}`\n }\n } else if (isNpmOrNpx) {\n // Handle npm/npx Unix shell scripts\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n }\n\n if (relPath) {\n // Resolve the relative path to handle .. segments properly.\n // biome-ignore lint/style/noParameterAssign: Resolving shell script target.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n }\n try {\n const realPath = fs?.realpathSync.native(binPath)\n return normalizePath(realPath)\n } catch {}\n // Return normalized path even if realpath fails.\n return normalizePath(binPath)\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAwB;AACxB,kBAAqB;AACrB,0BAA6B;AAC7B,2BAA8B;AAE9B,gBAA6B;AAC7B,qBAAuB;AACvB,kBAAsC;AACtC,mBAAsB;AAEtB,IAAI;AAAA;AAKJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAGrB,UAAoB,QAAQ,SAAS;AAAA,EACvC;AAEA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AAEA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,WAAW;AAClB,MAAI,WAAW,QAAW;AACxB,aAAuB,QAAQ,kBAAkB;AAAA,EACnD;AAEA,SAAO;AACT;AAA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AM,QAAQ,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AACA,MAAI;AACF,UAAM,WAAW,IAAI,aAAa,OAAO,OAAO;AAChD,eAAO,2BAAc,QAAQ;AAAA,EAC/B,QAAQ;AAAA,EAAC;AAET,aAAO,2BAAc,OAAO;AAC9B;",
6
6
  "names": ["binPath"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/cacache.ts"],
4
- "sourcesContent": ["/** @fileoverview Cacache utilities for Socket ecosystem shared content-addressable cache. */\n\nimport { getSocketCacacheDir } from './paths'\n\nexport interface GetOptions {\n integrity?: string | undefined\n size?: number | undefined\n memoize?: boolean | undefined\n}\n\nexport interface PutOptions {\n integrity?: string | undefined\n size?: number | undefined\n // biome-ignore lint/suspicious/noExplicitAny: User-provided arbitrary metadata.\n metadata?: any | undefined\n memoize?: boolean | undefined\n}\n\nexport interface CacheEntry {\n data: Buffer\n integrity: string\n key: string\n // biome-ignore lint/suspicious/noExplicitAny: User-provided arbitrary metadata.\n metadata?: any | undefined\n path: string\n size: number\n time: number\n}\n\nexport interface RemoveOptions {\n /**\n * Optional key prefix to filter removals.\n * If provided, only keys starting with this prefix will be removed.\n * Can include wildcards (*) for pattern matching.\n *\n * @example\n * { prefix: 'socket-sdk' } // Simple prefix\n * { prefix: 'socket-sdk:scans:abc*' } // With wildcard\n */\n prefix?: string | undefined\n}\n\n/**\n * Get the cacache module for cache operations.\n */\nfunction getCacache() {\n return /*@__PURE__*/ require('../external/cacache')\n}\n\n/**\n * Convert wildcard pattern to regex for matching.\n * Supports * as wildcard (matches any characters).\n */\nfunction patternToRegex(pattern: string): RegExp {\n // Escape regex special characters except *\n const escaped = pattern.replaceAll(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n // Convert * to .* (match any characters)\n const regexPattern = escaped.replaceAll('*', '.*')\n return new RegExp(`^${regexPattern}`)\n}\n\n/**\n * Check if a key matches a pattern (with wildcard support).\n */\nfunction matchesPattern(key: string, pattern: string): boolean {\n // If no wildcards, use simple prefix matching (faster)\n if (!pattern.includes('*')) {\n return key.startsWith(pattern)\n }\n // Use regex for wildcard patterns\n const regex = patternToRegex(pattern)\n return regex.test(key)\n}\n\n/**\n * Clear entries from the Socket shared cache.\n *\n * Supports wildcard patterns (*) in prefix for flexible matching.\n * For simple prefixes without wildcards, uses efficient streaming.\n * For wildcard patterns, iterates and matches each entry.\n *\n * @param options - Optional configuration for selective clearing\n * @param options.prefix - Prefix or pattern to match (supports * wildcards)\n * @returns Number of entries removed (only when prefix is specified)\n *\n * @example\n * // Clear all entries\n * await clear()\n *\n * @example\n * // Clear entries with simple prefix\n * const removed = await clear({ prefix: 'socket-sdk:scans' })\n * console.log(`Removed ${removed} scan cache entries`)\n *\n * @example\n * // Clear entries with wildcard pattern\n * await clear({ prefix: 'socket-sdk:scans:abc*' })\n * await clear({ prefix: 'socket-sdk:npm/lodash/*' })\n */\nexport async function clear(\n options?: RemoveOptions | undefined,\n): Promise<number | undefined> {\n const opts = { __proto__: null, ...options } as RemoveOptions\n const cacache = getCacache()\n const cacheDir = getSocketCacacheDir()\n\n // If no prefix specified, clear everything.\n if (!opts.prefix) {\n try {\n await cacache.rm.all(cacheDir)\n return\n } catch (e) {\n // Ignore ENOTEMPTY errors - can occur when multiple processes\n // are cleaning up concurrently (e.g., in CI test environments).\n if ((e as NodeJS.ErrnoException)?.code !== 'ENOTEMPTY') {\n throw e\n }\n return\n }\n }\n\n const hasWildcard = opts.prefix.includes('*')\n\n // For simple prefix (no wildcards), use faster iteration.\n if (!hasWildcard) {\n let removed = 0\n const stream = cacache.ls.stream(cacheDir)\n\n for await (const entry of stream) {\n if (entry.key.startsWith(opts.prefix)) {\n try {\n await cacache.rm.entry(cacheDir, entry.key)\n removed++\n } catch {\n // Ignore individual removal errors (e.g., already removed by another process).\n }\n }\n }\n\n return removed\n }\n\n // For wildcard patterns, need to match each entry.\n let removed = 0\n const stream = cacache.ls.stream(cacheDir)\n\n for await (const entry of stream) {\n if (matchesPattern(entry.key, opts.prefix)) {\n try {\n await cacache.rm.entry(cacheDir, entry.key)\n removed++\n } catch {\n // Ignore individual removal errors.\n }\n }\n }\n\n return removed\n}\n\n/**\n * Get data from the Socket shared cache by key.\n * @throws {Error} When cache entry is not found.\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function get(\n key: string,\n options?: GetOptions | undefined,\n): Promise<CacheEntry> {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: \"pattern*\" }).',\n )\n }\n // biome-ignore lint/suspicious/noExplicitAny: cacache types are incomplete.\n const cacache = getCacache() as any\n return await cacache.get(getSocketCacacheDir(), key, options)\n}\n\n/**\n * Put data into the Socket shared cache with a key.\n *\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function put(\n key: string,\n data: string | Buffer,\n options?: PutOptions | undefined,\n) {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: \"pattern*\" }).',\n )\n }\n const cacache = getCacache()\n return await cacache.put(getSocketCacacheDir(), key, data, options)\n}\n\n/**\n * Remove an entry from the Socket shared cache by key.\n *\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function remove(key: string): Promise<unknown> {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Use clear({ prefix: \"pattern*\" }) to remove multiple entries.',\n )\n }\n // biome-ignore lint/suspicious/noExplicitAny: cacache types are incomplete.\n const cacache = getCacache() as any\n return await cacache.rm.entry(getSocketCacacheDir(), key)\n}\n\n/**\n * Get data from the Socket shared cache by key without throwing.\n */\nexport async function safeGet(\n key: string,\n options?: GetOptions | undefined,\n): Promise<CacheEntry | undefined> {\n try {\n return await get(key, options)\n } catch {\n return undefined\n }\n}\n\n/**\n * Execute a callback with a temporary directory for cache operations.\n */\nexport async function withTmp<T>(\n callback: (tmpDirPath: string) => Promise<T>,\n): Promise<T> {\n const cacache = getCacache()\n // The DefinitelyTyped types for cacache.tmp.withTmp are incorrect.\n // It actually returns the callback's return value, not void.\n return (await cacache.tmp.withTmp(\n getSocketCacacheDir(),\n {},\n // biome-ignore lint/suspicious/noExplicitAny: cacache types are incomplete.\n callback as any,\n )) as T\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAoC;AA2CpC,SAAS,aAAa;AACpB,SAAqB,QAAQ,qBAAqB;AACpD;AAMA,SAAS,eAAe,SAAyB;AAE/C,QAAM,UAAU,QAAQ,WAAW,sBAAsB,MAAM;AAE/D,QAAM,eAAe,QAAQ,WAAW,KAAK,IAAI;AACjD,SAAO,IAAI,OAAO,IAAI,YAAY,EAAE;AACtC;AAKA,SAAS,eAAe,KAAa,SAA0B;AAE7D,MAAI,CAAC,QAAQ,SAAS,GAAG,GAAG;AAC1B,WAAO,IAAI,WAAW,OAAO;AAAA,EAC/B;AAEA,QAAM,QAAQ,eAAe,OAAO;AACpC,SAAO,MAAM,KAAK,GAAG;AACvB;AA2BA,eAAsB,MACpB,SAC6B;AAC7B,QAAM,OAAO,EAAE,WAAW,MAAM,GAAG,QAAQ;AAC3C,QAAM,UAAU,WAAW;AAC3B,QAAM,eAAW,kCAAoB;AAGrC,MAAI,CAAC,KAAK,QAAQ;AAChB,QAAI;AACF,YAAM,QAAQ,GAAG,IAAI,QAAQ;AAC7B;AAAA,IACF,SAAS,GAAG;AAGV,UAAK,GAA6B,SAAS,aAAa;AACtD,cAAM;AAAA,MACR;AACA;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,KAAK,OAAO,SAAS,GAAG;AAG5C,MAAI,CAAC,aAAa;AAChB,QAAIA,WAAU;AACd,UAAMC,UAAS,QAAQ,GAAG,OAAO,QAAQ;AAEzC,qBAAiB,SAASA,SAAQ;AAChC,UAA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ACY;AACZ,QAAM,UAAU,WAAW;AAG3B,SAAQ,MAAM,QAAQ,IAAI;AAAA,QACxB,kCAAoB;AAAA,IACpB,CAAC;AAAA;AAAA,IAED;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/** @fileoverview Cacache utilities for Socket ecosystem shared content-addressable cache. */\n\nimport { getSocketCacacheDir } from './paths'\n\nexport interface GetOptions {\n integrity?: string | undefined\n size?: number | undefined\n memoize?: boolean | undefined\n}\n\nexport interface PutOptions {\n integrity?: string | undefined\n size?: number | undefined\n // biome-ignore lint/suspicious/noExplicitAny: User-provided arbitrary metadata.\n metadata?: any | undefined\n memoize?: boolean | undefined\n}\n\nexport interface CacheEntry {\n data: Buffer\n integrity: string\n key: string\n // biome-ignore lint/suspicious/noExplicitAny: User-provided arbitrary metadata.\n metadata?: any | undefined\n path: string\n size: number\n time: number\n}\n\nexport interface RemoveOptions {\n /**\n * Optional key prefix to filter removals.\n * If provided, only keys starting with this prefix will be removed.\n * Can include wildcards (*) for pattern matching.\n *\n * @example\n * { prefix: 'socket-sdk' } // Simple prefix\n * { prefix: 'socket-sdk:scans:abc*' } // With wildcard\n */\n prefix?: string | undefined\n}\n\n/**\n * Get the cacache module for cache operations.\n */\nfunction getCacache() {\n return /*@__PURE__*/ require('./external/cacache')\n}\n\n/**\n * Convert wildcard pattern to regex for matching.\n * Supports * as wildcard (matches any characters).\n */\nfunction patternToRegex(pattern: string): RegExp {\n // Escape regex special characters except *\n const escaped = pattern.replaceAll(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n // Convert * to .* (match any characters)\n const regexPattern = escaped.replaceAll('*', '.*')\n return new RegExp(`^${regexPattern}`)\n}\n\n/**\n * Check if a key matches a pattern (with wildcard support).\n */\nfunction matchesPattern(key: string, pattern: string): boolean {\n // If no wildcards, use simple prefix matching (faster)\n if (!pattern.includes('*')) {\n return key.startsWith(pattern)\n }\n // Use regex for wildcard patterns\n const regex = patternToRegex(pattern)\n return regex.test(key)\n}\n\n/**\n * Clear entries from the Socket shared cache.\n *\n * Supports wildcard patterns (*) in prefix for flexible matching.\n * For simple prefixes without wildcards, uses efficient streaming.\n * For wildcard patterns, iterates and matches each entry.\n *\n * @param options - Optional configuration for selective clearing\n * @param options.prefix - Prefix or pattern to match (supports * wildcards)\n * @returns Number of entries removed (only when prefix is specified)\n *\n * @example\n * // Clear all entries\n * await clear()\n *\n * @example\n * // Clear entries with simple prefix\n * const removed = await clear({ prefix: 'socket-sdk:scans' })\n * console.log(`Removed ${removed} scan cache entries`)\n *\n * @example\n * // Clear entries with wildcard pattern\n * await clear({ prefix: 'socket-sdk:scans:abc*' })\n * await clear({ prefix: 'socket-sdk:npm/lodash/*' })\n */\nexport async function clear(\n options?: RemoveOptions | undefined,\n): Promise<number | undefined> {\n const opts = { __proto__: null, ...options } as RemoveOptions\n const cacache = getCacache()\n const cacheDir = getSocketCacacheDir()\n\n // If no prefix specified, clear everything.\n if (!opts.prefix) {\n try {\n await cacache.rm.all(cacheDir)\n return\n } catch (e) {\n // Ignore ENOTEMPTY errors - can occur when multiple processes\n // are cleaning up concurrently (e.g., in CI test environments).\n if ((e as NodeJS.ErrnoException)?.code !== 'ENOTEMPTY') {\n throw e\n }\n return\n }\n }\n\n const hasWildcard = opts.prefix.includes('*')\n\n // For simple prefix (no wildcards), use faster iteration.\n if (!hasWildcard) {\n let removed = 0\n const stream = cacache.ls.stream(cacheDir)\n\n for await (const entry of stream) {\n if (entry.key.startsWith(opts.prefix)) {\n try {\n await cacache.rm.entry(cacheDir, entry.key)\n removed++\n } catch {\n // Ignore individual removal errors (e.g., already removed by another process).\n }\n }\n }\n\n return removed\n }\n\n // For wildcard patterns, need to match each entry.\n let removed = 0\n const stream = cacache.ls.stream(cacheDir)\n\n for await (const entry of stream) {\n if (matchesPattern(entry.key, opts.prefix)) {\n try {\n await cacache.rm.entry(cacheDir, entry.key)\n removed++\n } catch {\n // Ignore individual removal errors.\n }\n }\n }\n\n return removed\n}\n\n/**\n * Get data from the Socket shared cache by key.\n * @throws {Error} When cache entry is not found.\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function get(\n key: string,\n options?: GetOptions | undefined,\n): Promise<CacheEntry> {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: \"pattern*\" }).',\n )\n }\n // biome-ignore lint/suspicious/noExplicitAny: cacache types are incomplete.\n const cacache = getCacache() as any\n return await cacache.get(getSocketCacacheDir(), key, options)\n}\n\n/**\n * Put data into the Socket shared cache with a key.\n *\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function put(\n key: string,\n data: string | Buffer,\n options?: PutOptions | undefined,\n) {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Wildcards are only supported in clear({ prefix: \"pattern*\" }).',\n )\n }\n const cacache = getCacache()\n return await cacache.put(getSocketCacacheDir(), key, data, options)\n}\n\n/**\n * Remove an entry from the Socket shared cache by key.\n *\n * @throws {TypeError} If key contains wildcards (*)\n */\nexport async function remove(key: string): Promise<unknown> {\n if (key.includes('*')) {\n throw new TypeError(\n 'Cache key cannot contain wildcards (*). Use clear({ prefix: \"pattern*\" }) to remove multiple entries.',\n )\n }\n // biome-ignore lint/suspicious/noExplicitAny: cacache types are incomplete.\n const cacache = getCacache() as any\n return await cacache.rm.entry(getSocketCacacheDir(), key)\n}\n\n/**\n * Get data from the Socket shared cache by key without throwing.\n */\nexport async function safeGet(\n key: string,\n options?: GetOptions | undefined,\n): Promise<CacheEntry | undefined> {\n try {\n return await get(key, options)\n } catch {\n return undefined\n }\n}\n\n/**\n * Execute a callback with a temporary directory for cache operations.\n */\nexport async function withTmp<T>(\n callback: (tmpDirPath: string) => Promise<T>,\n): Promise<T> {\n const cacache = getCacache()\n // The DefinitelyTyped types for cacache.tmp.withTmp are incorrect.\n // It actually returns the callback's return value, not void.\n return (await cacache.tmp.withTmp(\n getSocketCacacheDir(),\n {},\n // biome-ignore lint/suspicious/noExplicitAny: c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@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/fs.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview File system utilities with cross-platform path handling.\n * Provides enhanced fs operations, glob matching, and directory traversal functions.\n */\n\nimport type { Abortable } from 'node:events'\nimport type {\n Dirent,\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n StatSyncOptions,\n WriteFileOptions,\n} from 'node:fs'\n\nimport { getAbortSignal } from '#constants/process'\n\nimport { isArray } from './arrays'\n\nconst abortSignal = getAbortSignal()\n\nimport { defaultIgnore, getGlobMatcher } from './globs'\nimport type { JsonReviver } from './json'\nimport { jsonParse } from './json'\nimport { objectFreeze, type Remap } from './objects'\nimport { normalizePath, pathLikeToString } from './path'\nimport { naturalCompare } from './sorts'\n\n// Type definitions\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex'\n\nexport type JsonContent = unknown\n\nexport interface FindUpOptions {\n cwd?: string\n onlyDirectories?: boolean\n onlyFiles?: boolean\n signal?: AbortSignal\n}\n\nexport interface FindUpSyncOptions {\n cwd?: string\n stopAt?: string\n onlyDirectories?: boolean\n onlyFiles?: boolean\n}\n\nexport interface IsDirEmptyOptions {\n ignore?: string[] | readonly string[] | undefined\n}\n\nexport interface ReadOptions extends Abortable {\n encoding?: BufferEncoding | string\n flag?: string\n}\n\nexport interface ReadDirOptions {\n ignore?: string[] | readonly string[] | undefined\n includeEmpty?: boolean | undefined\n sort?: boolean | undefined\n}\n\nexport type ReadFileOptions =\n | Remap<\n ObjectEncodingOptions &\n Abortable & {\n flag?: OpenMode | undefined\n }\n >\n | BufferEncoding\n | null\n\nexport type ReadJsonOptions = Remap<\n ReadFileOptions & {\n throws?: boolean | undefined\n reviver?: Parameters<typeof JSON.parse>[1]\n }\n>\n\nexport interface RemoveOptions {\n force?: boolean\n maxRetries?: number\n recursive?: boolean\n retryDelay?: number\n signal?: AbortSignal\n}\n\nexport interface SafeReadOptions extends ReadOptions {\n defaultValue?: unknown\n}\n\nexport interface WriteOptions extends Abortable {\n encoding?: BufferEncoding | string\n mode?: number\n flag?: string\n}\n\nexport interface WriteJsonOptions extends WriteOptions {\n EOL?: string | undefined\n finalEOL?: boolean | undefined\n replacer?: JsonReviver | undefined\n spaces?: number | string | undefined\n}\n\nconst defaultRemoveOptions = objectFreeze({\n __proto__: null,\n force: true,\n maxRetries: 3,\n recursive: true,\n retryDelay: 200,\n})\n\nlet _fs: typeof import('fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs as typeof import('fs')\n}\n\nlet _path: typeof import('path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path as typeof import('path')\n}\n\nlet _os: typeof import('os') | undefined\n/**\n * Lazily load the os module to avoid Webpack errors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getOs() {\n if (_os === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _os = /*@__PURE__*/ require('node:os')\n }\n return _os as typeof import('os')\n}\n\n/**\n * Process directory entries and filter for directories.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction innerReadDirNames(\n dirents: Dirent[],\n dirname: string | undefined,\n options?: ReadDirOptions | undefined,\n): string[] {\n const {\n ignore,\n includeEmpty = true,\n sort = true,\n } = { __proto__: null, ...options } as ReadDirOptions\n const path = getPath()\n const names = dirents\n .filter(\n (d: Dirent) =>\n d.isDirectory() &&\n (includeEmpty ||\n !isDirEmptySync(path.join(dirname || d.parentPath, d.name), {\n ignore,\n })),\n )\n .map((d: Dirent) => d.name)\n return sort ? names.sort(naturalCompare) : names\n}\n\n/**\n * Stringify JSON with custom formatting options.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringify(\n json: unknown,\n EOL: string,\n finalEOL: boolean,\n replacer: JsonReviver | undefined,\n spaces: number | string = 2,\n): string {\n const EOF = finalEOL ? EOL : ''\n const str = JSON.stringify(json, replacer, spaces)\n return `${str.replace(/\\n/g, EOL)}${EOF}`\n}\n\n/**\n * Find a file or directory by traversing up parent directories.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function findUp(\n name: string | string[] | readonly string[],\n options?: FindUpOptions | undefined,\n): Promise<string | undefined> {\n const { cwd = process.cwd(), signal = abortSignal } = {\n __proto__: null,\n ...options,\n } as FindUpOptions\n let { onlyDirectories = false, onlyFiles = true } = {\n __proto__: null,\n ...options,\n } as FindUpOptions\n if (onlyDirectories) {\n onlyFiles = false\n }\n if (onlyFiles) {\n onlyDirectories = false\n }\n const fs = getFs()\n const path = getPath()\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const names = isArray(name) ? name : [name as string]\n while (dir && dir !== root) {\n for (const n of names) {\n if (signal?.aborted) {\n return undefined\n }\n const thePath = path.join(dir, n)\n try {\n // eslint-disable-next-line no-await-in-loop\n const stats = await fs.promises.stat(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\n/**\n * Synchronously find a file or directory by traversing up parent directories.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function findUpSync(\n name: string | string[] | readonly string[],\n options?: FindUpSyncOptions | undefined,\n) {\n const { cwd = process.cwd(), stopAt } = {\n __proto__: null,\n ...options,\n } as FindUpSyncOptions\n let { onlyDirectories = false, onlyFiles = true } = {\n __proto__: null,\n ...options,\n } as FindUpSyncOptions\n if (onlyDirectories) {\n onlyFiles = false\n }\n if (onlyFiles) {\n onlyDirectories = false\n }\n const fs = getFs()\n const path = getPath()\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const stopDir = stopAt ? path.resolve(stopAt) : undefined\n const names = isArray(name) ? name : [name as string]\n while (dir && dir !== root) {\n // Check if we should stop at this directory.\n if (stopDir && dir === stopDir) {\n // Check current directory but don't go up.\n for (const n of names) {\n const thePath = path.join(dir, n)\n try {\n const stats = fs.statSync(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n return undefined\n }\n for (const n of names) {\n const thePath = path.join(dir, n)\n try {\n const stats = fs.statSync(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\n/**\n * Check if a path is a directory asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function isDir(filepath: PathLike) {\n return !!(await safeStats(filepath))?.isDirectory()\n}\n\n/**\n * Check if a path is a directory synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isDirSync(filepath: PathLike) {\n return !!safeStatsSync(filepath)?.isDirectory()\n}\n\n/**\n * Check if a directory is empty synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isDirEmptySync(\n dirname: PathLike,\n options?: IsDirEmptyOptions | undefined,\n) {\n const { ignore = defaultIgnore } = {\n __proto__: null,\n ...options,\n } as IsDirEmptyOptions\n const fs = getFs()\n try {\n const files = fs.readdirSync(dirname)\n const { length } = files\n if (length === 0) {\n return true\n }\n const matcher = getGlobMatcher(\n ignore as string[],\n {\n cwd: pathLikeToString(dirname),\n } as { cwd?: string; dot?: boolean; ignore?: string[]; nocase?: boolean },\n )\n let ignoredCount = 0\n for (let i = 0; i < length; i += 1) {\n const file = files[i]\n if (file && matcher(file)) {\n ignoredCount += 1\n }\n }\n return ignoredCount === length\n } catch {\n // Return false for non-existent paths or other errors.\n return false\n }\n}\n\n/**\n * Check if a path is a symbolic link synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isSymLinkSync(filepath: PathLike) {\n const fs = getFs()\n try {\n return fs.lstatSync(filepath).isSymbolicLink()\n } catch {}\n return false\n}\n\n/**\n * Read directory names asynchronously with filtering and sorting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readDirNames(\n dirname: PathLike,\n options?: ReadDirOptions | undefined,\n) {\n const fs = getFs()\n try {\n return innerReadDirNames(\n await fs.promises.readdir(dirname, {\n __proto__: null,\n encoding: 'utf8',\n withFileTypes: true,\n } as ObjectEncodingOptions & { withFileTypes: true }),\n String(dirname),\n options,\n )\n } catch {}\n return []\n}\n\n/**\n * Read directory names synchronously with filtering and sorting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readDirNamesSync(dirname: PathLike, options?: ReadDirOptions) {\n const fs = getFs()\n try {\n return innerReadDirNames(\n fs.readdirSync(dirname, {\n __proto__: null,\n encoding: 'utf8',\n withFileTypes: true,\n } as ObjectEncodingOptions & { withFileTypes: true }),\n String(dirname),\n options,\n )\n } catch {}\n return []\n}\n\n/**\n * Read a file as binary data asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readFileBinary(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n // Don't specify encoding to get a Buffer.\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n encoding: null,\n })\n}\n\n/**\n * Read a file as UTF-8 text asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readFileUtf8(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n encoding: 'utf8',\n })\n}\n\n/**\n * Read a file as binary data synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readFileBinarySync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n // Don't specify encoding to get a Buffer\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return fs.readFileSync(filepath, {\n ...opts,\n encoding: null,\n } as ObjectEncodingOptions)\n}\n\n/**\n * Read a file as UTF-8 text synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readFileUtf8Sync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return fs.readFileSync(filepath, {\n ...opts,\n encoding: 'utf8',\n } as ObjectEncodingOptions)\n}\n\n/**\n * Read and parse a JSON file asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readJson(\n filepath: PathLike,\n options?: ReadJsonOptions | string | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { reviver, throws, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as unknown as ReadJsonOptions\n const shouldThrow = throws === undefined || !!throws\n const fs = getFs()\n let content = ''\n try {\n content = await fs.promises.readFile(filepath, {\n __proto__: null,\n encoding: 'utf8',\n ...fsOptions,\n } as unknown as Parameters<typeof fs.promises.readFile>[1] & {\n encoding: string\n })\n } catch (e) {\n if (shouldThrow) {\n throw e\n }\n return undefined\n }\n return jsonParse(content, {\n filepath: String(filepath),\n reviver,\n throws: shouldThrow,\n })\n}\n\n/**\n * Read and parse a JSON file synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readJsonSync(\n filepath: PathLike,\n options?: ReadJsonOptions | string | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { reviver, throws, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as unknown as ReadJsonOptions\n const shouldThrow = throws === undefined || !!throws\n const fs = getFs()\n let content = ''\n try {\n content = fs.readFileSync(filepath, {\n __proto__: null,\n encoding: 'utf8',\n ...fsOptions,\n } as unknown as Parameters<typeof fs.readFileSync>[1] & {\n encoding: string\n })\n } catch (e) {\n if (shouldThrow) {\n throw e\n }\n return undefined\n }\n return jsonParse(content, {\n filepath: String(filepath),\n reviver,\n throws: shouldThrow,\n })\n}\n\n/**\n * Safely delete a file or directory asynchronously with built-in protections.\n * Uses `del` for safer deletion that prevents removing cwd and above by default.\n * Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories.\n * @throws {Error} When attempting to delete protected paths without force option.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeDelete(\n filepath: PathLike | PathLike[],\n options?: RemoveOptions | undefined,\n) {\n const del = /*@__PURE__*/ require('../external/del')\n const { deleteAsync } = del\n const opts = { __proto__: null, ...options } as RemoveOptions\n const patterns = isArray(filepath)\n ? filepath.map(pathLikeToString)\n : [pathLikeToString(filepath)]\n\n // Check if we're deleting within allowed directories.\n let shouldForce = opts.force !== false\n if (!shouldForce && patterns.length > 0) {\n const os = getOs()\n const path = getPath()\n const {\n getSocketCacacheDir,\n getSocketUserDir,\n } = /*@__PURE__*/ require('./paths')\n\n // Get allowed directories\n const tmpDir = os.tmpdir()\n const resolvedTmpDir = path.resolve(tmpDir)\n const cacacheDir = getSocketCacacheDir()\n const resolvedCacacheDir = path.resolve(cacacheDir)\n const socketUserDir = getSocketUserDir()\n const resolvedSocketUserDir = path.resolve(socketUserDir)\n\n // Check if all patterns are within allowed directories.\n const allInAllowedDirs = patterns.every(pattern => {\n const resolvedPath = path.resolve(pattern)\n\n // Check each allowed directory\n for (const allowedDir of [\n resolvedTmpDir,\n resolvedCacacheDir,\n resolvedSocketUserDir,\n ]) {\n const isInAllowedDir =\n resolvedPath.startsWith(allowedDir + path.sep) ||\n resolvedPath === allowedDir\n const relativePath = path.relative(allowedDir, resolvedPath)\n const isGoingBackward = relativePath.startsWith('..')\n\n if (isInAllowedDir && !isGoingBackward) {\n return true\n }\n }\n\n return false\n })\n\n if (allInAllowedDirs) {\n shouldForce = true\n }\n }\n\n await deleteAsync(patterns, {\n concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,\n dryRun: false,\n force: shouldForce,\n onlyFiles: false,\n })\n}\n\n/**\n * Safely delete a file or directory synchronously with built-in protections.\n * Uses `del` for safer deletion that prevents removing cwd and above by default.\n * Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories.\n * @throws {Error} When attempting to delete protected paths without force option.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeDeleteSync(\n filepath: PathLike | PathLike[],\n options?: RemoveOptions | undefined,\n) {\n const del = /*@__PURE__*/ require('../external/del')\n const { deleteSync } = del\n const opts = { __proto__: null, ...options } as RemoveOptions\n const patterns = isArray(filepath)\n ? filepath.map(pathLikeToString)\n : [pathLikeToString(filepath)]\n\n // Check if we're deleting within allowed directories.\n let shouldForce = opts.force !== false\n if (!shouldForce && patterns.length > 0) {\n const os = getOs()\n const path = getPath()\n const {\n getSocketCacacheDir,\n getSocketUserDir,\n } = /*@__PURE__*/ require('./paths')\n\n // Get allowed directories\n const tmpDir = os.tmpdir()\n const resolvedTmpDir = path.resolve(tmpDir)\n const cacacheDir = getSocketCacacheDir()\n const resolvedCacacheDir = path.resolve(cacacheDir)\n const socketUserDir = getSocketUserDir()\n const resolvedSocketUserDir = path.resolve(socketUserDir)\n\n // Check if all patterns are within allowed directories.\n const allInAllowedDirs = patterns.every(pattern => {\n const resolvedPath = path.resolve(pattern)\n\n // Check each allowed directory\n for (const allowedDir of [\n resolvedTmpDir,\n resolvedCacacheDir,\n resolvedSocketUserDir,\n ]) {\n const isInAllowedDir =\n resolvedPath.startsWith(allowedDir + path.sep) ||\n resolvedPath === allowedDir\n const relativePath = path.relative(allowedDir, resolvedPath)\n const isGoingBackward = relativePath.startsWith('..')\n\n if (isInAllowedDir && !isGoingBackward) {\n return true\n }\n }\n\n return false\n })\n\n if (allInAllowedDirs) {\n shouldForce = true\n }\n }\n\n deleteSync(patterns, {\n concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,\n dryRun: false,\n force: shouldForce,\n onlyFiles: false,\n })\n}\n\n/**\n * Safely read a file asynchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeReadFile(\n filepath: PathLike,\n options?: SafeReadOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n } as Abortable)\n } catch {}\n return undefined\n}\n\n/**\n * Safely get file stats asynchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeStats(filepath: PathLike) {\n const fs = getFs()\n try {\n return await fs.promises.stat(filepath)\n } catch {}\n return undefined\n}\n\n/**\n * Safely get file stats synchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeStatsSync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return fs.statSync(filepath, {\n __proto__: null,\n throwIfNoEntry: false,\n ...opts,\n } as StatSyncOptions)\n } catch {}\n return undefined\n}\n\n/**\n * Safely read a file synchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeReadFileSync(\n filepath: PathLike,\n options?: SafeReadOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return fs.readFileSync(filepath, {\n __proto__: null,\n ...opts,\n } as ObjectEncodingOptions)\n } catch {}\n return undefined\n}\n\n/**\n * Generate a unique filepath by adding number suffix if the path exists.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function uniqueSync(filepath: PathLike): string {\n const fs = getFs()\n const path = getPath()\n const filepathStr = String(filepath)\n\n // If the file doesn't exist, return as is\n if (!fs.existsSync(filepathStr)) {\n return normalizePath(filepathStr)\n }\n\n const dirname = path.dirname(filepathStr)\n const ext = path.extname(filepathStr)\n const basename = path.basename(filepathStr, ext)\n\n let counter = 1\n let uniquePath: string\n do {\n uniquePath = path.join(dirname, `${basename}-${counter}${ext}`)\n counter++\n } while (fs.existsSync(uniquePath))\n\n return normalizePath(uniquePath)\n}\n\n/**\n * Write JSON content to a file asynchronously with formatting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function writeJson(\n filepath: PathLike,\n jsonContent: unknown,\n options?: WriteJsonOptions | string,\n): Promise<void> {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as WriteJsonOptions\n const fs = getFs()\n const jsonString = stringify(\n jsonContent,\n EOL || '\\n',\n finalEOL !== undefined ? finalEOL : true,\n replacer,\n spaces,\n )\n await fs.promises.writeFile(filepath, jsonString, {\n encoding: 'utf8',\n ...fsOptions,\n __proto__: null,\n } as ObjectEncodingOptions)\n}\n\n/**\n * Write JSON content to a file synchronously with formatting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function writeJsonSync(\n filepath: PathLike,\n jsonContent: unknown,\n options?: WriteJsonOptions | string | undefined,\n): void {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {\n __proto__: null,\n ...opts,\n }\n const fs = getFs()\n const jsonString = stringify(\n jsonContent,\n EOL || '\\n',\n finalEOL !== undefined ? finalEOL : true,\n replacer,\n spaces,\n )\n fs.writeFileSync(filepath, jsonString, {\n encoding: 'utf8',\n ...fsOptions,\n __proto__: null,\n } as WriteFileOptions)\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AG,WAAW,UAAU;AAEjC,aAAO,2BAAc,UAAU;AACjC;AAAA;AAMA,eAAsB,UACpB,UACA,aACA,SACe;AACf,QAAM,OAAO,OAAO,YAAY,WAAW,EAAE,UAAU,QAAQ,IAAI;AACnE,QAAM,EAAE,KAAK,UAAU,UAAU,QAAQ,GAAG,UAAU,IAAI;AAAA,IACxD,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,KAAK,sBAAM;AACjB,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,OAAO;AAAA,IACP,aAAa,SAAY,WAAW;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AACA,QAAM,GAAG,SAAS,UAAU,UAAU,YAAY;AAAA,IAChD,UAAU;AAAA,IACV,GAAG;AAAA,IACH,WAAW;AAAA,EACb,CAA0B;AAC5B;AAAA;AAMO,SAAS,cACd,UACA,aACA,SACM;AACN,QAAM,OAAO,OAAO,YAAY,WAAW,EAAE,UAAU,QAAQ,IAAI;AACnE,QAAM,EAAE,KAAK,UAAU,UAAU,QAAQ,GAAG,UAAU,IAAI;AAAA,IACxD,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,KAAK,sBAAM;AACjB,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,OAAO;AAAA,IACP,aAAa,SAAY,WAAW;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AACA,KAAG,cAAc,UAAU,YAAY;AAAA,IACrC,UAAU;AAAA,IACV,GAAG;AAAA,IACH,WAAW;AAAA,EACb,CAAqB;AACvB;",
4
+ "sourcesContent": ["/**\n * @fileoverview File system utilities with cross-platform path handling.\n * Provides enhanced fs operations, glob matching, and directory traversal functions.\n */\n\nimport type { Abortable } from 'node:events'\nimport type {\n Dirent,\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n StatSyncOptions,\n WriteFileOptions,\n} from 'node:fs'\n\nimport { getAbortSignal } from '#constants/process'\n\nimport { isArray } from './arrays'\n\nconst abortSignal = getAbortSignal()\n\nimport { defaultIgnore, getGlobMatcher } from './globs'\nimport type { JsonReviver } from './json'\nimport { jsonParse } from './json'\nimport { objectFreeze, type Remap } from './objects'\nimport { normalizePath, pathLikeToString } from './path'\nimport { naturalCompare } from './sorts'\n\n// Type definitions\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex'\n\nexport type JsonContent = unknown\n\nexport interface FindUpOptions {\n cwd?: string\n onlyDirectories?: boolean\n onlyFiles?: boolean\n signal?: AbortSignal\n}\n\nexport interface FindUpSyncOptions {\n cwd?: string\n stopAt?: string\n onlyDirectories?: boolean\n onlyFiles?: boolean\n}\n\nexport interface IsDirEmptyOptions {\n ignore?: string[] | readonly string[] | undefined\n}\n\nexport interface ReadOptions extends Abortable {\n encoding?: BufferEncoding | string\n flag?: string\n}\n\nexport interface ReadDirOptions {\n ignore?: string[] | readonly string[] | undefined\n includeEmpty?: boolean | undefined\n sort?: boolean | undefined\n}\n\nexport type ReadFileOptions =\n | Remap<\n ObjectEncodingOptions &\n Abortable & {\n flag?: OpenMode | undefined\n }\n >\n | BufferEncoding\n | null\n\nexport type ReadJsonOptions = Remap<\n ReadFileOptions & {\n throws?: boolean | undefined\n reviver?: Parameters<typeof JSON.parse>[1]\n }\n>\n\nexport interface RemoveOptions {\n force?: boolean\n maxRetries?: number\n recursive?: boolean\n retryDelay?: number\n signal?: AbortSignal\n}\n\nexport interface SafeReadOptions extends ReadOptions {\n defaultValue?: unknown\n}\n\nexport interface WriteOptions extends Abortable {\n encoding?: BufferEncoding | string\n mode?: number\n flag?: string\n}\n\nexport interface WriteJsonOptions extends WriteOptions {\n EOL?: string | undefined\n finalEOL?: boolean | undefined\n replacer?: JsonReviver | undefined\n spaces?: number | string | undefined\n}\n\nconst defaultRemoveOptions = objectFreeze({\n __proto__: null,\n force: true,\n maxRetries: 3,\n recursive: true,\n retryDelay: 200,\n})\n\nlet _fs: typeof import('fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs as typeof import('fs')\n}\n\nlet _path: typeof import('path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path as typeof import('path')\n}\n\nlet _os: typeof import('os') | undefined\n/**\n * Lazily load the os module to avoid Webpack errors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getOs() {\n if (_os === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _os = /*@__PURE__*/ require('node:os')\n }\n return _os as typeof import('os')\n}\n\n/**\n * Process directory entries and filter for directories.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction innerReadDirNames(\n dirents: Dirent[],\n dirname: string | undefined,\n options?: ReadDirOptions | undefined,\n): string[] {\n const {\n ignore,\n includeEmpty = true,\n sort = true,\n } = { __proto__: null, ...options } as ReadDirOptions\n const path = getPath()\n const names = dirents\n .filter(\n (d: Dirent) =>\n d.isDirectory() &&\n (includeEmpty ||\n !isDirEmptySync(path.join(dirname || d.parentPath, d.name), {\n ignore,\n })),\n )\n .map((d: Dirent) => d.name)\n return sort ? names.sort(naturalCompare) : names\n}\n\n/**\n * Stringify JSON with custom formatting options.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringify(\n json: unknown,\n EOL: string,\n finalEOL: boolean,\n replacer: JsonReviver | undefined,\n spaces: number | string = 2,\n): string {\n const EOF = finalEOL ? EOL : ''\n const str = JSON.stringify(json, replacer, spaces)\n return `${str.replace(/\\n/g, EOL)}${EOF}`\n}\n\n/**\n * Find a file or directory by traversing up parent directories.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function findUp(\n name: string | string[] | readonly string[],\n options?: FindUpOptions | undefined,\n): Promise<string | undefined> {\n const { cwd = process.cwd(), signal = abortSignal } = {\n __proto__: null,\n ...options,\n } as FindUpOptions\n let { onlyDirectories = false, onlyFiles = true } = {\n __proto__: null,\n ...options,\n } as FindUpOptions\n if (onlyDirectories) {\n onlyFiles = false\n }\n if (onlyFiles) {\n onlyDirectories = false\n }\n const fs = getFs()\n const path = getPath()\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const names = isArray(name) ? name : [name as string]\n while (dir && dir !== root) {\n for (const n of names) {\n if (signal?.aborted) {\n return undefined\n }\n const thePath = path.join(dir, n)\n try {\n // eslint-disable-next-line no-await-in-loop\n const stats = await fs.promises.stat(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\n/**\n * Synchronously find a file or directory by traversing up parent directories.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function findUpSync(\n name: string | string[] | readonly string[],\n options?: FindUpSyncOptions | undefined,\n) {\n const { cwd = process.cwd(), stopAt } = {\n __proto__: null,\n ...options,\n } as FindUpSyncOptions\n let { onlyDirectories = false, onlyFiles = true } = {\n __proto__: null,\n ...options,\n } as FindUpSyncOptions\n if (onlyDirectories) {\n onlyFiles = false\n }\n if (onlyFiles) {\n onlyDirectories = false\n }\n const fs = getFs()\n const path = getPath()\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const stopDir = stopAt ? path.resolve(stopAt) : undefined\n const names = isArray(name) ? name : [name as string]\n while (dir && dir !== root) {\n // Check if we should stop at this directory.\n if (stopDir && dir === stopDir) {\n // Check current directory but don't go up.\n for (const n of names) {\n const thePath = path.join(dir, n)\n try {\n const stats = fs.statSync(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n return undefined\n }\n for (const n of names) {\n const thePath = path.join(dir, n)\n try {\n const stats = fs.statSync(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\n/**\n * Check if a path is a directory asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function isDir(filepath: PathLike) {\n return !!(await safeStats(filepath))?.isDirectory()\n}\n\n/**\n * Check if a path is a directory synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isDirSync(filepath: PathLike) {\n return !!safeStatsSync(filepath)?.isDirectory()\n}\n\n/**\n * Check if a directory is empty synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isDirEmptySync(\n dirname: PathLike,\n options?: IsDirEmptyOptions | undefined,\n) {\n const { ignore = defaultIgnore } = {\n __proto__: null,\n ...options,\n } as IsDirEmptyOptions\n const fs = getFs()\n try {\n const files = fs.readdirSync(dirname)\n const { length } = files\n if (length === 0) {\n return true\n }\n const matcher = getGlobMatcher(\n ignore as string[],\n {\n cwd: pathLikeToString(dirname),\n } as { cwd?: string; dot?: boolean; ignore?: string[]; nocase?: boolean },\n )\n let ignoredCount = 0\n for (let i = 0; i < length; i += 1) {\n const file = files[i]\n if (file && matcher(file)) {\n ignoredCount += 1\n }\n }\n return ignoredCount === length\n } catch {\n // Return false for non-existent paths or other errors.\n return false\n }\n}\n\n/**\n * Check if a path is a symbolic link synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isSymLinkSync(filepath: PathLike) {\n const fs = getFs()\n try {\n return fs.lstatSync(filepath).isSymbolicLink()\n } catch {}\n return false\n}\n\n/**\n * Read directory names asynchronously with filtering and sorting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readDirNames(\n dirname: PathLike,\n options?: ReadDirOptions | undefined,\n) {\n const fs = getFs()\n try {\n return innerReadDirNames(\n await fs.promises.readdir(dirname, {\n __proto__: null,\n encoding: 'utf8',\n withFileTypes: true,\n } as ObjectEncodingOptions & { withFileTypes: true }),\n String(dirname),\n options,\n )\n } catch {}\n return []\n}\n\n/**\n * Read directory names synchronously with filtering and sorting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readDirNamesSync(dirname: PathLike, options?: ReadDirOptions) {\n const fs = getFs()\n try {\n return innerReadDirNames(\n fs.readdirSync(dirname, {\n __proto__: null,\n encoding: 'utf8',\n withFileTypes: true,\n } as ObjectEncodingOptions & { withFileTypes: true }),\n String(dirname),\n options,\n )\n } catch {}\n return []\n}\n\n/**\n * Read a file as binary data asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readFileBinary(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n // Don't specify encoding to get a Buffer.\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n encoding: null,\n })\n}\n\n/**\n * Read a file as UTF-8 text asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readFileUtf8(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n encoding: 'utf8',\n })\n}\n\n/**\n * Read a file as binary data synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readFileBinarySync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n // Don't specify encoding to get a Buffer\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return fs.readFileSync(filepath, {\n ...opts,\n encoding: null,\n } as ObjectEncodingOptions)\n}\n\n/**\n * Read a file as UTF-8 text synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readFileUtf8Sync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return fs.readFileSync(filepath, {\n ...opts,\n encoding: 'utf8',\n } as ObjectEncodingOptions)\n}\n\n/**\n * Read and parse a JSON file asynchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readJson(\n filepath: PathLike,\n options?: ReadJsonOptions | string | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { reviver, throws, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as unknown as ReadJsonOptions\n const shouldThrow = throws === undefined || !!throws\n const fs = getFs()\n let content = ''\n try {\n content = await fs.promises.readFile(filepath, {\n __proto__: null,\n encoding: 'utf8',\n ...fsOptions,\n } as unknown as Parameters<typeof fs.promises.readFile>[1] & {\n encoding: string\n })\n } catch (e) {\n if (shouldThrow) {\n throw e\n }\n return undefined\n }\n return jsonParse(content, {\n filepath: String(filepath),\n reviver,\n throws: shouldThrow,\n })\n}\n\n/**\n * Read and parse a JSON file synchronously.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readJsonSync(\n filepath: PathLike,\n options?: ReadJsonOptions | string | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { reviver, throws, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as unknown as ReadJsonOptions\n const shouldThrow = throws === undefined || !!throws\n const fs = getFs()\n let content = ''\n try {\n content = fs.readFileSync(filepath, {\n __proto__: null,\n encoding: 'utf8',\n ...fsOptions,\n } as unknown as Parameters<typeof fs.readFileSync>[1] & {\n encoding: string\n })\n } catch (e) {\n if (shouldThrow) {\n throw e\n }\n return undefined\n }\n return jsonParse(content, {\n filepath: String(filepath),\n reviver,\n throws: shouldThrow,\n })\n}\n\n/**\n * Safely delete a file or directory asynchronously with built-in protections.\n * Uses `del` for safer deletion that prevents removing cwd and above by default.\n * Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories.\n * @throws {Error} When attempting to delete protected paths without force option.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeDelete(\n filepath: PathLike | PathLike[],\n options?: RemoveOptions | undefined,\n) {\n const del = /*@__PURE__*/ require('./external/del')\n const { deleteAsync } = del\n const opts = { __proto__: null, ...options } as RemoveOptions\n const patterns = isArray(filepath)\n ? filepath.map(pathLikeToString)\n : [pathLikeToString(filepath)]\n\n // Check if we're deleting within allowed directories.\n let shouldForce = opts.force !== false\n if (!shouldForce && patterns.length > 0) {\n const os = getOs()\n const path = getPath()\n const {\n getSocketCacacheDir,\n getSocketUserDir,\n } = /*@__PURE__*/ require('./paths')\n\n // Get allowed directories\n const tmpDir = os.tmpdir()\n const resolvedTmpDir = path.resolve(tmpDir)\n const cacacheDir = getSocketCacacheDir()\n const resolvedCacacheDir = path.resolve(cacacheDir)\n const socketUserDir = getSocketUserDir()\n const resolvedSocketUserDir = path.resolve(socketUserDir)\n\n // Check if all patterns are within allowed directories.\n const allInAllowedDirs = patterns.every(pattern => {\n const resolvedPath = path.resolve(pattern)\n\n // Check each allowed directory\n for (const allowedDir of [\n resolvedTmpDir,\n resolvedCacacheDir,\n resolvedSocketUserDir,\n ]) {\n const isInAllowedDir =\n resolvedPath.startsWith(allowedDir + path.sep) ||\n resolvedPath === allowedDir\n const relativePath = path.relative(allowedDir, resolvedPath)\n const isGoingBackward = relativePath.startsWith('..')\n\n if (isInAllowedDir && !isGoingBackward) {\n return true\n }\n }\n\n return false\n })\n\n if (allInAllowedDirs) {\n shouldForce = true\n }\n }\n\n await deleteAsync(patterns, {\n concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,\n dryRun: false,\n force: shouldForce,\n onlyFiles: false,\n })\n}\n\n/**\n * Safely delete a file or directory synchronously with built-in protections.\n * Uses `del` for safer deletion that prevents removing cwd and above by default.\n * Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories.\n * @throws {Error} When attempting to delete protected paths without force option.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeDeleteSync(\n filepath: PathLike | PathLike[],\n options?: RemoveOptions | undefined,\n) {\n const del = /*@__PURE__*/ require('./external/del')\n const { deleteSync } = del\n const opts = { __proto__: null, ...options } as RemoveOptions\n const patterns = isArray(filepath)\n ? filepath.map(pathLikeToString)\n : [pathLikeToString(filepath)]\n\n // Check if we're deleting within allowed directories.\n let shouldForce = opts.force !== false\n if (!shouldForce && patterns.length > 0) {\n const os = getOs()\n const path = getPath()\n const {\n getSocketCacacheDir,\n getSocketUserDir,\n } = /*@__PURE__*/ require('./paths')\n\n // Get allowed directories\n const tmpDir = os.tmpdir()\n const resolvedTmpDir = path.resolve(tmpDir)\n const cacacheDir = getSocketCacacheDir()\n const resolvedCacacheDir = path.resolve(cacacheDir)\n const socketUserDir = getSocketUserDir()\n const resolvedSocketUserDir = path.resolve(socketUserDir)\n\n // Check if all patterns are within allowed directories.\n const allInAllowedDirs = patterns.every(pattern => {\n const resolvedPath = path.resolve(pattern)\n\n // Check each allowed directory\n for (const allowedDir of [\n resolvedTmpDir,\n resolvedCacacheDir,\n resolvedSocketUserDir,\n ]) {\n const isInAllowedDir =\n resolvedPath.startsWith(allowedDir + path.sep) ||\n resolvedPath === allowedDir\n const relativePath = path.relative(allowedDir, resolvedPath)\n const isGoingBackward = relativePath.startsWith('..')\n\n if (isInAllowedDir && !isGoingBackward) {\n return true\n }\n }\n\n return false\n })\n\n if (allInAllowedDirs) {\n shouldForce = true\n }\n }\n\n deleteSync(patterns, {\n concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,\n dryRun: false,\n force: shouldForce,\n onlyFiles: false,\n })\n}\n\n/**\n * Safely read a file asynchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeReadFile(\n filepath: PathLike,\n options?: SafeReadOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n } as Abortable)\n } catch {}\n return undefined\n}\n\n/**\n * Safely get file stats asynchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeStats(filepath: PathLike) {\n const fs = getFs()\n try {\n return await fs.promises.stat(filepath)\n } catch {}\n return undefined\n}\n\n/**\n * Safely get file stats synchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeStatsSync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return fs.statSync(filepath, {\n __proto__: null,\n throwIfNoEntry: false,\n ...opts,\n } as StatSyncOptions)\n } catch {}\n return undefined\n}\n\n/**\n * Safely read a file synchronously, returning undefined on error.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeReadFileSync(\n filepath: PathLike,\n options?: SafeReadOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return fs.readFileSync(filepath, {\n __proto__: null,\n ...opts,\n } as ObjectEncodingOptions)\n } catch {}\n return undefined\n}\n\n/**\n * Generate a unique filepath by adding number suffix if the path exists.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function uniqueSync(filepath: PathLike): string {\n const fs = getFs()\n const path = getPath()\n const filepathStr = String(filepath)\n\n // If the file doesn't exist, return as is\n if (!fs.existsSync(filepathStr)) {\n return normalizePath(filepathStr)\n }\n\n const dirname = path.dirname(filepathStr)\n const ext = path.extname(filepathStr)\n const basename = path.basename(filepathStr, ext)\n\n let counter = 1\n let uniquePath: string\n do {\n uniquePath = path.join(dirname, `${basename}-${counter}${ext}`)\n counter++\n } while (fs.existsSync(uniquePath))\n\n return normalizePath(uniquePath)\n}\n\n/**\n * Write JSON content to a file asynchronously with formatting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function writeJson(\n filepath: PathLike,\n jsonContent: unknown,\n options?: WriteJsonOptions | string,\n): Promise<void> {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as WriteJsonOptions\n const fs = getFs()\n const jsonString = stringify(\n jsonContent,\n EOL || '\\n',\n finalEOL !== undefined ? finalEOL : true,\n replacer,\n spaces,\n )\n await fs.promises.writeFile(filepath, jsonString, {\n encoding: 'utf8',\n ...fsOptions,\n __proto__: null,\n } as ObjectEncodingOptions)\n}\n\n/**\n * Write JSON content to a file synchronously with formatting.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function writeJsonSync(\n filepath: PathLike,\n jsonContent: unknown,\n options?: WriteJsonOptions | string | undefined,\n): void {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {\n __proto__: null,\n ...opts,\n }\n const fs = getFs()\n const jsonString = stringify(\n jsonContent,\n EOL || '\\n',\n finalEOL !== undefined ? finalEOL : true,\n replacer,\n spaces,\n )\n fs.writeFileSync(filepath, jsonString, {\n encoding: 'utf8',\n ...fsOptions,\n __proto__: null,\n } as WriteFileOptions)\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAA+B;AAE/B,oBAAwB;AAIxB,mBAA8C;AAE9C,kBAA0B;AAC1B,qBAAyC;AACzC,kBAAgD;AAChD,mBAA+B;AAP/B,MAAM,kBAAc,+BAAe;AAgGnC,MAAM,2BAAuB,6BAAa;AAAA,EACxC,WAAW;AAAA,EACX,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,YAAY;AACd,CAAC;AAED,IAAI;AAAA;AAKJ,SAAS,QAAQ;AACf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Y,WAAW;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AACA,QAAM,GAAG,SAAS,UAAU,UAAU,YAAY;AAAA,IAChD,UAAU;AAAA,IACV,GAAG;AAAA,IACH,WAAW;AAAA,EACb,CAA0B;AAC5B;AAAA;AAMO,SAAS,cACd,UACA,aACA,SACM;AACN,QAAM,OAAO,OAAO,YAAY,WAAW,EAAE,UAAU,QAAQ,IAAI;AACnE,QAAM,EAAE,KAAK,UAAU,UAAU,QAAQ,GAAG,UAAU,IAAI;AAAA,IACxD,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,KAAK,sBAAM;AACjB,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,OAAO;AAAA,IACP,aAAa,SAAY,WAAW;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AACA,KAAG,cAAc,UAAU,YAAY;AAAA,IACrC,UAAU;AAAA,IACV,GAAG;AAAA,IACH,WAAW;AAAA,EACb,CAAqB;AACvB;",
6
6
  "names": []
7
7
  }
package/dist/globs.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/globs.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Glob pattern matching utilities with default ignore patterns.\n * Provides file filtering and glob matcher functions for npm-like behavior.\n */\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\nimport { objectFreeze as ObjectFreeze } from './objects'\n\n// Type definitions\ntype Pattern = string\n\ninterface FastGlobOptions {\n absolute?: boolean\n baseNameMatch?: boolean\n braceExpansion?: boolean\n caseSensitiveMatch?: boolean\n concurrency?: number\n cwd?: string\n deep?: number\n dot?: boolean\n extglob?: boolean\n followSymbolicLinks?: boolean\n fs?: unknown\n globstar?: boolean\n ignore?: string[]\n ignoreFiles?: string[]\n markDirectories?: boolean\n objectMode?: boolean\n onlyDirectories?: boolean\n onlyFiles?: boolean\n stats?: boolean\n suppressErrors?: boolean\n throwErrorOnBrokenSymbolicLink?: boolean\n unique?: boolean\n}\n\nexport interface GlobOptions extends FastGlobOptions {\n ignoreOriginals?: boolean\n recursive?: boolean\n}\n\nexport type { Pattern, FastGlobOptions }\n\nexport const defaultIgnore = ObjectFreeze([\n // Most of these ignored files can be included specifically if included in the\n // files globs. Exceptions to this are:\n // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#files\n // These can NOT be included.\n // https://github.com/npm/npm-packlist/blob/v10.0.0/lib/index.js#L280\n '**/.git',\n '**/.npmrc',\n // '**/bun.lockb?',\n '**/node_modules',\n // '**/package-lock.json',\n // '**/pnpm-lock.ya?ml',\n // '**/yarn.lock',\n // Include npm-packlist defaults:\n // https://github.com/npm/npm-packlist/blob/v10.0.0/lib/index.js#L15-L38\n '**/.DS_Store',\n '**/.gitignore',\n '**/.hg',\n '**/.lock-wscript',\n '**/.npmignore',\n '**/.svn',\n '**/.wafpickle-*',\n '**/.*.swp',\n '**/._*/**',\n '**/archived-packages/**',\n '**/build/config.gypi',\n '**/CVS',\n '**/npm-debug.log',\n '**/*.orig',\n // Inline generic socket-registry .gitignore entries.\n '**/.env',\n '**/.eslintcache',\n '**/.nvm',\n '**/.tap',\n '**/.vscode',\n '**/*.tsbuildinfo',\n '**/Thumbs.db',\n // Inline additional ignores.\n '**/bower_components',\n])\n\nlet _picomatch: typeof import('picomatch') | undefined\n/**\n * Lazily load the picomatch module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPicomatch() {\n if (_picomatch === undefined) {\n // The 'picomatch' package is browser safe.\n _picomatch = /*@__PURE__*/ require('../external/picomatch')\n }\n return _picomatch as typeof import('picomatch')\n}\n\nlet _fastGlob: typeof import('fast-glob') | undefined\n/**\n * Lazily load the fast-glob module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFastGlob() {\n if (_fastGlob === undefined) {\n const globExport = /*@__PURE__*/ require('../external/fast-glob')\n _fastGlob = globExport.default || globExport\n }\n return _fastGlob as typeof import('fast-glob')\n}\n\n/**\n * Create a stream of license file paths matching glob patterns.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function globStreamLicenses(\n dirname: string,\n options?: GlobOptions,\n): NodeJS.ReadableStream {\n const {\n ignore: ignoreOpt,\n ignoreOriginals,\n recursive,\n ...globOptions\n } = { __proto__: null, ...options } as GlobOptions\n const ignore = [\n ...(Array.isArray(ignoreOpt) ? ignoreOpt : defaultIgnore),\n '**/*.{cjs,cts,js,json,mjs,mts,ts}',\n ]\n if (ignoreOriginals) {\n ignore.push(\n /*@__INLINE__*/ require('../constants/paths')\n .LICENSE_ORIGINAL_GLOB_RECURSIVE,\n )\n }\n const fastGlob = getFastGlob()\n return fastGlob.globStream(\n [\n recursive\n ? /*@__INLINE__*/ require('../constants/paths').LICENSE_GLOB_RECURSIVE\n : /*@__INLINE__*/ require('../constants/paths').LICENSE_GLOB,\n ],\n {\n __proto__: null,\n absolute: true,\n caseSensitiveMatch: false,\n cwd: dirname,\n ...globOptions,\n ...(ignore ? { ignore } : {}),\n } as import('fast-glob').Options,\n )\n}\n\nconst matcherCache = new Map()\n/**\n * Get a cached glob matcher function.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function getGlobMatcher(\n glob: Pattern | Pattern[],\n options?: { dot?: boolean; nocase?: boolean; ignore?: string[] },\n): (path: string) => boolean {\n const patterns = Array.isArray(glob) ? glob : [glob]\n const key = JSON.stringify({ patterns, options })\n let matcher = matcherCache.get(key)\n if (matcher) {\n return matcher\n }\n\n // Separate positive and negative patterns.\n const positivePatterns = patterns.filter(p => !p.startsWith('!'))\n const negativePatterns = patterns\n .filter(p => p.startsWith('!'))\n .map(p => p.slice(1))\n\n const picomatch = getPicomatch()\n\n // Use ignore option for negation patterns.\n const matchOptions = {\n dot: true,\n nocase: true,\n ...options,\n ...(negativePatterns.length > 0 ? { ignore: negativePatterns } : {}),\n }\n\n matcher = picomatch(\n positivePatterns.length > 0 ? positivePatterns : patterns,\n matchOptions,\n )\n\n matcherCache.set(key, matcher)\n return matcher\n}\n"],
5
-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BAAoB,EAAE;AAAA;AAAA,IACpD;AAAA,IACA;AAAA,MACE,WAAW;AAAA,MACX,UAAU;AAAA,MACV,oBAAoB;AAAA,MACpB,KAAK;AAAA,MACL,GAAG;AAAA,MACH,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC7B;AAAA,EACF;AACF;AAEA,MAAM,eAAe,oBAAI,IAAI;AAAA;AAKtB,SAAS,eACd,MACA,SAC2B;AAC3B,QAAM,WAAW,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AACnD,QAAM,MAAM,KAAK,UAAU,EAAE,UAAU,QAAQ,CAAC;AAChD,MAAI,UAAU,aAAa,IAAI,GAAG;AAClC,MAAI,SAAS;AACX,WAAO;AAAA,EACT;AAGA,QAAM,mBAAmB,SAAS,OAAO,OAAK,CAAC,EAAE,WAAW,GAAG,CAAC;AAChE,QAAM,mBAAmB,SACtB,OAAO,OAAK,EAAE,WAAW,GAAG,CAAC,EAC7B,IAAI,OAAK,EAAE,MAAM,CAAC,CAAC;AAEtB,QAAM,YAAY,6BAAa;AAG/B,QAAM,eAAe;AAAA,IACnB,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,GAAG;AAAA,IACH,GAAI,iBAAiB,SAAS,IAAI,EAAE,QAAQ,iBAAiB,IAAI,CAAC;AAAA,EACpE;AAEA,YAAU;AAAA,IACR,iBAAiB,SAAS,IAAI,mBAAmB;AAAA,IACjD;AAAA,EACF;AAEA,eAAa,IAAI,KAAK,OAAO;AAC7B,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * @fileoverview Glob pattern matching utilities with default ignore patterns.\n * Provides file filtering and glob matcher functions for npm-like behavior.\n */\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\nimport { objectFreeze as ObjectFreeze } from './objects'\n\n// Type definitions\ntype Pattern = string\n\ninterface FastGlobOptions {\n absolute?: boolean\n baseNameMatch?: boolean\n braceExpansion?: boolean\n caseSensitiveMatch?: boolean\n concurrency?: number\n cwd?: string\n deep?: number\n dot?: boolean\n extglob?: boolean\n followSymbolicLinks?: boolean\n fs?: unknown\n globstar?: boolean\n ignore?: string[]\n ignoreFiles?: string[]\n markDirectories?: boolean\n objectMode?: boolean\n onlyDirectories?: boolean\n onlyFiles?: boolean\n stats?: boolean\n suppressErrors?: boolean\n throwErrorOnBrokenSymbolicLink?: boolean\n unique?: boolean\n}\n\nexport interface GlobOptions extends FastGlobOptions {\n ignoreOriginals?: boolean\n recursive?: boolean\n}\n\nexport type { Pattern, FastGlobOptions }\n\nexport const defaultIgnore = ObjectFreeze([\n // Most of these ignored files can be included specifically if included in the\n // files globs. Exceptions to this are:\n // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#files\n // These can NOT be included.\n // https://github.com/npm/npm-packlist/blob/v10.0.0/lib/index.js#L280\n '**/.git',\n '**/.npmrc',\n // '**/bun.lockb?',\n '**/node_modules',\n // '**/package-lock.json',\n // '**/pnpm-lock.ya?ml',\n // '**/yarn.lock',\n // Include npm-packlist defaults:\n // https://github.com/npm/npm-packlist/blob/v10.0.0/lib/index.js#L15-L38\n '**/.DS_Store',\n '**/.gitignore',\n '**/.hg',\n '**/.lock-wscript',\n '**/.npmignore',\n '**/.svn',\n '**/.wafpickle-*',\n '**/.*.swp',\n '**/._*/**',\n '**/archived-packages/**',\n '**/build/config.gypi',\n '**/CVS',\n '**/npm-debug.log',\n '**/*.orig',\n // Inline generic socket-registry .gitignore entries.\n '**/.env',\n '**/.eslintcache',\n '**/.nvm',\n '**/.tap',\n '**/.vscode',\n '**/*.tsbuildinfo',\n '**/Thumbs.db',\n // Inline additional ignores.\n '**/bower_components',\n])\n\nlet _picomatch: typeof import('picomatch') | undefined\n/**\n * Lazily load the picomatch module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPicomatch() {\n if (_picomatch === undefined) {\n // The 'picomatch' package is browser safe.\n _picomatch = /*@__PURE__*/ require('./external/picomatch')\n }\n return _picomatch as typeof import('picomatch')\n}\n\nlet _fastGlob: typeof import('fast-glob') | undefined\n/**\n * Lazily load the fast-glob module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFastGlob() {\n if (_fastGlob === undefined) {\n const globExport = /*@__PURE__*/ require('./external/fast-glob')\n _fastGlob = globExport.default || globExport\n }\n return _fastGlob as typeof import('fast-glob')\n}\n\n/**\n * Create a stream of license file paths matching glob patterns.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function globStreamLicenses(\n dirname: string,\n options?: GlobOptions,\n): NodeJS.ReadableStream {\n const {\n ignore: ignoreOpt,\n ignoreOriginals,\n recursive,\n ...globOptions\n } = { __proto__: null, ...options } as GlobOptions\n const ignore = [\n ...(Array.isArray(ignoreOpt) ? ignoreOpt : defaultIgnore),\n '**/*.{cjs,cts,js,json,mjs,mts,ts}',\n ]\n if (ignoreOriginals) {\n ignore.push(\n /*@__INLINE__*/ require('../constants/paths')\n .LICENSE_ORIGINAL_GLOB_RECURSIVE,\n )\n }\n const fastGlob = getFastGlob()\n return fastGlob.globStream(\n [\n recursive\n ? /*@__INLINE__*/ require('../constants/paths').LICENSE_GLOB_RECURSIVE\n : /*@__INLINE__*/ require('../constants/paths').LICENSE_GLOB,\n ],\n {\n __proto__: null,\n absolute: true,\n caseSensitiveMatch: false,\n cwd: dirname,\n ...globOptions,\n ...(ignore ? { ignore } : {}),\n } as import('fast-glob').Options,\n )\n}\n\nconst matcherCache = new Map()\n/**\n * Get a cached glob matcher function.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function getGlobMatcher(\n glob: Pattern | Pattern[],\n options?: { dot?: boolean; nocase?: boolean; ignore?: string[] },\n): (path: string) => boolean {\n const patterns = Array.isArray(glob) ? glob : [glob]\n const key = JSON.stringify({ patterns, options })\n let matcher = matcherCache.get(key)\n if (matcher) {\n return matcher\n }\n\n // Separate positive and negative patterns.\n const positivePatterns = patterns.filter(p => !p.startsWith('!'))\n const negativePatterns = patterns\n .filter(p => p.startsWith('!'))\n .map(p => p.slice(1))\n\n const picomatch = getPicomatch()\n\n // Use ignore option for negation patterns.\n const matchOptions = {\n dot: true,\n nocase: true,\n ...options,\n ...(negativePatterns.length > 0 ? { ignore: negativePatterns } : {}),\n }\n\n matcher = picomatch(\n positivePatterns.length > 0 ? positivePatterns : patterns,\n matchOptions,\n )\n\n matcherCache.set(key, matcher)\n return matcher\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,qBAA6C;AAqCtC,MAAM,oBAAgB,eAAAA,cAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxC;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACF,CAAC;AAED,IAAI;AAAA;AAMJ,SAAS,eAAe;AACtB,MAAI,eAAe,QAAW;AAE5B,iBAA2B,QAAQ,sBAAsB;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAMJ,SAAS,cAAc;AACrB,MAAI,cAAc,QAAW;AAC3B,UAAM,aAA2B,QAAQ,sBAAsB;AAC/D,gBAAY,WAAW,WAAW;AAAA,EACpC;AACA,SAAO;AACT;AAAA;AAMO,SAAS,mBACd,SACA,SACuB;AACvB,QAAM;AAAA,IACJ,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACL,IAAI,EAAE,WAAW,MAAM,GAAG,QAAQ;AAClC,QAAM,SAAS;AAAA,IACb,GAAI,MAAM,QAAQ,SAAS,IAAI,YAAY;AAAA,IAC3C;AAA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map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/spawn.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Child process spawning utilities with cross-platform support.\n * Provides enhanced spawn functionality with stdio handling and error management.\n *\n * SECURITY: Array-Based Arguments Prevent Command Injection\n *\n * This module uses array-based arguments for all command execution, which is the\n * PRIMARY DEFENSE against command injection attacks. When you pass arguments as\n * an array to spawn():\n *\n * spawn('npx', ['sfw', tool, ...args], { shell: true })\n *\n * Node.js handles escaping automatically. Each argument is passed directly to the\n * OS without shell interpretation. Shell metacharacters like ; | & $ ( ) ` are\n * treated as LITERAL STRINGS, not as commands. This approach is secure even when\n * shell: true is used on Windows for .cmd/.bat file resolution.\n *\n * UNSAFE ALTERNATIVE (not used in this codebase):\n * spawn(`npx sfw ${tool} ${args.join(' ')}`, { shell: true }) // \u2716 VULNERABLE\n *\n * String concatenation allows injection. For example, if tool = \"foo; rm -rf /\",\n * the shell would execute both commands. Array-based arguments prevent this.\n *\n * References:\n * - https://nodejs.org/api/child_process.html#child_processspawncommand-args-options\n * - https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html\n */\n\nimport { getAbortSignal, getSpinner } from '#constants/process'\n\nimport { isArray } from './arrays'\n\nconst abortSignal = getAbortSignal()\nconst spinner = getSpinner()\n\nimport { getOwn, hasOwn } from './objects'\nimport { stripAnsi } from './strings'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\nconst windowsScriptExtRegExp = /\\.(?:cmd|bat|ps1)$/i\n\nlet _child_process: typeof import('node:child_process') | undefined\n/**\n * Lazily load the child_process module.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getChildProcess() {\n if (_child_process === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _child_process = /*@__PURE__*/ require('node:child_process')\n }\n return _child_process as typeof import('node:child_process')\n}\n\n// Type for promise-spawn options.\nexport type PromiseSpawnOptions = {\n cwd?: string | undefined\n stdioString?: boolean | undefined\n stdio?: StdioType | undefined\n env?: NodeJS.ProcessEnv | undefined\n shell?: boolean | string | undefined\n signal?: AbortSignal | undefined\n timeout?: number | undefined\n uid?: number | undefined\n gid?: number | undefined\n}\n\n// Type for promise-spawn result.\nexport type PromiseSpawnResult = Promise<{\n cmd: string\n args: string[] | readonly string[]\n code: number\n signal: NodeJS.Signals | null\n stdout: string | Buffer\n stderr: string | Buffer\n}> & {\n process: ChildProcessType\n stdin: WritableStreamType | null\n}\n\nlet _npmCliPromiseSpawn:\n | ((\n cmd: string,\n args: string[],\n options?: PromiseSpawnOptions | undefined,\n extra?: SpawnExtra | undefined,\n ) => PromiseSpawnResult)\n | undefined\n/**\n * Lazily load the promise-spawn module for async process spawning.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getNpmcliPromiseSpawn() {\n if (_npmCliPromiseSpawn === undefined) {\n _npmCliPromiseSpawn = /*@__PURE__*/ require('../external/@npmcli/promise-spawn')\n }\n return _npmCliPromiseSpawn as unknown as typeof import('@npmcli/promise-spawn')\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path as typeof import('node:path')\n}\n\n/**\n * Check if a value is a spawn error.\n */\nexport type SpawnError = {\n args: string[]\n cmd: string\n code: number\n name: string\n message: string\n signal: NodeJS.Signals | null\n stack: string\n stderr: string | Buffer\n stdout: string | Buffer\n}\n\nexport type SpawnErrorWithOutputString = SpawnError & {\n stdout: string\n stderr: string\n}\n\nexport type SpawnErrorWithOutputBuffer = SpawnError & {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport type SpawnExtra = Record<string, unknown>\n\nexport type IOType = 'pipe' | 'ignore' | 'inherit' | 'overlapped'\nexport type StdioType = IOType | 'ipc' | Array<IOType | 'ipc'>\n\nexport interface SpawnSyncReturns<T> {\n pid: number\n output: Array<T | null>\n stdout: T\n stderr: T\n status: number | null\n signal: NodeJS.Signals | null\n error?: Error | undefined\n}\n\n/**\n * Check if a value is a spawn error with expected properties.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isSpawnError(value: unknown): value is SpawnError {\n if (value === null || typeof value !== 'object') {\n return false\n }\n // Check for spawn-specific error properties.\n const err = value as Record<string, unknown>\n return (\n (hasOwn(err, 'code') && typeof err['code'] !== 'undefined') ||\n (hasOwn(err, 'errno') && typeof err['errno'] !== 'undefined') ||\n (hasOwn(err, 'syscall') && typeof err['syscall'] === 'string')\n )\n}\n\n/**\n * Check if stdio configuration matches a specific type.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isStdioType(\n stdio: string | string[],\n type?: StdioType | undefined,\n): boolean {\n // If called with one argument, check if it's a valid stdio type.\n // biome-ignore lint/complexity/noArguments: Function overload detection for single vs two-arg calls.\n if (arguments.length === 1) {\n const validTypes = ['pipe', 'ignore', 'inherit', 'overlapped']\n return typeof stdio === 'string' && validTypes.includes(stdio)\n }\n // Original two-argument behavior.\n return (\n stdio === type ||\n ((stdio === null || stdio === undefined) && type === 'pipe') ||\n (isArray(stdio) &&\n stdio.length > 2 &&\n stdio[0] === type &&\n stdio[1] === type &&\n stdio[2] === type)\n )\n}\n\n/**\n * Strip ANSI escape codes from spawn result stdout and stderr.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction stripAnsiFromSpawnResult(result: unknown): unknown {\n const res = result as {\n stdout?: string | Buffer\n stderr?: string | Buffer\n }\n const { stderr, stdout } = res\n if (typeof stdout === 'string') {\n res.stdout = stripAnsi(stdout)\n }\n if (typeof stderr === 'string') {\n res.stderr = stripAnsi(stderr)\n }\n return res\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n// Duplicated from Node.js child_process.SpawnOptions\n// These are the options passed to child_process.spawn()\ninterface NodeSpawnOptions {\n cwd?: string | URL | undefined\n env?: NodeJS.ProcessEnv | undefined\n argv0?: string | undefined\n // biome-ignore lint/suspicious/noExplicitAny: Stdio can be complex union of types from Node.js.\n stdio?: any\n detached?: boolean | undefined\n uid?: number | undefined\n gid?: number | undefined\n serialization?: 'json' | 'advanced' | undefined\n shell?: boolean | string | undefined\n windowsVerbatimArguments?: boolean | undefined\n windowsHide?: boolean | undefined\n signal?: AbortSignal | undefined\n timeout?: number | undefined\n killSignal?: NodeJS.Signals | number | undefined\n}\n\n// Duplicated from Node.js child_process.ChildProcess\n// This represents a spawned child process\ninterface ChildProcessType {\n stdin: NodeJS.WritableStream | null\n stdout: NodeJS.ReadableStream | null\n stderr: NodeJS.ReadableStream | null\n // biome-ignore lint/suspicious/noExplicitAny: IPC channel type from Node.js.\n readonly channel?: any\n readonly stdio: [\n NodeJS.WritableStream | null,\n NodeJS.ReadableStream | null,\n NodeJS.ReadableStream | null,\n NodeJS.ReadableStream | NodeJS.WritableStream | null | undefined,\n NodeJS.ReadableStream | NodeJS.WritableStream | null | undefined,\n ]\n readonly killed: boolean\n readonly pid?: number | undefined\n readonly connected: boolean\n readonly exitCode: number | null\n readonly signalCode: NodeJS.Signals | null\n readonly spawnargs: string[]\n readonly spawnfile: string\n kill(signal?: NodeJS.Signals | number): boolean\n // biome-ignore lint/suspicious/noExplicitAny: IPC message type from Node.js.\n send(message: any, callback?: (error: Error | null) => void): boolean\n send(\n // biome-ignore lint/suspicious/noExplicitAny: IPC message and handle types from Node.js.\n message: any,\n // biome-ignore lint/suspicious/noExplicitAny: IPC message and handle types from Node.js.\n sendHandle?: any | undefined,\n callback?: (error: Error | null) => void,\n ): boolean\n send(\n // biome-ignore lint/suspicious/noExplicitAny: IPC message, handle, and options types from Node.js.\n message: any,\n // biome-ignore lint/suspicious/noExplicitAny: IPC message, handle, and options types from Node.js.\n sendHandle?: any | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: IPC message, handle, and options types from Node.js.\n options?: any | undefined,\n callback?: (error: Error | null) => void,\n ): boolean\n disconnect(): void\n unref(): void\n ref(): void\n}\n\n// Duplicated from Node.js stream.Writable\ninterface WritableStreamType {\n writable: boolean\n writableEnded: boolean\n writableFinished: boolean\n writableHighWaterMark: number\n writableLength: number\n writableObjectMode: boolean\n writableCorked: number\n destroyed: boolean\n write(\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n chunk: any,\n encoding?: BufferEncoding | undefined,\n callback?: (error?: Error | null) => void,\n ): boolean\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n write(chunk: any, callback?: (error?: Error | null) => void): boolean\n end(cb?: () => void): this\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n end(chunk: any, cb?: () => void): this\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n end(chunk: any, encoding?: BufferEncoding | undefined, cb?: () => void): this\n cork(): void\n uncork(): void\n destroy(error?: Error | undefined): this\n}\n\n/**\n * Spawn a child process with enhanced error handling and output capture.\n */\nexport type SpawnOptions = import('./objects').Remap<\n NodeSpawnOptions & {\n spinner?: import('./spinner').Spinner | undefined\n stdioString?: boolean\n stripAnsi?: boolean\n }\n>\nexport type SpawnResult = PromiseSpawnResult\nexport type SpawnStdioResult = {\n cmd: string\n args: string[] | readonly string[]\n code: number\n signal: NodeJS.Signals | null\n stdout: string | Buffer\n stderr: string | Buffer\n}\n\n/**\n * Spawn a child process and return a promise that resolves when it completes.\n *\n * SECURITY: This function uses array-based arguments which prevent command injection.\n * Arguments in the `args` array are passed directly to the OS without shell\n * interpretation. Shell metacharacters (;|&$()`) are treated as literal strings,\n * not as commands or operators. This is the PRIMARY SECURITY DEFENSE.\n *\n * Even when shell: true is used (on Windows for .cmd/.bat execution), the array-based\n * approach remains secure because Node.js properly escapes each argument before passing\n * to the shell.\n *\n * @param cmd - Command to execute (not user-controlled)\n * @param args - Array of arguments (safe even with user input due to array-based passing)\n * @param options - Spawn options\n * @param extra - Extra options for promise-spawn\n *\n * @example\n * // \u2714 DO THIS - Array-based arguments\n * spawn('git', ['commit', '-m', userMessage])\n * // Each argument is properly escaped, even if userMessage = \"foo; rm -rf /\"\n *\n * @example\n * // \u2716 NEVER DO THIS - String concatenation\n * spawn(`git commit -m \"${userMessage}\"`, { shell: true })\n * // Vulnerable to injection if userMessage = '\"; rm -rf / #'\n */\nexport function spawn(\n cmd: string,\n args?: string[] | readonly string[],\n options?: SpawnOptions | undefined,\n extra?: SpawnExtra | undefined,\n): SpawnResult {\n // Windows cmd.exe command resolution for .cmd/.bat/.ps1 files:\n //\n // When shell: true is used on Windows with script files (.cmd, .bat, .ps1),\n // cmd.exe can have issues executing full paths. The solution is to use just\n // the command basename without extension and let cmd.exe find it via PATH.\n //\n // How cmd.exe resolves commands:\n // 1. Searches current directory first\n // 2. Then searches each directory in PATH environment variable\n // 3. For each directory, tries extensions from PATHEXT (.COM, .EXE, .BAT, .CMD, etc.)\n // 4. Executes the first match found\n //\n // Example: Given 'C:\\pnpm\\pnpm.cmd' with shell: true\n // 1. Extract basename without extension: 'pnpm'\n // 2. cmd.exe searches PATH directories for 'pnpm'\n // 3. PATHEXT causes it to try 'pnpm.com', 'pnpm.exe', 'pnpm.bat', 'pnpm.cmd', etc.\n // 4. Finds and executes 'C:\\pnpm\\pnpm.cmd'\n //\n // This approach is consistent with how other tools handle Windows execution:\n // - npm's promise-spawn: uses which.sync() to find commands in PATH\n // - cross-spawn: spawns cmd.exe with escaped arguments\n // - execa: uses cross-spawn under the hood for Windows support\n //\n // See: https://github.com/nodejs/node/issues/3675\n const shell = getOwn(options, 'shell')\n // Inline WIN32 constant for coverage mode compatibility\n const WIN32 = process.platform === 'win32'\n let actualCmd = cmd\n if (WIN32 && shell && windowsScriptExtRegExp.test(actualCmd)) {\n const path = getPath()\n // Extract just the command name without path and extension.\n actualCmd = path.basename(actualCmd, path.extname(actualCmd))\n }\n const {\n spinner: optionsSpinner = spinner,\n stripAnsi: shouldStripAnsi = true,\n ...spawnOptions\n } = { __proto__: null, ...options } as SpawnOptions\n const spinnerInstance = optionsSpinner\n const { env, stdio, stdioString = true } = spawnOptions\n // The stdio option can be a string or an array.\n // https://nodejs.org/api/child_process.html#optionsstdio\n const wasSpinning = !!spinnerInstance?.isSpinning\n const shouldStopSpinner =\n wasSpinning && !isStdioType(stdio, 'ignore') && !isStdioType(stdio, 'pipe')\n const shouldRestartSpinner = shouldStopSpinner\n if (shouldStopSpinner) {\n spinnerInstance.stop()\n }\n const npmCliPromiseSpawn = getNpmcliPromiseSpawn()\n // Use __proto__: null to prevent prototype pollution when passing to\n // third-party code, Node.js built-ins, or JavaScript built-in methods.\n // https://github.com/npm/promise-spawn\n // https://github.com/nodejs/node/blob/v24.0.1/lib/child_process.js#L674-L678\n const promiseSpawnOpts = {\n __proto__: null,\n cwd: typeof spawnOptions.cwd === 'string' ? spawnOptions.cwd : undefined,\n env: {\n __proto__: null,\n ...process.env,\n ...env,\n } as unknown as NodeJS.ProcessEnv,\n signal: abortSignal,\n stdio: spawnOptions.stdio,\n stdioString,\n shell: spawnOptions.shell,\n timeout: spawnOptions.timeout,\n uid: spawnOptions.uid,\n gid: spawnOptions.gid,\n } as unknown as PromiseSpawnOptions\n const spawnPromise = npmCliPromiseSpawn(\n actualCmd,\n args ? [...args] : [],\n promiseSpawnOpts as Parameters<typeof npmCliPromiseSpawn>[2],\n extra,\n )\n const oldSpawnPromise = spawnPromise\n let newSpawnPromise: PromiseSpawnResult\n if (shouldStripAnsi && stdioString) {\n newSpawnPromise = spawnPromise\n .then(result => {\n const strippedResult = stripAnsiFromSpawnResult(result)\n // Add exitCode as an alias for code.\n if ('code' in (strippedResult as { code?: number })) {\n ;(strippedResult as { code: number; exitCode: number }).exitCode = (\n strippedResult as { code: number }\n ).code\n }\n return strippedResult\n })\n .catch(error => {\n throw stripAnsiFromSpawnResult(error)\n }) as PromiseSpawnResult\n } else {\n newSpawnPromise = spawnPromise.then(result => {\n // Add exitCode as an alias for code.\n if ('code' in result) {\n const res = result as typeof result & { exitCode: number }\n res.exitCode = result.code\n return res\n }\n return result\n }) as PromiseSpawnResult\n }\n if (shouldRestartSpinner) {\n newSpawnPromise = newSpawnPromise.finally(() => {\n spinnerInstance.start()\n }) as PromiseSpawnResult\n }\n // Copy process and stdin properties from original promise\n ;(newSpawnPromise as unknown as PromiseSpawnResult).process =\n oldSpawnPromise.process\n ;(newSpawnPromise as unknown as PromiseSpawnResult).stdin = (\n oldSpawnPromise as unknown as PromiseSpawnResult\n ).stdin\n return newSpawnPromise as SpawnResult\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Synchronously spawn a child process.\n */\nexport type SpawnSyncOptions = Omit<SpawnOptions, 'spinner'>\nexport function spawnSync(\n cmd: string,\n args?: string[] | readonly string[],\n options?: SpawnSyncOptions | undefined,\n): SpawnSyncReturns<string | Buffer> {\n // Windows cmd.exe command resolution for .cmd/.bat/.ps1 files:\n // See spawn() function above for detailed explanation of this approach.\n const shell = getOwn(options, 'shell')\n // Inline WIN32 constant for coverage mode compatibility\n const WIN32 = process.platform === 'win32'\n let actualCmd = cmd\n if (WIN32 && shell && windowsScriptExtRegExp.test(actualCmd)) {\n const path = getPath()\n // Extract just the command name without path and extension.\n actualCmd = path.basename(actualCmd, path.extname(actualCmd))\n }\n const { stripAnsi: shouldStripAnsi = true, ...rawSpawnOptions } = {\n __proto__: null,\n ...options,\n } as SpawnSyncOptions\n const { stdioString: rawStdioString = true } = rawSpawnOptions\n const rawEncoding = rawStdioString ? 'utf8' : 'buffer'\n const spawnOptions = {\n encoding: rawEncoding,\n ...rawSpawnOptions,\n } as NodeSpawnOptions & { encoding: BufferEncoding | 'buffer' }\n const stdioString = spawnOptions.encoding !== 'buffer'\n const result = getChildProcess().spawnSync(actualCmd, args, spawnOptions)\n if (stdioString) {\n const { stderr, stdout } = result\n if (stdout) {\n result.stdout = stdout.toString().trim()\n }\n if (stderr) {\n result.stderr = stderr.toString().trim()\n }\n }\n return (\n shouldStripAnsi && stdioString ?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AAA,IAChE,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,EAAE,aAAa,iBAAiB,KAAK,IAAI;AAC/C,QAAM,cAAc,iBAAiB,SAAS;AAC9C,QAAM,eAAe;AAAA,IACnB,UAAU;AAAA,IACV,GAAG;AAAA,EACL;AACA,QAAM,cAAc,aAAa,aAAa;AAC9C,QAAM,UAAS,gCAAgB,GAAE,UAAU,WAAW,MAAM,YAAY;AACxE,MAAI,aAAa;AACf,UAAM,EAAE,QAAQ,OAAO,IAAI;AAC3B,QAAI,QAAQ;AACV,aAAO,SAAS,OAAO,SAAS,EAAE,KAAK;AAAA,IACzC;AACA,QAAI,QAAQ;AACV,aAAO,SAAS,OAAO,SAAS,EAAE,KAAK;AAAA,IACzC;AAAA,EACF;AACA,SACE,mBAAmB,cAAc,yCAAyB,MAAM,IAAI;AAExE;",
4
+ "sourcesContent": ["/**\n * @fileoverview Child process spawning utilities with cross-platform support.\n * Provides enhanced spawn functionality with stdio handling and error management.\n *\n * SECURITY: Array-Based Arguments Prevent Command Injection\n *\n * This module uses array-based arguments for all command execution, which is the\n * PRIMARY DEFENSE against command injection attacks. When you pass arguments as\n * an array to spawn():\n *\n * spawn('npx', ['sfw', tool, ...args], { shell: true })\n *\n * Node.js handles escaping automatically. Each argument is passed directly to the\n * OS without shell interpretation. Shell metacharacters like ; | & $ ( ) ` are\n * treated as LITERAL STRINGS, not as commands. This approach is secure even when\n * shell: true is used on Windows for .cmd/.bat file resolution.\n *\n * UNSAFE ALTERNATIVE (not used in this codebase):\n * spawn(`npx sfw ${tool} ${args.join(' ')}`, { shell: true }) // \u2716 VULNERABLE\n *\n * String concatenation allows injection. For example, if tool = \"foo; rm -rf /\",\n * the shell would execute both commands. Array-based arguments prevent this.\n *\n * References:\n * - https://nodejs.org/api/child_process.html#child_processspawncommand-args-options\n * - https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html\n */\n\nimport { getAbortSignal, getSpinner } from '#constants/process'\n\nimport { isArray } from './arrays'\n\nconst abortSignal = getAbortSignal()\nconst spinner = getSpinner()\n\nimport { getOwn, hasOwn } from './objects'\nimport { stripAnsi } from './strings'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\nconst windowsScriptExtRegExp = /\\.(?:cmd|bat|ps1)$/i\n\nlet _child_process: typeof import('node:child_process') | undefined\n/**\n * Lazily load the child_process module.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getChildProcess() {\n if (_child_process === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _child_process = /*@__PURE__*/ require('node:child_process')\n }\n return _child_process as typeof import('node:child_process')\n}\n\n// Type for promise-spawn options.\nexport type PromiseSpawnOptions = {\n cwd?: string | undefined\n stdioString?: boolean | undefined\n stdio?: StdioType | undefined\n env?: NodeJS.ProcessEnv | undefined\n shell?: boolean | string | undefined\n signal?: AbortSignal | undefined\n timeout?: number | undefined\n uid?: number | undefined\n gid?: number | undefined\n}\n\n// Type for promise-spawn result.\nexport type PromiseSpawnResult = Promise<{\n cmd: string\n args: string[] | readonly string[]\n code: number\n signal: NodeJS.Signals | null\n stdout: string | Buffer\n stderr: string | Buffer\n}> & {\n process: ChildProcessType\n stdin: WritableStreamType | null\n}\n\nlet _npmCliPromiseSpawn:\n | ((\n cmd: string,\n args: string[],\n options?: PromiseSpawnOptions | undefined,\n extra?: SpawnExtra | undefined,\n ) => PromiseSpawnResult)\n | undefined\n/**\n * Lazily load the promise-spawn module for async process spawning.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getNpmcliPromiseSpawn() {\n if (_npmCliPromiseSpawn === undefined) {\n _npmCliPromiseSpawn = /*@__PURE__*/ require('./external/@npmcli/promise-spawn')\n }\n return _npmCliPromiseSpawn as unknown as typeof import('@npmcli/promise-spawn')\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path as typeof import('node:path')\n}\n\n/**\n * Check if a value is a spawn error.\n */\nexport type SpawnError = {\n args: string[]\n cmd: string\n code: number\n name: string\n message: string\n signal: NodeJS.Signals | null\n stack: string\n stderr: string | Buffer\n stdout: string | Buffer\n}\n\nexport type SpawnErrorWithOutputString = SpawnError & {\n stdout: string\n stderr: string\n}\n\nexport type SpawnErrorWithOutputBuffer = SpawnError & {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport type SpawnExtra = Record<string, unknown>\n\nexport type IOType = 'pipe' | 'ignore' | 'inherit' | 'overlapped'\nexport type StdioType = IOType | 'ipc' | Array<IOType | 'ipc'>\n\nexport interface SpawnSyncReturns<T> {\n pid: number\n output: Array<T | null>\n stdout: T\n stderr: T\n status: number | null\n signal: NodeJS.Signals | null\n error?: Error | undefined\n}\n\n/**\n * Check if a value is a spawn error with expected properties.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isSpawnError(value: unknown): value is SpawnError {\n if (value === null || typeof value !== 'object') {\n return false\n }\n // Check for spawn-specific error properties.\n const err = value as Record<string, unknown>\n return (\n (hasOwn(err, 'code') && typeof err['code'] !== 'undefined') ||\n (hasOwn(err, 'errno') && typeof err['errno'] !== 'undefined') ||\n (hasOwn(err, 'syscall') && typeof err['syscall'] === 'string')\n )\n}\n\n/**\n * Check if stdio configuration matches a specific type.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isStdioType(\n stdio: string | string[],\n type?: StdioType | undefined,\n): boolean {\n // If called with one argument, check if it's a valid stdio type.\n // biome-ignore lint/complexity/noArguments: Function overload detection for single vs two-arg calls.\n if (arguments.length === 1) {\n const validTypes = ['pipe', 'ignore', 'inherit', 'overlapped']\n return typeof stdio === 'string' && validTypes.includes(stdio)\n }\n // Original two-argument behavior.\n return (\n stdio === type ||\n ((stdio === null || stdio === undefined) && type === 'pipe') ||\n (isArray(stdio) &&\n stdio.length > 2 &&\n stdio[0] === type &&\n stdio[1] === type &&\n stdio[2] === type)\n )\n}\n\n/**\n * Strip ANSI escape codes from spawn result stdout and stderr.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction stripAnsiFromSpawnResult(result: unknown): unknown {\n const res = result as {\n stdout?: string | Buffer\n stderr?: string | Buffer\n }\n const { stderr, stdout } = res\n if (typeof stdout === 'string') {\n res.stdout = stripAnsi(stdout)\n }\n if (typeof stderr === 'string') {\n res.stderr = stripAnsi(stderr)\n }\n return res\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n// Duplicated from Node.js child_process.SpawnOptions\n// These are the options passed to child_process.spawn()\ninterface NodeSpawnOptions {\n cwd?: string | URL | undefined\n env?: NodeJS.ProcessEnv | undefined\n argv0?: string | undefined\n // biome-ignore lint/suspicious/noExplicitAny: Stdio can be complex union of types from Node.js.\n stdio?: any\n detached?: boolean | undefined\n uid?: number | undefined\n gid?: number | undefined\n serialization?: 'json' | 'advanced' | undefined\n shell?: boolean | string | undefined\n windowsVerbatimArguments?: boolean | undefined\n windowsHide?: boolean | undefined\n signal?: AbortSignal | undefined\n timeout?: number | undefined\n killSignal?: NodeJS.Signals | number | undefined\n}\n\n// Duplicated from Node.js child_process.ChildProcess\n// This represents a spawned child process\ninterface ChildProcessType {\n stdin: NodeJS.WritableStream | null\n stdout: NodeJS.ReadableStream | null\n stderr: NodeJS.ReadableStream | null\n // biome-ignore lint/suspicious/noExplicitAny: IPC channel type from Node.js.\n readonly channel?: any\n readonly stdio: [\n NodeJS.WritableStream | null,\n NodeJS.ReadableStream | null,\n NodeJS.ReadableStream | null,\n NodeJS.ReadableStream | NodeJS.WritableStream | null | undefined,\n NodeJS.ReadableStream | NodeJS.WritableStream | null | undefined,\n ]\n readonly killed: boolean\n readonly pid?: number | undefined\n readonly connected: boolean\n readonly exitCode: number | null\n readonly signalCode: NodeJS.Signals | null\n readonly spawnargs: string[]\n readonly spawnfile: string\n kill(signal?: NodeJS.Signals | number): boolean\n // biome-ignore lint/suspicious/noExplicitAny: IPC message type from Node.js.\n send(message: any, callback?: (error: Error | null) => void): boolean\n send(\n // biome-ignore lint/suspicious/noExplicitAny: IPC message and handle types from Node.js.\n message: any,\n // biome-ignore lint/suspicious/noExplicitAny: IPC message and handle types from Node.js.\n sendHandle?: any | undefined,\n callback?: (error: Error | null) => void,\n ): boolean\n send(\n // biome-ignore lint/suspicious/noExplicitAny: IPC message, handle, and options types from Node.js.\n message: any,\n // biome-ignore lint/suspicious/noExplicitAny: IPC message, handle, and options types from Node.js.\n sendHandle?: any | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: IPC message, handle, and options types from Node.js.\n options?: any | undefined,\n callback?: (error: Error | null) => void,\n ): boolean\n disconnect(): void\n unref(): void\n ref(): void\n}\n\n// Duplicated from Node.js stream.Writable\ninterface WritableStreamType {\n writable: boolean\n writableEnded: boolean\n writableFinished: boolean\n writableHighWaterMark: number\n writableLength: number\n writableObjectMode: boolean\n writableCorked: number\n destroyed: boolean\n write(\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n chunk: any,\n encoding?: BufferEncoding | undefined,\n callback?: (error?: Error | null) => void,\n ): boolean\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n write(chunk: any, callback?: (error?: Error | null) => void): boolean\n end(cb?: () => void): this\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n end(chunk: any, cb?: () => void): this\n // biome-ignore lint/suspicious/noExplicitAny: Stream chunk can be any type.\n end(chunk: any, encoding?: BufferEncoding | undefined, cb?: () => void): this\n cork(): void\n uncork(): void\n destroy(error?: Error | undefined): this\n}\n\n/**\n * Spawn a child process with enhanced error handling and output capture.\n */\nexport type SpawnOptions = import('./objects').Remap<\n NodeSpawnOptions & {\n spinner?: import('./spinner').Spinner | undefined\n stdioString?: boolean\n stripAnsi?: boolean\n }\n>\nexport type SpawnResult = PromiseSpawnResult\nexport type SpawnStdioResult = {\n cmd: string\n args: string[] | readonly string[]\n code: number\n signal: NodeJS.Signals | null\n stdout: string | Buffer\n stderr: string | Buffer\n}\n\n/**\n * Spawn a child process and return a promise that resolves when it completes.\n *\n * SECURITY: This function uses array-based arguments which prevent command injection.\n * Arguments in the `args` array are passed directly to the OS without shell\n * interpretation. Shell metacharacters (;|&$()`) are treated as literal strings,\n * not as commands or operators. This is the PRIMARY SECURITY DEFENSE.\n *\n * Even when shell: true is used (on Windows for .cmd/.bat execution), the array-based\n * approach remains secure because Node.js properly escapes each argument before passing\n * to the shell.\n *\n * @param cmd - Command to execute (not user-controlled)\n * @param args - Array of arguments (safe even with user input due to array-based passing)\n * @param options - Spawn options\n * @param extra - Extra options for promise-spawn\n *\n * @example\n * // \u2714 DO THIS - Array-based arguments\n * spawn('git', ['commit', '-m', userMessage])\n * // Each argument is properly escaped, even if userMessage = \"foo; rm -rf /\"\n *\n * @example\n * // \u2716 NEVER DO THIS - String concatenation\n * spawn(`git commit -m \"${userMessage}\"`, { shell: true })\n * // Vulnerable to injection if userMessage = '\"; rm -rf / #'\n */\nexport function spawn(\n cmd: string,\n args?: string[] | readonly string[],\n options?: SpawnOptions | undefined,\n extra?: SpawnExtra | undefined,\n): SpawnResult {\n // Windows cmd.exe command resolution for .cmd/.bat/.ps1 files:\n //\n // When shell: true is used on Windows with script files (.cmd, .bat, .ps1),\n // cmd.exe can have issues executing full paths. The solution is to use just\n // the command basename without extension and let cmd.exe find it via PATH.\n //\n // How cmd.exe resolves commands:\n // 1. Searches current directory first\n // 2. Then searches each directory in PATH environment variable\n // 3. For each directory, tries extensions from PATHEXT (.COM, .EXE, .BAT, .CMD, etc.)\n // 4. Executes the first match found\n //\n // Example: Given 'C:\\pnpm\\pnpm.cmd' with shell: true\n // 1. Extract basename without extension: 'pnpm'\n // 2. cmd.exe searches PATH directories for 'pnpm'\n // 3. PATHEXT causes it to try 'pnpm.com', 'pnpm.exe', 'pnpm.bat', 'pnpm.cmd', etc.\n // 4. Finds and executes 'C:\\pnpm\\pnpm.cmd'\n //\n // This approach is consistent with how other tools handle Windows execution:\n // - npm's promise-spawn: uses which.sync() to find commands in PATH\n // - cross-spawn: spawns cmd.exe with escaped arguments\n // - execa: uses cross-spawn under the hood for Windows support\n //\n // See: https://github.com/nodejs/node/issues/3675\n const shell = getOwn(options, 'shell')\n // Inline WIN32 constant for coverage mode compatibility\n const WIN32 = process.platform === 'win32'\n let actualCmd = cmd\n if (WIN32 && shell && windowsScriptExtRegExp.test(actualCmd)) {\n const path = getPath()\n // Extract just the command name without path and extension.\n actualCmd = path.basename(actualCmd, path.extname(actualCmd))\n }\n const {\n spinner: optionsSpinner = spinner,\n stripAnsi: shouldStripAnsi = true,\n ...spawnOptions\n } = { __proto__: null, ...options } as SpawnOptions\n const spinnerInstance = optionsSpinner\n const { env, stdio, stdioString = true } = spawnOptions\n // The stdio option can be a string or an array.\n // https://nodejs.org/api/child_process.html#optionsstdio\n const wasSpinning = !!spinnerInstance?.isSpinning\n const shouldStopSpinner =\n wasSpinning && !isStdioType(stdio, 'ignore') && !isStdioType(stdio, 'pipe')\n const shouldRestartSpinner = shouldStopSpinner\n if (shouldStopSpinner) {\n spinnerInstance.stop()\n }\n const npmCliPromiseSpawn = getNpmcliPromiseSpawn()\n // Use __proto__: null to prevent prototype pollution when passing to\n // third-party code, Node.js built-ins, or JavaScript built-in methods.\n // https://github.com/npm/promise-spawn\n // https://github.com/nodejs/node/blob/v24.0.1/lib/child_process.js#L674-L678\n const promiseSpawnOpts = {\n __proto__: null,\n cwd: typeof spawnOptions.cwd === 'string' ? spawnOptions.cwd : undefined,\n env: {\n __proto__: null,\n ...process.env,\n ...env,\n } as unknown as NodeJS.ProcessEnv,\n signal: abortSignal,\n stdio: spawnOptions.stdio,\n stdioString,\n shell: spawnOptions.shell,\n timeout: spawnOptions.timeout,\n uid: spawnOptions.uid,\n gid: spawnOptions.gid,\n } as unknown as PromiseSpawnOptions\n const spawnPromise = npmCliPromiseSpawn(\n actualCmd,\n args ? [...args] : [],\n promiseSpawnOpts as Parameters<typeof npmCliPromiseSpawn>[2],\n extra,\n )\n const oldSpawnPromise = spawnPromise\n let newSpawnPromise: PromiseSpawnResult\n if (shouldStripAnsi && stdioString) {\n newSpawnPromise = spawnPromise\n .then(result => {\n const strippedResult = stripAnsiFromSpawnResult(result)\n // Add exitCode as an alias for code.\n if ('code' in (strippedResult as { code?: number })) {\n ;(strippedResult as { code: number; exitCode: number }).exitCode = (\n strippedResult as { code: number }\n ).code\n }\n return strippedResult\n })\n .catch(error => {\n throw stripAnsiFromSpawnResult(error)\n }) as PromiseSpawnResult\n } else {\n newSpawnPromise = spawnPromise.then(result => {\n // Add exitCode as an alias for code.\n if ('code' in result) {\n const res = result as typeof result & { exitCode: number }\n res.exitCode = result.code\n return res\n }\n return result\n }) as PromiseSpawnResult\n }\n if (shouldRestartSpinner) {\n newSpawnPromise = newSpawnPromise.finally(() => {\n spinnerInstance.start()\n }) as PromiseSpawnResult\n }\n // Copy process and stdin properties from original promise\n ;(newSpawnPromise as unknown as PromiseSpawnResult).process =\n oldSpawnPromise.process\n ;(newSpawnPromise as unknown as PromiseSpawnResult).stdin = (\n oldSpawnPromise as unknown as PromiseSpawnResult\n ).stdin\n return newSpawnPromise as SpawnResult\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Synchronously spawn a child process.\n */\nexport type SpawnSyncOptions = Omit<SpawnOptions, 'spinner'>\nexport function spawnSync(\n cmd: string,\n args?: string[] | readonly string[],\n options?: SpawnSyncOptions | undefined,\n): SpawnSyncReturns<string | Buffer> {\n // Windows cmd.exe command resolution for .cmd/.bat/.ps1 files:\n // See spawn() function above for detailed explanation of this approach.\n const shell = getOwn(options, 'shell')\n // Inline WIN32 constant for coverage mode compatibility\n const WIN32 = process.platform === 'win32'\n let actualCmd = cmd\n if (WIN32 && shell && windowsScriptExtRegExp.test(actualCmd)) {\n const path = getPath()\n // Extract just the command name without path and extension.\n actualCmd = path.basename(actualCmd, path.extname(actualCmd))\n }\n const { stripAnsi: shouldStripAnsi = true, ...rawSpawnOptions } = {\n __proto__: null,\n ...options,\n } as SpawnSyncOptions\n const { stdioString: rawStdioString = true } = rawSpawnOptions\n const rawEncoding = rawStdioString ? 'utf8' : 'buffer'\n const spawnOptions = {\n encoding: rawEncoding,\n ...rawSpawnOptions,\n } as NodeSpawnOptions & { encoding: BufferEncoding | 'buffer' }\n const stdioString = spawnOptions.encoding !== 'buffer'\n const result = getChildProcess().spawnSync(actualCmd, args, spawnOptions)\n if (stdioString) {\n const { stderr, stdout } = result\n if (stdout) {\n result.stdout = stdout.toString().trim()\n }\n if (stderr) {\n result.stderr = stderr.toString().trim()\n }\n }\n return (\n shouldStripAnsi && stdioString ? stripAnsiFromSpawnResult(result) : result\n ) as SpawnSyncReturns<string | Buffer>\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,qBAA2C;AAE3C,oBAAwB;AAKxB,qBAA+B;AAC/B,qBAA0B;AAJ1B,MAAM,kBAAc,+BAAe;AACnC,MAAM,cAAU,2BAAW;AAQ3B,MAAM,yBAAyB;AAE/B,IAAI;AAAA;AAKJ,SAAS,kBAAkB;AACzB,MAAI,mBAAmB,QAAW;AAGhC,qBAA+B,QAAQ,oBAAoB;AAAA,EAC7D;AACA,SAAO;AACT;AA4BA,IAAI;AAAA;AAYJ,SAAS,wBAAwB;AAC/B,MAAI,wBAAwB,QAAW;AACrC,0BAAoC,QAAQ,kCAAkC;AAAA,EAChF;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AACA,SAAO;AACT;AAAA;AA8CO,SAAS,aAAa,OAAqC;AAChE,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO;AAAA,EACT;AAEA,QAAM,MAAM;AAC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AAgB,MAAM;AAAA,IACxB,CAAC;AAAA,EACH;AAEA;AAAC,EAAC,gBAAkD,UAClD,gBAAgB;AACjB,EAAC,gBAAkD,QAClD,gBACA;AACF,SAAO;AACT;AAOO,SAAS,UACd,KACA,MACA,SACmC;AAGnC,QAAM,YAAQ,uBAAO,SAAS,OAAO;AAErC,QAAM,QAAQ,QAAQ,aAAa;AACnC,MAAI,YAAY;AAChB,MAAI,SAAS,SAAS,uBAAuB,KAAK,SAAS,GAAG;AAC5D,UAAM,OAAO,wBAAQ;AAErB,gBAAY,KAAK,SAAS,WAAW,KAAK,QAAQ,SAAS,CAAC;AAAA,EAC9D;AACA,QAAM,EAAE,WAAW,kBAAkB,MAAM,GAAG,gBAAgB,IAAI;AAAA,IAChE,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,EAAE,aAAa,iBAAiB,KAAK,IAAI;AAC/C,QAAM,cAAc,iBAAiB,SAAS;AAC9C,QAAM,eAAe;AAAA,IACnB,UAAU;AAAA,IACV,GAAG;AAAA,EACL;AACA,QAAM,cAAc,aAAa,aAAa;AAC9C,QAAM,UAAS,gCAAgB,GAAE,UAAU,WAAW,MAAM,YAAY;AACxE,MAAI,aAAa;AACf,UAAM,EAAE,QAAQ,OAAO,IAAI;AAC3B,QAAI,QAAQ;AACV,aAAO,SAAS,OAAO,SAAS,EAAE,KAAK;AAAA,IACzC;AACA,QAAI,QAAQ;AACV,aAAO,SAAS,OAAO,SAAS,EAAE,KAAK;AAAA,IACzC;AAAA,EACF;AACA,SACE,mBAAmB,cAAc,yCAAyB,MAAM,IAAI;AAExE;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/spinner.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview CLI spinner utilities for long-running operations.\n * Provides animated progress indicators with CI environment detection.\n */\n\nimport type { Writable } from 'node:stream'\n\n// Note: getAbortSignal is imported lazily to avoid circular dependencies.\nimport { CI } from '#env/ci'\nimport { generateSocketSpinnerFrames } from './effects/pulse-frames'\nimport type {\n ShimmerColorGradient,\n ShimmerConfig,\n ShimmerDirection,\n ShimmerState,\n} from './effects/text-shimmer'\nimport { applyShimmer, COLOR_INHERIT, DIR_LTR } from './effects/text-shimmer'\nimport yoctoSpinner from './external/@socketregistry/yocto-spinner'\nimport { hasOwn } from './objects'\nimport { isBlankString, stringWidth } from './strings'\n\nexport type ColorName =\n | 'black'\n | 'blue'\n | 'blueBright'\n | 'cyan'\n | 'cyanBright'\n | 'gray'\n | 'green'\n | 'greenBright'\n | 'magenta'\n | 'magentaBright'\n | 'red'\n | 'redBright'\n | 'white'\n | 'whiteBright'\n | 'yellow'\n | 'yellowBright'\n\nexport type ColorInherit = 'inherit'\n\nexport type ColorRgb = readonly [number, number, number]\n\nexport type ColorValue = ColorName | ColorRgb\n\nexport type SymbolType = 'fail' | 'info' | 'success' | 'warn'\n\n// Map color names to RGB values.\nconst colorToRgb: Record<ColorName, ColorRgb> = {\n __proto__: null,\n black: [0, 0, 0],\n blue: [0, 0, 255],\n blueBright: [100, 149, 237],\n cyan: [0, 255, 255],\n cyanBright: [0, 255, 255],\n gray: [128, 128, 128],\n green: [0, 128, 0],\n greenBright: [0, 255, 0],\n magenta: [255, 0, 255],\n magentaBright: [255, 105, 180],\n red: [255, 0, 0],\n redBright: [255, 69, 0],\n white: [255, 255, 255],\n whiteBright: [255, 255, 255],\n yellow: [255, 255, 0],\n yellowBright: [255, 255, 153],\n} as Record<ColorName, ColorRgb>\n\n/**\n * Check if value is RGB tuple.\n */\nfunction isRgbTuple(value: ColorValue): value is ColorRgb {\n return Array.isArray(value)\n}\n\n/**\n * Convert ColorValue to RGB tuple.\n */\nfunction toRgb(color: ColorValue): ColorRgb {\n if (isRgbTuple(color)) {\n return color\n }\n return colorToRgb[color]\n}\n\nexport type ProgressInfo = {\n current: number\n total: number\n unit?: string | undefined\n}\n\nexport type ShimmerInfo = ShimmerState & {\n color: ColorInherit | ColorValue | ShimmerColorGradient\n}\n\nexport type Spinner = {\n color: ColorRgb\n spinner: SpinnerStyle\n\n get isSpinning(): boolean\n\n clear(): Spinner\n debug(text?: string | undefined, ...extras: unknown[]): Spinner\n debugAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n error(text?: string | undefined, ...extras: unknown[]): Spinner\n errorAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n fail(text?: string | undefined, ...extras: unknown[]): Spinner\n failAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n // text property returns a method via _textMethod override\n text(value: string): Spinner\n text(): string\n\n indent(spaces?: number | undefined): Spinner\n dedent(spaces?: number | undefined): Spinner\n\n info(text?: string | undefined, ...extras: unknown[]): Spinner\n infoAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n log(text?: string | undefined, ...extras: unknown[]): Spinner\n logAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n start(text?: string | undefined): Spinner\n stop(text?: string | undefined): Spinner\n stopAndPersist(text?: string | undefined): Spinner\n\n step(text?: string | undefined, ...extras: unknown[]): Spinner\n substep(text?: string | undefined, ...extras: unknown[]): Spinner\n\n success(text?: string | undefined, ...extras: unknown[]): Spinner\n successAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n done(text?: string | undefined, ...extras: unknown[]): Spinner\n doneAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n progress(current: number, total: number, unit?: string | undefined): Spinner\n progressStep(amount?: number): Spinner\n\n shimmer(enabled: boolean): Spinner\n shimmer(config: Partial<ShimmerConfig> | ShimmerDirection): Spinner\n\n warn(text?: string | undefined, ...extras: unknown[]): Spinner\n warnAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n}\n\nexport type SpinnerOptions = {\n readonly color?: ColorValue | undefined\n readonly shimmer?: ShimmerConfig | ShimmerDirection | undefined\n readonly spinner?: SpinnerStyle | undefined\n readonly signal?: AbortSignal | undefined\n readonly stream?: Writable | undefined\n readonly text?: string | undefined\n}\n\nexport type SpinnerStyle = {\n readonly frames: string[]\n readonly interval?: number | undefined\n}\n\nexport const ciSpinner: SpinnerStyle = {\n frames: [''],\n interval: 2_147_483_647,\n}\n\nfunction desc(value: unknown) {\n return {\n __proto__: null,\n configurable: true,\n value,\n writable: true,\n }\n}\n\nfunction normalizeText(value: unknown) {\n return typeof value === 'string' ? value.trimStart() : ''\n}\n\nfunction formatProgress(progress: ProgressInfo): string {\n const { current, total, unit } = progress\n const percentage = Math.round((current / total) * 100)\n const bar = renderProgressBar(percentage)\n const count = unit ? `${current}/${total} ${unit}` : `${current}/${total}`\n return `${bar} ${percentage}% (${count})`\n}\n\nfunction renderProgressBar(percentage: number, width: number = 20): string {\n const filled = Math.round((percentage / 100) * width)\n const empty = width - filled\n const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(empty)\n // Use cyan color for the progress bar\n const colors = /*@__PURE__*/ require('../external/yoctocolors-cjs')\n return colors.cyan(bar)\n}\n\nlet _cliSpinners: Record<string, SpinnerStyle> | undefined\n\n/**\n * Get available CLI spinner styles or a specific style by name.\n * Extends the standard cli-spinners collection with Socket custom spinners.\n *\n * @see https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json\n *\n * Custom spinners:\n * - `socket` (default): Socket pulse animation with sparkles and lightning\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function getCliSpinners(\n styleName?: string | undefined,\n): SpinnerStyle | Record<string, SpinnerStyle> | undefined {\n if (_cliSpinners === undefined) {\n // biome-ignore lint/suspicious/noExplicitAny: Accessing internal yocto-spinner constructor.\n const YoctoCtor = yoctoSpinner as any\n // Get the YoctoSpinner class to access static properties.\n const tempInstance = YoctoCtor({})\n // biome-ignore lint/suspicious/noExplicitAny: Accessing internal yocto-spinner class.\n const YoctoSpinnerClass = tempInstance.constructor as any\n // Extend the standard cli-spinners collection with Socket custom spinners.\n _cliSpinners = {\n __proto__: null,\n ...YoctoSpinnerClass.spinners,\n socket: generateSocketSpinnerFrames(),\n }\n }\n if (typeof styleName === 'string' && _cliSpinners) {\n return hasOwn(_cliSpinners, styleName) ? _cliSpinners[styleName] : undefined\n }\n return _cliSpinners\n}\n\nlet _Spinner: {\n new (options?: SpinnerOptions | undefined): Spinner\n}\nlet _defaultSpinner: SpinnerStyle | undefined\n\n/**\n * Create a spinner instance for displaying loading indicators.\n *\n * AUTO-CLEAR BEHAVIOR:\n * - All *AndStop() methods AUTO-CLEAR the spinner line via yocto-spinner.stop()\n * Examples: doneAndStop(), successAndStop(), failAndStop(), etc.\n *\n * - Methods WITHOUT \"AndStop\" do NOT clear (spinner keeps spinning)\n * Examples: done(), success(), fail(), etc.\n *\n * STREAM USAGE:\n * - Spinner animation: stderr (yocto-spinner default)\n * - Status methods (done, success, fail, info, warn, step, substep): stderr\n * - Data methods (log): stdout\n *\n * COMPARISON WITH LOGGER:\n * - logger.done() does NOT auto-clear (requires manual logger.clearLine())\n * - spinner.doneAndStop() DOES auto-clear (built into yocto-spinner.stop())\n * - Pattern: logger.clearLine().done() vs spinner.doneAndStop()\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function Spinner(options?: SpinnerOptions | undefined): Spinner {\n if (_Spinner === undefined) {\n // biome-ignore lint/suspicious/noExplicitAny: Accessing internal yocto-spinner constructor.\n const YoctoCtor = yoctoSpinner as any\n // Get the actual YoctoSpinner class from an instance\n const tempInstance = YoctoCtor({})\n const YoctoSpinnerClass = tempInstance.constructor\n\n /*@__PURE__*/\n // biome-ignore lint/suspicious/noExplicitAny: Extending yocto-spinner class.\n _Spinner = class SpinnerClass extends (YoctoSpinnerClass as any) {\n declare isSpinning: boolean\n #baseText: string = ''\n #indentation: string = ''\n #progress?: ProgressInfo | undefined\n #shimmer?: ShimmerInfo | undefined\n #shimmerSavedConfig?: ShimmerInfo | undefined\n\n constructor(options?: SpinnerOptions | undefined) {\n const opts = { __proto__: null, ...options } as SpinnerOptions\n\n // Convert color option to RGB (default to Socket purple).\n const spinnerColor = opts.color ?? ([140, 82, 255] as const)\n\n // Validate RGB tuple if provided.\n if (\n isRgbTuple(spinnerColor) &&\n (spinnerColor.length !== 3 ||\n !spinnerColor.every(\n n => typeof n === 'number' && n >= 0 && n <= 255,\n ))\n ) {\n throw new TypeError(\n 'RGB color must be an array of 3 numbers between 0 and 255',\n )\n }\n\n const spinnerColorRgb = toRgb(spinnerColor)\n\n // Parse shimmer config - can be object or direction string.\n let shimmerInfo: ShimmerInfo | undefined\n if (opts.shimmer) {\n let shimmerDir: ShimmerDirection\n let shimmerColor:\n | ColorInherit\n | ColorValue\n | ShimmerColorGradient\n | undefined\n // Default: 0.33 steps per frame (~150ms per step).\n let shimmerSpeed: number = 1 / 3\n\n if (typeof opts.shimmer === 'string') {\n shimmerDir = opts.shimmer\n } else {\n const shimmerConfig = {\n __proto__: null,\n ...opts.shimmer,\n } as ShimmerConfig\n shimmerDir = shimmerConfig.dir ?? DIR_LTR\n shimmerColor = shimmerConfig.color ?? COLOR_INHERIT\n shimmerSpeed = shimmerConfig.speed ?? 1 / 3\n }\n\n // Create shimmer info with initial animation state:\n // - COLOR_INHERIT means use spinner color dynamically\n // - ColorValue (name or RGB tuple) is an explicit override color\n // - undefined color defaults to COLOR_INHERIT\n // - speed controls steps per frame (lower = slower, e.g., 0.33 = ~150ms per step)\n shimmerInfo = {\n __proto__: null,\n color: shimmerColor === undefined ? COLOR_INHERIT : shimmerColor,\n currentDir: DIR_LTR,\n mode: shimmerDir,\n speed: shimmerSpeed,\n step: 0,\n } as ShimmerInfo\n }\n\n // eslint-disable-next-line constructor-super\n super({\n signal: require('#constants/process').getAbortSignal(),\n ...opts,\n // Pass RGB color directly to yocto-spinner (it now supports RGB).\n color: spinnerColorRgb,\n // onRenderFrame callback provides full control over frame + text layout.\n // Calculates spacing based on frame width to prevent text jumping.\n onRenderFrame: (\n frame: string,\n text: string,\n applyColor: (text: string) => string,\n ) => {\n const width = stringWidth(frame)\n // Narrow frames (width 1) get 2 spaces, wide frames (width 2) get 1 space.\n // Total width is consistent: 3 characters (frame + spacing) before text.\n const spacing = width === 1 ? ' ' : ' '\n return frame ? `${applyColor(frame)}${spacing}${text}` : text\n },\n // onFrameUpdate callback is called by yocto-spinner whenever a frame advances.\n // This ensures shimmer updates are perfectly synchronized with animation beats.\n onFrameUpdate: shimmerInfo\n ? () => {\n // Update parent's text without triggering render.\n // Parent's #skipRender flag prevents nested render calls.\n // Only update if we have base text to avoid blank frames.\n if (this.#baseText) {\n super.text = this.#buildDisplayText()\n }\n }\n : undefined,\n })\n\n this.#shimmer = shimmerInfo\n this.#shimmerSavedConfig = shimmerInfo\n }\n\n // Override color getter to ensure it's always RGB.\n get color(): ColorRgb {\n const value = super.color\n return isRgbTuple(value) ? value : toRgb(value)\n }\n\n // Override color setter to always convert to RGB before passing to yocto-spinner.\n set color(value: ColorValue | ColorRgb) {\n super.color = isRgbTuple(value) ? value : toRgb(value)\n }\n\n /**\n * Apply a yocto-spinner method and update logger state.\n * Handles text normalization, extra arguments, and logger tracking.\n * @private\n */\n #apply(methodName: string, args: unknown[]) {\n let extras: unknown[]\n let text = args.at(0)\n if (typeof text === 'string') {\n extras = args.slice(1)\n } else {\n extras = args\n text = ''\n }\n const wasSpinning = this.isSpinning\n const normalized = normalizeText(text)\n super[methodName](normalized)\n const {\n incLogCallCountSymbol,\n lastWasBlankSymbol,\n logger,\n } = /*@__PURE__*/ require('./logger.js')\n if (methodName === 'stop') {\n if (wasSpinning && normalized) {\n logger[lastWasBlankSymbol](isBlankString(normalized))\n logger[incLogCallCountSymbol]()\n }\n } else {\n logger[lastWasBlankSymbol](false)\n logger[incLogCallCountSymbol]()\n }\n if (extras.length) {\n logger.log(...extras)\n logger[lastWasBlankSymbol](false)\n }\n return this\n }\n\n /**\n * Build the complete display text with progress, shimmer, and indentation.\n * Combines base text, progress bar, shimmer effects, and indentation.\n * @private\n */\n #buildDisplayText() {\n let displayText = this.#baseText\n\n if (this.#progress) {\n const progressText = formatProgress(this.#progress)\n displayText = displayText\n ? `${displayText} ${progressText}`\n : progressText\n }\n\n // Apply shimmer effect if enabled.\n if (displayText && this.#shimmer) {\n // If shimmer color is 'inherit', use current spinner color (getter ensures RGB).\n // Otherwise, check if it's a gradient (array of arrays) or single color.\n let shimmerColor: ColorRgb | ShimmerColorGradient\n if (this.#shimmer.color === COLOR_INHERIT) {\n shimmerColor = this.color\n } else if (Array.isArray(this.#shimmer.color[0])) {\n // It's a gradient - use as is.\n shimmerColor = this.#shimmer.color as ShimmerColorGradient\n } else {\n // It's a single color - convert to RGB.\n shimmerColor = toRgb(this.#shimmer.color as ColorValue)\n }\n\n displayText = applyShimmer(displayText, this.#shimmer, {\n color: shimmerColor,\n direction: this.#shimmer.mode,\n })\n }\n\n // Apply indentation\n if (this.#indentation && displayText) {\n displayText = this.#indentation + displayText\n }\n\n return displayText\n }\n\n /**\n * Show a status message without stopping the spinner.\n * Outputs the symbol and message to stderr, then continues spinning.\n */\n #showStatusAndKeepSpinning(symbolType: SymbolType, args: unknown[]) {\n let text = args.at(0)\n let extras: unknown[]\n if (typeof text === 'string') {\n extras = args.slice(1)\n } else {\n extras = args\n text = ''\n }\n\n const { LOG_SYMBOLS, logger } = /*@__PURE__*/ require('./logger.js')\n // Note: Status messages always go to stderr.\n logger.error(`${LOG_SYMBOLS[symbolType]} ${text}`, ...extras)\n return this\n }\n\n /**\n * Update the spinner's displayed text.\n * Rebuilds display text and triggers render.\n * @private\n */\n #updateSpinnerText() {\n // Call the parent class's text setter, which triggers render.\n super.text = this.#buildDisplayText()\n }\n\n /**\n * Show a debug message without stopping the spinner (only if debug mode enabled).\n * Outputs to stderr and continues spinning.\n */\n debug(...args: unknown[]) {\n const { isDebug } = /*@__PURE__*/ require('./debug.js')\n if (isDebug()) {\n return this.#showStatusAndKeepSpinning('info', args)\n }\n return this\n }\n\n /**\n * Show a debug message and stop the spinner (only if debug mode enabled).\n * Auto-clears the spinner line before displaying the message.\n */\n debugAndStop(...args: unknown[]) {\n const { isDebug } = /*@__PURE__*/ require('./debug.js')\n if (isDebug()) {\n return this.#apply('info', args)\n }\n return this\n }\n\n /**\n * Decrease indentation level.\n * Pass 0 to reset indentation to zero.\n * @param spaces - Number of spaces to remove (default: 2)\n */\n dedent(spaces?: number) {\n // Pass 0 to reset indentation\n if (spaces === 0) {\n this.#indentation = ''\n } else {\n const amount = spaces ?? 2\n const newLength = Math.max(0, this.#indentation.length - amount)\n this.#indentation = this.#indentation.slice(0, newLength)\n }\n this.#updateSpinnerText()\n return this\n }\n\n /**\n * Alias for success() (shorter name).\n * DESIGN DECISION: Unlike yocto-spinner, our done() does NOT stop the spinner.\n * Use doneAndStop() if you want to stop the spinner.\n */\n done(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('success', args)\n }\n\n /**\n * Show a done message and stop the spinner.\n * Auto-clears the spinner line before displaying the success message.\n */\n doneAndStop(...args: unknown[]) {\n return this.#apply('success', args)\n }\n\n /**\n * Show a failure message without stopping the spinner.\n * DESIGN DECISION: Unlike yocto-spinner, our fail() does NOT stop the spinner.\n * This allows displaying errors while continuing to spin.\n * Use failAndStop() if you want to stop the spinner.\n */\n fail(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('fail', args)\n }\n\n /**\n * Show a failure message and stop the spinner.\n * Auto-clears the spinner line before displaying the error message.\n */\n failAndStop(...args: unknown[]) {\n return this.#apply('error', args)\n }\n\n /**\n * Increase indentation level.\n * Pass 0 to reset indentation to zero.\n * @param spaces - Number of spaces to add (default: 2)\n */\n indent(spaces?: number) {\n // Pass 0 to reset indentation\n if (spaces === 0) {\n this.#indentation = ''\n } else {\n const amount = spaces ?? 2\n this.#indentation += ' '.repeat(amount)\n }\n this.#updateSpinnerText()\n return this\n }\n\n /**\n * Show an info message without stopping the spinner.\n * Outputs to stderr and continues spinning.\n */\n info(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('info', args)\n }\n\n /**\n * Show an info message and stop the spinner.\n * Auto-clears the spinner line before displaying the message.\n */\n infoAndStop(...args: unknown[]) {\n return this.#apply('info', args)\n }\n\n /**\n * Log a message to stdout without stopping the spinner.\n * Unlike other methods, this outputs to stdout for data logging.\n */\n log(...args: unknown[]) {\n const { logger } = /*@__PURE__*/ require('./logger.js')\n logger.log(...args)\n return this\n }\n\n /**\n * Log a message and stop the spinner.\n * Auto-clears the spinner line before displaying the message.\n */\n logAndStop(...args: unknown[]) {\n return this.#apply('stop', args)\n }\n\n /**\n * Update progress information displayed with the spinner.\n * Shows a progress bar with percentage and optional unit label.\n * @param current - Current progress value\n * @param total - Total progress value\n * @param unit - Optional unit label (e.g., 'files', 'items')\n */\n progress = (\n current: number,\n total: number,\n unit?: string | undefined,\n ) => {\n this.#progress = {\n __proto__: null,\n current,\n total,\n ...(unit ? { unit } : {}),\n } as ProgressInfo\n this.#updateSpinnerText()\n return this\n }\n\n /**\n * Increment progress by a specified amount.\n * Updates the progress bar displayed with the spinner.\n * @param amount - Amount to increment (default: 1)\n */\n progressStep(amount: number = 1) {\n if (this.#progress) {\n const newCurrent = this.#progress.current + amount\n this.#progress = {\n __proto__: null,\n current: Math.max(0, Math.min(newCurrent, this.#progress.total)),\n total: this.#progress.total,\n ...(this.#progress.unit ? { unit: this.#progress.unit } : {}),\n } as ProgressInfo\n this.#updateSpinnerText()\n }\n return this\n }\n\n /**\n * Start the spinner animation with optional text.\n * Begins displaying the animated spinner.\n * @param text - Optional text to display with the spinner\n */\n start(...args: unknown[]) {\n if (args.length) {\n const text = args.at(0)\n const normalized = normalizeText(text)\n // We clear this.text on start when `text` is falsy because yocto-spinner\n // will not clear it otherwise.\n if (!normalized) {\n this.#baseText = ''\n super.text = ''\n } else {\n this.#baseText = normalized\n }\n }\n\n this.#updateSpinnerText()\n return this.#apply('start', args)\n }\n\n /**\n * Log a main step message to stderr without stopping the spinner.\n * Adds a blank line before the message for visual separation.\n * Aligns with logger.step() to use stderr for status messages.\n */\n step(...args: unknown[]) {\n const text = args[0]\n const { logger } = /*@__PURE__*/ require('./logger.js')\n if (typeof text === 'string') {\n // Add blank line before step for visual separation.\n logger.error('')\n // Use error (stderr) to align with logger.step() default stream.\n logger.error(text, ...args.slice(1))\n }\n return this\n }\n\n /**\n * Log an indented substep message to stderr without stopping the spinner.\n * Adds 2-space indentation to the message.\n * Aligns with logger.substep() to use stderr for status messages.\n */\n substep(...args: unknown[]) {\n const text = args[0]\n if (typeof text === 'string') {\n // Add 2-space indent for substep.\n const { logger } = /*@__PURE__*/ require('./logger.js')\n // Use error (stderr) to align with logger.substep() default stream.\n logger.error(` ${text}`, ...args.slice(1))\n }\n return this\n }\n\n /**\n * Stop the spinner animation and clear internal state.\n * Auto-clears the spinner line via yocto-spinner.stop().\n * Resets progress, shimmer, and text state.\n * @param text - Optional final text to display after stopping\n */\n stop(...args: unknown[]) {\n // Clear internal state.\n this.#baseText = ''\n this.#progress = undefined\n // Reset shimmer animation state if shimmer is enabled.\n if (this.#shimmer) {\n this.#shimmer.currentDir = DIR_LTR\n this.#shimmer.step = 0\n }\n // Call parent stop first (clears screen, sets isSpinning = false).\n const result = this.#apply('stop', args)\n // Then clear text to avoid blank frame render.\n // This is safe now because isSpinning is false.\n super.text = ''\n return result\n }\n\n /**\n * Show a success message without stopping the spinner.\n * DESIGN DECISION: Unlike yocto-spinner, our success() does NOT stop the spinner.\n * This allows displaying success messages while continuing to spin for multi-step operations.\n * Use successAndStop() if you want to stop the spinner.\n */\n success(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('success', args)\n }\n\n /**\n * Show a success message and stop the spinner.\n * Auto-clears the spinner line before displaying the success message.\n */\n successAndStop(...args: unknown[]) {\n return this.#apply('success', args)\n }\n\n /**\n * Get or set the spinner text.\n * When called with no arguments, returns the current text.\n * When called with text, updates the display and returns the spinner.\n * @param value - Text to display (omit to get current text)\n * @returns Current text (getter) or this spinner (setter)\n */\n text(): string\n text(value: string): Spinner\n text(value?: string): string | Spinner {\n // biome-ignore lint/complexity/noArguments: Function overload for getter/setter pattern.\n if (arguments.length === 0) {\n // Getter: return current base text\n return this.#baseText\n }\n // Setter: update base text and refresh display\n this.#baseText = value ?? ''\n this.#updateSpinnerText()\n return this as unknown as Spinner\n }\n\n /**\n * Show a warning message without stopping the spinner.\n * Outputs to stderr and continues spinning.\n */\n warn(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('warn', args)\n }\n\n /**\n * Show a warning message and stop the spinner.\n * Auto-clears the spinner line before displaying the warning message.\n */\n warnAndStop(...args: unknown[]) {\n return this.#apply('warning', args)\n }\n\n /**\n * Toggle shimmer effect or update shimmer configuration.\n * Preserves shimmer config when toggling off, allowing easy re-enable.\n * Supports partial config updates to tweak specific properties.\n *\n * @param enabledOrConfig - Boolean to toggle, partial config to update, or direction string\n * @returns This spinner for chaining\n *\n * @example\n * // Toggle off (preserves config for later re-enable)\n * spinner.shimmer(false)\n *\n * // Toggle on (restores saved config or uses defaults)\n * spinner.shimmer(true)\n *\n * // Update specific properties\n * spinner.shimmer({ speed: 0.5 })\n * spinner.shimmer({ color: [255, 0, 0] })\n *\n * // Set direction\n * spinner.shimmer('rtl')\n */\n shimmer(\n enabledOrConfig:\n | boolean\n | Partial<ShimmerConfig>\n | ShimmerDirection\n | undefined,\n ): Spinner {\n if (enabledOrConfig === false) {\n // Disable shimmer but preserve config.\n this.#shimmer = undefined\n } else if (enabledOrConfig === true) {\n // Re-enable with saved config or defaults.\n if (this.#shimmerSavedConfig) {\n // Restore saved config.\n this.#shimmer = { ...this.#shimmerSavedConfig }\n } else {\n // Create default config.\n this.#shimmer = {\n color: COLOR_INHERIT,\n currentDir: DIR_LTR,\n mode: DIR_LTR,\n speed: 1 / 3,\n step: 0,\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n }\n } else if (typeof enabledOrConfig === 'string') {\n // Direction string - update existing or create new.\n if (this.#shimmer) {\n // Update existing shimmer direction.\n this.#shimmer = {\n ...this.#shimmer,\n mode: enabledOrConfig,\n }\n this.#shimmerSavedConfig = this.#shimmer\n } else if (this.#shimmerSavedConfig) {\n // Restore and update.\n this.#shimmer = {\n ...this.#shimmerSavedConfig,\n mode: enabledOrConfig,\n }\n this.#shimmerSavedConfig = this.#shimmer\n } else {\n // Create new with direction.\n this.#shimmer = {\n color: COLOR_INHERIT,\n currentDir: DIR_LTR,\n mode: enabledOrConfig,\n speed: 1 / 3,\n step: 0,\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n }\n } else if (enabledOrConfig && typeof enabledOrConfig === 'object') {\n // Partial config update - merge with existing or saved config.\n const partialConfig = {\n __proto__: null,\n ...enabledOrConfig,\n } as Partial<ShimmerConfig>\n\n if (this.#shimmer) {\n // Update existing shimmer.\n this.#shimmer = {\n ...this.#shimmer,\n ...(partialConfig.color !== undefined\n ? { color: partialConfig.color }\n : {}),\n ...(partialConfig.dir !== undefined\n ? { mode: partialConfig.dir }\n : {}),\n ...(partialConfig.speed !== undefined\n ? { speed: partialConfig.speed }\n : {}),\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n } else if (this.#shimmerSavedConfig) {\n // Restore and update.\n this.#shimmer = {\n ...this.#shimmerSavedConfig,\n ...(partialConfig.color !== undefined\n ? { color: partialConfig.color }\n : {}),\n ...(partialConfig.dir !== undefined\n ? { mode: partialConfig.dir }\n : {}),\n ...(partialConfig.speed !== undefined\n ? { speed: partialConfig.speed }\n : {}),\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n } else {\n // Create new with partial config.\n this.#shimmer = {\n color: partialConfig.color ?? COLOR_INHERIT,\n currentDir: DIR_LTR,\n mode: partialConfig.dir ?? DIR_LTR,\n speed: partialConfig.speed ?? 1 / 3,\n step: 0,\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n }\n }\n\n this.#updateSpinnerText()\n return this as unknown as Spinner\n }\n } as unknown as {\n new (options?: SpinnerOptions | undefined): Spinner\n }\n // Add aliases.\n Object.defineProperties(_Spinner.prototype, {\n error: desc(_Spinner.prototype.fail),\n errorAndStop: desc(_Spinner.prototype.failAndStop),\n warning: desc(_Spinner.prototype.warn),\n warningAndStop: desc(_Spinner.prototype.warnAndStop),\n })\n _defaultSpinner = CI\n ? ciSpinner\n : (getCliSpinners('socket') as SpinnerStyle)\n }\n return new _Spinner({\n spinner: _defaultSpinner,\n ...options,\n })\n}\n\nlet _spinner: ReturnType<typeof Spinner> | undefined\n/**\n * Get the default spinner instance.\n * Lazily creates the spinner to avoid circular dependencies during module initialization.\n */\nexport function getDefaultSpinner(): ReturnType<typeof Spinner> {\n if (_spinner === undefined) {\n _spinner = Spinner()\n }\n return _spinner\n}\n\n/**\n * @deprecated Use `getDefaultSpinner()` function instead for better tree-shaking and to avoid circular dependencies.\n */\nexport const spinner = /* @__PURE__ */ (() => {\n // Lazy initialization to prevent circular dependency issues during module loading.\n let _lazySpinner: ReturnType<typeof Spinner> | undefined\n return new Proxy({} as ReturnType<typeof Spinner>, {\n get(_target, prop) {\n if (_lazySpinner === undefined) {\n _lazySpinner = Spinner()\n }\n const value = _lazySpinner[prop as keyof ReturnType<typeof Spinner>]\n return typeof value === 'function' ? value.bind(_lazySpinner) : value\n },\n })\n})()\n\nexport type WithSpinnerOptions<T> = {\n message: string\n operation: () => Promise<T>\n spinner?: Spinner | undefined\n}\n\n/**\n * Execute an async operation with spinner lifecycle management.\n * Ensures spinner.stop() is always called via try/finally, even if the operation throws.\n *\n * @param options - Configuration object\n * @param options.message - Message to display while spinner is running\n * @param options.operation - Async function to execute\n * @param options.spinner - Optional spinner instance (if not provided, no spinner is used)\n * @returns Result of the operation\n * @throws Re-throws any error from operation after stopping spinner\n *\n * @example\n * import { spinner, withSpinner } from '@socketsecurity/registry/lib/spinner'\n *\n * // With spinner instance\n * await withSpinner({\n * message: 'Processing\u2026',\n * operation: async () => {\n * return await processData()\n * },\n * spinner\n * })\n *\n * // Without spinner instance (no-op)\n * await withSpinner({\n * message: 'Processing\u2026',\n * operation: async () => {\n * return await processData()\n * }\n * })\n */\nexport async function withSpinner<T>(\n options: WithSpinnerOptions<T>,\n): Promise<T> {\n const { message, operation, spinner } = {\n __proto__: null,\n ...options,\n } as WithSpinnerOptions<T>\n\n if (!spinner) {\n return await operation()\n }\n\n spinner.start(message)\n try {\n return await operation()\n } finally {\n spinner.stop()\n }\n}\n\nexport type WithSpinnerRestoreOptions<T> = {\n operation: () => Promise<T>\n spinner?: Spinner | undefined\n wasSpinning: boolean\n}\n\n/**\n * Execute an async operation with conditional spinner restart.\n * Useful when you need to temporarily stop a spinner for an operation,\n * then restore it to its previous state.\n *\n * @param options - Configuration object\n * @param options.operation - Async function to execute\n * @param options.spinner - Optional spinner instance to manage\n * @param options.wasSpinning - Whether spinner was spinning before\n * @returns Result of the operation\n * @throws Re-throws any error from operation after restoring spinner state\n *\n * @example\n * import { spinner, withSpinnerRestore } from '@socketsecurity/registry/lib/spinner'\n *\n * const wasSpinning = spinner.isSpinning\n * spinner.stop()\n *\n * const result = await withSpinnerRestore({\n * operation: async () => {\n * // Do work without spinner\n * return await someOperation()\n * },\n * spinner,\n * wasSpinning\n * })\n */\nexport async function withSpinnerRestore<T>(\n options: WithSpinnerRestoreOptions<T>,\n): Promise<T> {\n const { operation, spinner, wasSpinning } = {\n __proto__: null,\n ...options,\n } as WithSpinnerRestoreOptions<T>\n\n try {\n return await operation()\n } finally {\n if (spinner && wasSpinning) {\n spinner.start()\n }\n }\n}\n\nexport type WithSpinnerSyncOptions<T> = {\n message: string\n operation: () => T\n spinner?: Spinner | undefined\n}\n\n/**\n * Execute a synchronous operation with spinner lifecycle management.\n * Ensures spinner.stop() is always called via try/finally, even if the operation throws.\n *\n * @param options - Configuration object\n * @param options.message - Message to display while spinner is running\n * @param options.operation - Function to execute\n * @param options.spinner - Optional spinner instance (if not provided, no spinner is used)\n * @returns Result of the operation\n * @throws Re-throws any error from operation after stopping spinner\n *\n * @example\n * import { spinner, withSpinnerSync} from '@socketsecurity/registry/lib/spinner'\n *\n * const result = withSpinnerSync({\n * message: 'Processing\u2026',\n * operation: () => {\n * return processDataSync()\n * },\n * spinner\n * })\n */\nexport function withSpinnerSync<T>(options: WithSpinnerSyncOptions<T>): T {\n const { message, operation, spinner } = {\n __proto__: null,\n ...options,\n } as WithSpinnerSyncOptions<T>\n\n if (!spinner) {\n return operation()\n }\n\n spinner.start(message)\n try {\n return operation()\n } finally {\n spinner.stop()\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,gBAAmB;AACnB,0BAA4C;AAO5C,0BAAqD;AACrD,2BAAyB;AACzB,qBAAuB;AACvB,qBAA2C;AA6B3C,MAAM,aAA0C;AAAA,EAC9C,WAAW;AAAA,EACX,OAAO,CAAC,GAAG,GAAG,CAAC;AAAA,EACf,MAAM,CAAC,GAAG,GAAG,GAAG;AAAA,EAChB,YAAY,CAAC,KAAK,KAAK,GAAG;AAAA,EAC1B,MAAM,CAAC,GAAG,KAAK,GAAG;AAAA,EAClB,YAAY,CAAC,GAAG,KAAK,GAAG;AAAA,EACxB,MAAM,CAAC,KAAK,KAAK,GAAG;AAAA,EACpB,OAAO,CAAC,GAAG,KAAK,CAAC;AAAA,EACjB,aAAa,CAAC,GAAG,KAAK,CAAC;AAAA,EACvB,SAAS,CAAC,KAAK,GAAG,GAAG;AAAA,EACrB,eAAe,CAAC,KAAK,KAAK,GAAG;AAAA,EAC7B,KAAK,CAAC,KAAK,GAAG,CAAC;AAAA,EACf,WAAW,CAAC,KAAK,IAAI,CAAC;AAAA,EACtB,OAAO,CAAC,KAAK,KAAK,GAAG;AAAA,EACrB,aAAa,CAAC,KAAK,KAAK,GAAG;AAAA,EAC3B,QAAQ,CAAC,KAAK,KAAK,CAAC;AAAA,EACpB,cAAc,CAAC,KAAK,KAAK,GAAG;AAC9B;AAKA,SAAS,WAAW,OAAsC;AACxD,SAAO,MAAM,QAAQ,KAAK;AAC5B;AAKA,SAAS,MAAM,OAA6B;AAC1C,MAAI,WAAW,KAAK,GAAG;AACrB,WAAO;AAAA,EACT;A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,WAAO,MAAM,UAAU;AAAA,EACzB,UAAE;AACA,QAAIA,YAAW,aAAa;AAC1B,MAAAA,SAAQ,MAAM;AAAA,IAChB;AAAA,EACF;AACF;AA8BO,SAAS,gBAAmB,SAAuC;AACxE,QAAM,EAAE,SAAS,WAAW,SAAAA,SAAQ,IAAI;AAAA,IACtC,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AAEA,MAAI,CAACA,UAAS;AACZ,WAAO,UAAU;AAAA,EACnB;AAEA,EAAAA,SAAQ,MAAM,OAAO;AACrB,MAAI;AACF,WAAO,UAAU;AAAA,EACnB,UAAE;AACA,IAAAA,SAAQ,KAAK;AAAA,EACf;AACF;",
4
+ "sourcesContent": ["/**\n * @fileoverview CLI spinner utilities for long-running operations.\n * Provides animated progress indicators with CI environment detection.\n */\n\nimport type { Writable } from 'node:stream'\n\n// Note: getAbortSignal is imported lazily to avoid circular dependencies.\nimport { CI } from '#env/ci'\nimport { generateSocketSpinnerFrames } from './effects/pulse-frames'\nimport type {\n ShimmerColorGradient,\n ShimmerConfig,\n ShimmerDirection,\n ShimmerState,\n} from './effects/text-shimmer'\nimport { applyShimmer, COLOR_INHERIT, DIR_LTR } from './effects/text-shimmer'\nimport yoctoSpinner from './external/@socketregistry/yocto-spinner'\nimport { hasOwn } from './objects'\nimport { isBlankString, stringWidth } from './strings'\n\nexport type ColorName =\n | 'black'\n | 'blue'\n | 'blueBright'\n | 'cyan'\n | 'cyanBright'\n | 'gray'\n | 'green'\n | 'greenBright'\n | 'magenta'\n | 'magentaBright'\n | 'red'\n | 'redBright'\n | 'white'\n | 'whiteBright'\n | 'yellow'\n | 'yellowBright'\n\nexport type ColorInherit = 'inherit'\n\nexport type ColorRgb = readonly [number, number, number]\n\nexport type ColorValue = ColorName | ColorRgb\n\nexport type SymbolType = 'fail' | 'info' | 'success' | 'warn'\n\n// Map color names to RGB values.\nconst colorToRgb: Record<ColorName, ColorRgb> = {\n __proto__: null,\n black: [0, 0, 0],\n blue: [0, 0, 255],\n blueBright: [100, 149, 237],\n cyan: [0, 255, 255],\n cyanBright: [0, 255, 255],\n gray: [128, 128, 128],\n green: [0, 128, 0],\n greenBright: [0, 255, 0],\n magenta: [255, 0, 255],\n magentaBright: [255, 105, 180],\n red: [255, 0, 0],\n redBright: [255, 69, 0],\n white: [255, 255, 255],\n whiteBright: [255, 255, 255],\n yellow: [255, 255, 0],\n yellowBright: [255, 255, 153],\n} as Record<ColorName, ColorRgb>\n\n/**\n * Check if value is RGB tuple.\n */\nfunction isRgbTuple(value: ColorValue): value is ColorRgb {\n return Array.isArray(value)\n}\n\n/**\n * Convert ColorValue to RGB tuple.\n */\nfunction toRgb(color: ColorValue): ColorRgb {\n if (isRgbTuple(color)) {\n return color\n }\n return colorToRgb[color]\n}\n\nexport type ProgressInfo = {\n current: number\n total: number\n unit?: string | undefined\n}\n\nexport type ShimmerInfo = ShimmerState & {\n color: ColorInherit | ColorValue | ShimmerColorGradient\n}\n\nexport type Spinner = {\n color: ColorRgb\n spinner: SpinnerStyle\n\n get isSpinning(): boolean\n\n clear(): Spinner\n debug(text?: string | undefined, ...extras: unknown[]): Spinner\n debugAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n error(text?: string | undefined, ...extras: unknown[]): Spinner\n errorAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n fail(text?: string | undefined, ...extras: unknown[]): Spinner\n failAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n // text property returns a method via _textMethod override\n text(value: string): Spinner\n text(): string\n\n indent(spaces?: number | undefined): Spinner\n dedent(spaces?: number | undefined): Spinner\n\n info(text?: string | undefined, ...extras: unknown[]): Spinner\n infoAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n log(text?: string | undefined, ...extras: unknown[]): Spinner\n logAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n start(text?: string | undefined): Spinner\n stop(text?: string | undefined): Spinner\n stopAndPersist(text?: string | undefined): Spinner\n\n step(text?: string | undefined, ...extras: unknown[]): Spinner\n substep(text?: string | undefined, ...extras: unknown[]): Spinner\n\n success(text?: string | undefined, ...extras: unknown[]): Spinner\n successAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n done(text?: string | undefined, ...extras: unknown[]): Spinner\n doneAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n\n progress(current: number, total: number, unit?: string | undefined): Spinner\n progressStep(amount?: number): Spinner\n\n shimmer(enabled: boolean): Spinner\n shimmer(config: Partial<ShimmerConfig> | ShimmerDirection): Spinner\n\n warn(text?: string | undefined, ...extras: unknown[]): Spinner\n warnAndStop(text?: string | undefined, ...extras: unknown[]): Spinner\n}\n\nexport type SpinnerOptions = {\n readonly color?: ColorValue | undefined\n readonly shimmer?: ShimmerConfig | ShimmerDirection | undefined\n readonly spinner?: SpinnerStyle | undefined\n readonly signal?: AbortSignal | undefined\n readonly stream?: Writable | undefined\n readonly text?: string | undefined\n}\n\nexport type SpinnerStyle = {\n readonly frames: string[]\n readonly interval?: number | undefined\n}\n\nexport const ciSpinner: SpinnerStyle = {\n frames: [''],\n interval: 2_147_483_647,\n}\n\nfunction desc(value: unknown) {\n return {\n __proto__: null,\n configurable: true,\n value,\n writable: true,\n }\n}\n\nfunction normalizeText(value: unknown) {\n return typeof value === 'string' ? value.trimStart() : ''\n}\n\nfunction formatProgress(progress: ProgressInfo): string {\n const { current, total, unit } = progress\n const percentage = Math.round((current / total) * 100)\n const bar = renderProgressBar(percentage)\n const count = unit ? `${current}/${total} ${unit}` : `${current}/${total}`\n return `${bar} ${percentage}% (${count})`\n}\n\nfunction renderProgressBar(percentage: number, width: number = 20): string {\n const filled = Math.round((percentage / 100) * width)\n const empty = width - filled\n const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(empty)\n // Use cyan color for the progress bar\n const colors = /*@__PURE__*/ require('./external/yoctocolors-cjs')\n return colors.cyan(bar)\n}\n\nlet _cliSpinners: Record<string, SpinnerStyle> | undefined\n\n/**\n * Get available CLI spinner styles or a specific style by name.\n * Extends the standard cli-spinners collection with Socket custom spinners.\n *\n * @see https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json\n *\n * Custom spinners:\n * - `socket` (default): Socket pulse animation with sparkles and lightning\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function getCliSpinners(\n styleName?: string | undefined,\n): SpinnerStyle | Record<string, SpinnerStyle> | undefined {\n if (_cliSpinners === undefined) {\n // biome-ignore lint/suspicious/noExplicitAny: Accessing internal yocto-spinner constructor.\n const YoctoCtor = yoctoSpinner as any\n // Get the YoctoSpinner class to access static properties.\n const tempInstance = YoctoCtor({})\n // biome-ignore lint/suspicious/noExplicitAny: Accessing internal yocto-spinner class.\n const YoctoSpinnerClass = tempInstance.constructor as any\n // Extend the standard cli-spinners collection with Socket custom spinners.\n _cliSpinners = {\n __proto__: null,\n ...YoctoSpinnerClass.spinners,\n socket: generateSocketSpinnerFrames(),\n }\n }\n if (typeof styleName === 'string' && _cliSpinners) {\n return hasOwn(_cliSpinners, styleName) ? _cliSpinners[styleName] : undefined\n }\n return _cliSpinners\n}\n\nlet _Spinner: {\n new (options?: SpinnerOptions | undefined): Spinner\n}\nlet _defaultSpinner: SpinnerStyle | undefined\n\n/**\n * Create a spinner instance for displaying loading indicators.\n *\n * AUTO-CLEAR BEHAVIOR:\n * - All *AndStop() methods AUTO-CLEAR the spinner line via yocto-spinner.stop()\n * Examples: doneAndStop(), successAndStop(), failAndStop(), etc.\n *\n * - Methods WITHOUT \"AndStop\" do NOT clear (spinner keeps spinning)\n * Examples: done(), success(), fail(), etc.\n *\n * STREAM USAGE:\n * - Spinner animation: stderr (yocto-spinner default)\n * - Status methods (done, success, fail, info, warn, step, substep): stderr\n * - Data methods (log): stdout\n *\n * COMPARISON WITH LOGGER:\n * - logger.done() does NOT auto-clear (requires manual logger.clearLine())\n * - spinner.doneAndStop() DOES auto-clear (built into yocto-spinner.stop())\n * - Pattern: logger.clearLine().done() vs spinner.doneAndStop()\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function Spinner(options?: SpinnerOptions | undefined): Spinner {\n if (_Spinner === undefined) {\n // biome-ignore lint/suspicious/noExplicitAny: Accessing internal yocto-spinner constructor.\n const YoctoCtor = yoctoSpinner as any\n // Get the actual YoctoSpinner class from an instance\n const tempInstance = YoctoCtor({})\n const YoctoSpinnerClass = tempInstance.constructor\n\n /*@__PURE__*/\n // biome-ignore lint/suspicious/noExplicitAny: Extending yocto-spinner class.\n _Spinner = class SpinnerClass extends (YoctoSpinnerClass as any) {\n declare isSpinning: boolean\n #baseText: string = ''\n #indentation: string = ''\n #progress?: ProgressInfo | undefined\n #shimmer?: ShimmerInfo | undefined\n #shimmerSavedConfig?: ShimmerInfo | undefined\n\n constructor(options?: SpinnerOptions | undefined) {\n const opts = { __proto__: null, ...options } as SpinnerOptions\n\n // Convert color option to RGB (default to Socket purple).\n const spinnerColor = opts.color ?? ([140, 82, 255] as const)\n\n // Validate RGB tuple if provided.\n if (\n isRgbTuple(spinnerColor) &&\n (spinnerColor.length !== 3 ||\n !spinnerColor.every(\n n => typeof n === 'number' && n >= 0 && n <= 255,\n ))\n ) {\n throw new TypeError(\n 'RGB color must be an array of 3 numbers between 0 and 255',\n )\n }\n\n const spinnerColorRgb = toRgb(spinnerColor)\n\n // Parse shimmer config - can be object or direction string.\n let shimmerInfo: ShimmerInfo | undefined\n if (opts.shimmer) {\n let shimmerDir: ShimmerDirection\n let shimmerColor:\n | ColorInherit\n | ColorValue\n | ShimmerColorGradient\n | undefined\n // Default: 0.33 steps per frame (~150ms per step).\n let shimmerSpeed: number = 1 / 3\n\n if (typeof opts.shimmer === 'string') {\n shimmerDir = opts.shimmer\n } else {\n const shimmerConfig = {\n __proto__: null,\n ...opts.shimmer,\n } as ShimmerConfig\n shimmerDir = shimmerConfig.dir ?? DIR_LTR\n shimmerColor = shimmerConfig.color ?? COLOR_INHERIT\n shimmerSpeed = shimmerConfig.speed ?? 1 / 3\n }\n\n // Create shimmer info with initial animation state:\n // - COLOR_INHERIT means use spinner color dynamically\n // - ColorValue (name or RGB tuple) is an explicit override color\n // - undefined color defaults to COLOR_INHERIT\n // - speed controls steps per frame (lower = slower, e.g., 0.33 = ~150ms per step)\n shimmerInfo = {\n __proto__: null,\n color: shimmerColor === undefined ? COLOR_INHERIT : shimmerColor,\n currentDir: DIR_LTR,\n mode: shimmerDir,\n speed: shimmerSpeed,\n step: 0,\n } as ShimmerInfo\n }\n\n // eslint-disable-next-line constructor-super\n super({\n signal: require('#constants/process').getAbortSignal(),\n ...opts,\n // Pass RGB color directly to yocto-spinner (it now supports RGB).\n color: spinnerColorRgb,\n // onRenderFrame callback provides full control over frame + text layout.\n // Calculates spacing based on frame width to prevent text jumping.\n onRenderFrame: (\n frame: string,\n text: string,\n applyColor: (text: string) => string,\n ) => {\n const width = stringWidth(frame)\n // Narrow frames (width 1) get 2 spaces, wide frames (width 2) get 1 space.\n // Total width is consistent: 3 characters (frame + spacing) before text.\n const spacing = width === 1 ? ' ' : ' '\n return frame ? `${applyColor(frame)}${spacing}${text}` : text\n },\n // onFrameUpdate callback is called by yocto-spinner whenever a frame advances.\n // This ensures shimmer updates are perfectly synchronized with animation beats.\n onFrameUpdate: shimmerInfo\n ? () => {\n // Update parent's text without triggering render.\n // Parent's #skipRender flag prevents nested render calls.\n // Only update if we have base text to avoid blank frames.\n if (this.#baseText) {\n super.text = this.#buildDisplayText()\n }\n }\n : undefined,\n })\n\n this.#shimmer = shimmerInfo\n this.#shimmerSavedConfig = shimmerInfo\n }\n\n // Override color getter to ensure it's always RGB.\n get color(): ColorRgb {\n const value = super.color\n return isRgbTuple(value) ? value : toRgb(value)\n }\n\n // Override color setter to always convert to RGB before passing to yocto-spinner.\n set color(value: ColorValue | ColorRgb) {\n super.color = isRgbTuple(value) ? value : toRgb(value)\n }\n\n /**\n * Apply a yocto-spinner method and update logger state.\n * Handles text normalization, extra arguments, and logger tracking.\n * @private\n */\n #apply(methodName: string, args: unknown[]) {\n let extras: unknown[]\n let text = args.at(0)\n if (typeof text === 'string') {\n extras = args.slice(1)\n } else {\n extras = args\n text = ''\n }\n const wasSpinning = this.isSpinning\n const normalized = normalizeText(text)\n super[methodName](normalized)\n const {\n incLogCallCountSymbol,\n lastWasBlankSymbol,\n logger,\n } = /*@__PURE__*/ require('./logger.js')\n if (methodName === 'stop') {\n if (wasSpinning && normalized) {\n logger[lastWasBlankSymbol](isBlankString(normalized))\n logger[incLogCallCountSymbol]()\n }\n } else {\n logger[lastWasBlankSymbol](false)\n logger[incLogCallCountSymbol]()\n }\n if (extras.length) {\n logger.log(...extras)\n logger[lastWasBlankSymbol](false)\n }\n return this\n }\n\n /**\n * Build the complete display text with progress, shimmer, and indentation.\n * Combines base text, progress bar, shimmer effects, and indentation.\n * @private\n */\n #buildDisplayText() {\n let displayText = this.#baseText\n\n if (this.#progress) {\n const progressText = formatProgress(this.#progress)\n displayText = displayText\n ? `${displayText} ${progressText}`\n : progressText\n }\n\n // Apply shimmer effect if enabled.\n if (displayText && this.#shimmer) {\n // If shimmer color is 'inherit', use current spinner color (getter ensures RGB).\n // Otherwise, check if it's a gradient (array of arrays) or single color.\n let shimmerColor: ColorRgb | ShimmerColorGradient\n if (this.#shimmer.color === COLOR_INHERIT) {\n shimmerColor = this.color\n } else if (Array.isArray(this.#shimmer.color[0])) {\n // It's a gradient - use as is.\n shimmerColor = this.#shimmer.color as ShimmerColorGradient\n } else {\n // It's a single color - convert to RGB.\n shimmerColor = toRgb(this.#shimmer.color as ColorValue)\n }\n\n displayText = applyShimmer(displayText, this.#shimmer, {\n color: shimmerColor,\n direction: this.#shimmer.mode,\n })\n }\n\n // Apply indentation\n if (this.#indentation && displayText) {\n displayText = this.#indentation + displayText\n }\n\n return displayText\n }\n\n /**\n * Show a status message without stopping the spinner.\n * Outputs the symbol and message to stderr, then continues spinning.\n */\n #showStatusAndKeepSpinning(symbolType: SymbolType, args: unknown[]) {\n let text = args.at(0)\n let extras: unknown[]\n if (typeof text === 'string') {\n extras = args.slice(1)\n } else {\n extras = args\n text = ''\n }\n\n const { LOG_SYMBOLS, logger } = /*@__PURE__*/ require('./logger.js')\n // Note: Status messages always go to stderr.\n logger.error(`${LOG_SYMBOLS[symbolType]} ${text}`, ...extras)\n return this\n }\n\n /**\n * Update the spinner's displayed text.\n * Rebuilds display text and triggers render.\n * @private\n */\n #updateSpinnerText() {\n // Call the parent class's text setter, which triggers render.\n super.text = this.#buildDisplayText()\n }\n\n /**\n * Show a debug message without stopping the spinner (only if debug mode enabled).\n * Outputs to stderr and continues spinning.\n */\n debug(...args: unknown[]) {\n const { isDebug } = /*@__PURE__*/ require('./debug.js')\n if (isDebug()) {\n return this.#showStatusAndKeepSpinning('info', args)\n }\n return this\n }\n\n /**\n * Show a debug message and stop the spinner (only if debug mode enabled).\n * Auto-clears the spinner line before displaying the message.\n */\n debugAndStop(...args: unknown[]) {\n const { isDebug } = /*@__PURE__*/ require('./debug.js')\n if (isDebug()) {\n return this.#apply('info', args)\n }\n return this\n }\n\n /**\n * Decrease indentation level.\n * Pass 0 to reset indentation to zero.\n * @param spaces - Number of spaces to remove (default: 2)\n */\n dedent(spaces?: number) {\n // Pass 0 to reset indentation\n if (spaces === 0) {\n this.#indentation = ''\n } else {\n const amount = spaces ?? 2\n const newLength = Math.max(0, this.#indentation.length - amount)\n this.#indentation = this.#indentation.slice(0, newLength)\n }\n this.#updateSpinnerText()\n return this\n }\n\n /**\n * Alias for success() (shorter name).\n * DESIGN DECISION: Unlike yocto-spinner, our done() does NOT stop the spinner.\n * Use doneAndStop() if you want to stop the spinner.\n */\n done(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('success', args)\n }\n\n /**\n * Show a done message and stop the spinner.\n * Auto-clears the spinner line before displaying the success message.\n */\n doneAndStop(...args: unknown[]) {\n return this.#apply('success', args)\n }\n\n /**\n * Show a failure message without stopping the spinner.\n * DESIGN DECISION: Unlike yocto-spinner, our fail() does NOT stop the spinner.\n * This allows displaying errors while continuing to spin.\n * Use failAndStop() if you want to stop the spinner.\n */\n fail(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('fail', args)\n }\n\n /**\n * Show a failure message and stop the spinner.\n * Auto-clears the spinner line before displaying the error message.\n */\n failAndStop(...args: unknown[]) {\n return this.#apply('error', args)\n }\n\n /**\n * Increase indentation level.\n * Pass 0 to reset indentation to zero.\n * @param spaces - Number of spaces to add (default: 2)\n */\n indent(spaces?: number) {\n // Pass 0 to reset indentation\n if (spaces === 0) {\n this.#indentation = ''\n } else {\n const amount = spaces ?? 2\n this.#indentation += ' '.repeat(amount)\n }\n this.#updateSpinnerText()\n return this\n }\n\n /**\n * Show an info message without stopping the spinner.\n * Outputs to stderr and continues spinning.\n */\n info(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('info', args)\n }\n\n /**\n * Show an info message and stop the spinner.\n * Auto-clears the spinner line before displaying the message.\n */\n infoAndStop(...args: unknown[]) {\n return this.#apply('info', args)\n }\n\n /**\n * Log a message to stdout without stopping the spinner.\n * Unlike other methods, this outputs to stdout for data logging.\n */\n log(...args: unknown[]) {\n const { logger } = /*@__PURE__*/ require('./logger.js')\n logger.log(...args)\n return this\n }\n\n /**\n * Log a message and stop the spinner.\n * Auto-clears the spinner line before displaying the message.\n */\n logAndStop(...args: unknown[]) {\n return this.#apply('stop', args)\n }\n\n /**\n * Update progress information displayed with the spinner.\n * Shows a progress bar with percentage and optional unit label.\n * @param current - Current progress value\n * @param total - Total progress value\n * @param unit - Optional unit label (e.g., 'files', 'items')\n */\n progress = (\n current: number,\n total: number,\n unit?: string | undefined,\n ) => {\n this.#progress = {\n __proto__: null,\n current,\n total,\n ...(unit ? { unit } : {}),\n } as ProgressInfo\n this.#updateSpinnerText()\n return this\n }\n\n /**\n * Increment progress by a specified amount.\n * Updates the progress bar displayed with the spinner.\n * @param amount - Amount to increment (default: 1)\n */\n progressStep(amount: number = 1) {\n if (this.#progress) {\n const newCurrent = this.#progress.current + amount\n this.#progress = {\n __proto__: null,\n current: Math.max(0, Math.min(newCurrent, this.#progress.total)),\n total: this.#progress.total,\n ...(this.#progress.unit ? { unit: this.#progress.unit } : {}),\n } as ProgressInfo\n this.#updateSpinnerText()\n }\n return this\n }\n\n /**\n * Start the spinner animation with optional text.\n * Begins displaying the animated spinner.\n * @param text - Optional text to display with the spinner\n */\n start(...args: unknown[]) {\n if (args.length) {\n const text = args.at(0)\n const normalized = normalizeText(text)\n // We clear this.text on start when `text` is falsy because yocto-spinner\n // will not clear it otherwise.\n if (!normalized) {\n this.#baseText = ''\n super.text = ''\n } else {\n this.#baseText = normalized\n }\n }\n\n this.#updateSpinnerText()\n return this.#apply('start', args)\n }\n\n /**\n * Log a main step message to stderr without stopping the spinner.\n * Adds a blank line before the message for visual separation.\n * Aligns with logger.step() to use stderr for status messages.\n */\n step(...args: unknown[]) {\n const text = args[0]\n const { logger } = /*@__PURE__*/ require('./logger.js')\n if (typeof text === 'string') {\n // Add blank line before step for visual separation.\n logger.error('')\n // Use error (stderr) to align with logger.step() default stream.\n logger.error(text, ...args.slice(1))\n }\n return this\n }\n\n /**\n * Log an indented substep message to stderr without stopping the spinner.\n * Adds 2-space indentation to the message.\n * Aligns with logger.substep() to use stderr for status messages.\n */\n substep(...args: unknown[]) {\n const text = args[0]\n if (typeof text === 'string') {\n // Add 2-space indent for substep.\n const { logger } = /*@__PURE__*/ require('./logger.js')\n // Use error (stderr) to align with logger.substep() default stream.\n logger.error(` ${text}`, ...args.slice(1))\n }\n return this\n }\n\n /**\n * Stop the spinner animation and clear internal state.\n * Auto-clears the spinner line via yocto-spinner.stop().\n * Resets progress, shimmer, and text state.\n * @param text - Optional final text to display after stopping\n */\n stop(...args: unknown[]) {\n // Clear internal state.\n this.#baseText = ''\n this.#progress = undefined\n // Reset shimmer animation state if shimmer is enabled.\n if (this.#shimmer) {\n this.#shimmer.currentDir = DIR_LTR\n this.#shimmer.step = 0\n }\n // Call parent stop first (clears screen, sets isSpinning = false).\n const result = this.#apply('stop', args)\n // Then clear text to avoid blank frame render.\n // This is safe now because isSpinning is false.\n super.text = ''\n return result\n }\n\n /**\n * Show a success message without stopping the spinner.\n * DESIGN DECISION: Unlike yocto-spinner, our success() does NOT stop the spinner.\n * This allows displaying success messages while continuing to spin for multi-step operations.\n * Use successAndStop() if you want to stop the spinner.\n */\n success(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('success', args)\n }\n\n /**\n * Show a success message and stop the spinner.\n * Auto-clears the spinner line before displaying the success message.\n */\n successAndStop(...args: unknown[]) {\n return this.#apply('success', args)\n }\n\n /**\n * Get or set the spinner text.\n * When called with no arguments, returns the current text.\n * When called with text, updates the display and returns the spinner.\n * @param value - Text to display (omit to get current text)\n * @returns Current text (getter) or this spinner (setter)\n */\n text(): string\n text(value: string): Spinner\n text(value?: string): string | Spinner {\n // biome-ignore lint/complexity/noArguments: Function overload for getter/setter pattern.\n if (arguments.length === 0) {\n // Getter: return current base text\n return this.#baseText\n }\n // Setter: update base text and refresh display\n this.#baseText = value ?? ''\n this.#updateSpinnerText()\n return this as unknown as Spinner\n }\n\n /**\n * Show a warning message without stopping the spinner.\n * Outputs to stderr and continues spinning.\n */\n warn(...args: unknown[]) {\n return this.#showStatusAndKeepSpinning('warn', args)\n }\n\n /**\n * Show a warning message and stop the spinner.\n * Auto-clears the spinner line before displaying the warning message.\n */\n warnAndStop(...args: unknown[]) {\n return this.#apply('warning', args)\n }\n\n /**\n * Toggle shimmer effect or update shimmer configuration.\n * Preserves shimmer config when toggling off, allowing easy re-enable.\n * Supports partial config updates to tweak specific properties.\n *\n * @param enabledOrConfig - Boolean to toggle, partial config to update, or direction string\n * @returns This spinner for chaining\n *\n * @example\n * // Toggle off (preserves config for later re-enable)\n * spinner.shimmer(false)\n *\n * // Toggle on (restores saved config or uses defaults)\n * spinner.shimmer(true)\n *\n * // Update specific properties\n * spinner.shimmer({ speed: 0.5 })\n * spinner.shimmer({ color: [255, 0, 0] })\n *\n * // Set direction\n * spinner.shimmer('rtl')\n */\n shimmer(\n enabledOrConfig:\n | boolean\n | Partial<ShimmerConfig>\n | ShimmerDirection\n | undefined,\n ): Spinner {\n if (enabledOrConfig === false) {\n // Disable shimmer but preserve config.\n this.#shimmer = undefined\n } else if (enabledOrConfig === true) {\n // Re-enable with saved config or defaults.\n if (this.#shimmerSavedConfig) {\n // Restore saved config.\n this.#shimmer = { ...this.#shimmerSavedConfig }\n } else {\n // Create default config.\n this.#shimmer = {\n color: COLOR_INHERIT,\n currentDir: DIR_LTR,\n mode: DIR_LTR,\n speed: 1 / 3,\n step: 0,\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n }\n } else if (typeof enabledOrConfig === 'string') {\n // Direction string - update existing or create new.\n if (this.#shimmer) {\n // Update existing shimmer direction.\n this.#shimmer = {\n ...this.#shimmer,\n mode: enabledOrConfig,\n }\n this.#shimmerSavedConfig = this.#shimmer\n } else if (this.#shimmerSavedConfig) {\n // Restore and update.\n this.#shimmer = {\n ...this.#shimmerSavedConfig,\n mode: enabledOrConfig,\n }\n this.#shimmerSavedConfig = this.#shimmer\n } else {\n // Create new with direction.\n this.#shimmer = {\n color: COLOR_INHERIT,\n currentDir: DIR_LTR,\n mode: enabledOrConfig,\n speed: 1 / 3,\n step: 0,\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n }\n } else if (enabledOrConfig && typeof enabledOrConfig === 'object') {\n // Partial config update - merge with existing or saved config.\n const partialConfig = {\n __proto__: null,\n ...enabledOrConfig,\n } as Partial<ShimmerConfig>\n\n if (this.#shimmer) {\n // Update existing shimmer.\n this.#shimmer = {\n ...this.#shimmer,\n ...(partialConfig.color !== undefined\n ? { color: partialConfig.color }\n : {}),\n ...(partialConfig.dir !== undefined\n ? { mode: partialConfig.dir }\n : {}),\n ...(partialConfig.speed !== undefined\n ? { speed: partialConfig.speed }\n : {}),\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n } else if (this.#shimmerSavedConfig) {\n // Restore and update.\n this.#shimmer = {\n ...this.#shimmerSavedConfig,\n ...(partialConfig.color !== undefined\n ? { color: partialConfig.color }\n : {}),\n ...(partialConfig.dir !== undefined\n ? { mode: partialConfig.dir }\n : {}),\n ...(partialConfig.speed !== undefined\n ? { speed: partialConfig.speed }\n : {}),\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n } else {\n // Create new with partial config.\n this.#shimmer = {\n color: partialConfig.color ?? COLOR_INHERIT,\n currentDir: DIR_LTR,\n mode: partialConfig.dir ?? DIR_LTR,\n speed: partialConfig.speed ?? 1 / 3,\n step: 0,\n } as ShimmerInfo\n this.#shimmerSavedConfig = this.#shimmer\n }\n }\n\n this.#updateSpinnerText()\n return this as unknown as Spinner\n }\n } as unknown as {\n new (options?: SpinnerOptions | undefined): Spinner\n }\n // Add aliases.\n Object.defineProperties(_Spinner.prototype, {\n error: desc(_Spinner.prototype.fail),\n errorAndStop: desc(_Spinner.prototype.failAndStop),\n warning: desc(_Spinner.prototype.warn),\n warningAndStop: desc(_Spinner.prototype.warnAndStop),\n })\n _defaultSpinner = CI\n ? ciSpinner\n : (getCliSpinners('socket') as SpinnerStyle)\n }\n return new _Spinner({\n spinner: _defaultSpinner,\n ...options,\n })\n}\n\nlet _spinner: ReturnType<typeof Spinner> | undefined\n/**\n * Get the default spinner instance.\n * Lazily creates the spinner to avoid circular dependencies during module initialization.\n */\nexport function getDefaultSpinner(): ReturnType<typeof Spinner> {\n if (_spinner === undefined) {\n _spinner = Spinner()\n }\n return _spinner\n}\n\n/**\n * @deprecated Use `getDefaultSpinner()` function instead for better tree-shaking and to avoid circular dependencies.\n */\nexport const spinner = /* @__PURE__ */ (() => {\n // Lazy initialization to prevent circular dependency issues during module loading.\n let _lazySpinner: ReturnType<typeof Spinner> | undefined\n return new Proxy({} as ReturnType<typeof Spinner>, {\n get(_target, prop) {\n if (_lazySpinner === undefined) {\n _lazySpinner = Spinner()\n }\n const value = _lazySpinner[prop as keyof ReturnType<typeof Spinner>]\n return typeof value === 'function' ? value.bind(_lazySpinner) : value\n },\n })\n})()\n\nexport type WithSpinnerOptions<T> = {\n message: string\n operation: () => Promise<T>\n spinner?: Spinner | undefined\n}\n\n/**\n * Execute an async operation with spinner lifecycle management.\n * Ensures spinner.stop() is always called via try/finally, even if the operation throws.\n *\n * @param options - Configuration object\n * @param options.message - Message to display while spinner is running\n * @param options.operation - Async function to execute\n * @param options.spinner - Optional spinner instance (if not provided, no spinner is used)\n * @returns Result of the operation\n * @throws Re-throws any error from operation after stopping spinner\n *\n * @example\n * import { spinner, withSpinner } from '@socketsecurity/registry/lib/spinner'\n *\n * // With spinner instance\n * await withSpinner({\n * message: 'Processing\u2026',\n * operation: async () => {\n * return await processData()\n * },\n * spinner\n * })\n *\n * // Without spinner instance (no-op)\n * await withSpinner({\n * message: 'Processing\u2026',\n * operation: async () => {\n * return await processData()\n * }\n * })\n */\nexport async function withSpinner<T>(\n options: WithSpinnerOptions<T>,\n): Promise<T> {\n const { message, operation, spinner } = {\n __proto__: null,\n ...options,\n } as WithSpinnerOptions<T>\n\n if (!spinner) {\n return await operation()\n }\n\n spinner.start(message)\n try {\n return await operation()\n } finally {\n spinner.stop()\n }\n}\n\nexport type WithSpinnerRestoreOptions<T> = {\n operation: () => Promise<T>\n spinner?: Spinner | undefined\n wasSpinning: boolean\n}\n\n/**\n * Execute an async operation with conditional spinner restart.\n * Useful when you need to temporarily stop a spinner for an operation,\n * then restore it to its previous state.\n *\n * @param options - Configuration object\n * @param options.operation - Async function to execute\n * @param options.spinner - Optional spinner instance to manage\n * @param options.wasSpinning - Whether spinner was spinning before\n * @returns Result of the operation\n * @throws Re-throws any error from operation after restoring spinner state\n *\n * @example\n * import { spinner, withSpinnerRestore } from '@socketsecurity/registry/lib/spinner'\n *\n * const wasSpinning = spinner.isSpinning\n * spinner.stop()\n *\n * const result = await withSpinnerRestore({\n * operation: async () => {\n * // Do work without spinner\n * return await someOperation()\n * },\n * spinner,\n * wasSpinning\n * })\n */\nexport async function withSpinnerRestore<T>(\n options: WithSpinnerRestoreOptions<T>,\n): Promise<T> {\n const { operation, spinner, wasSpinning } = {\n __proto__: null,\n ...options,\n } as WithSpinnerRestoreOptions<T>\n\n try {\n return await operation()\n } finally {\n if (spinner && wasSpinning) {\n spinner.start()\n }\n }\n}\n\nexport type WithSpinnerSyncOptions<T> = {\n message: string\n operation: () => T\n spinner?: Spinner | undefined\n}\n\n/**\n * Execute a synchronous operation with spinner lifecycle management.\n * Ensures spinner.stop() is always called via try/finally, even if the operation throws.\n *\n * @param options - Configuration object\n * @param options.message - Message to display while spinner is running\n * @param options.operation - Function to execute\n * @param options.spinner - Optional spinner instance (if not provided, no spinner is used)\n * @returns Result of the operation\n * @throws Re-throws any error from operation after stopping spinner\n *\n * @example\n * import { spinner, withSpinnerSync} from '@socketsecurity/registry/lib/spinner'\n *\n * const result = withSpinnerSync({\n * message: 'Processing\u2026',\n * operation: () => {\n * return processDataSync()\n * },\n * spinner\n * })\n */\nexport function withSpinnerSync<T>(options: WithSpinnerSyncOptions<T>): T {\n const { message, operation, spinner } = {\n __proto__: null,\n ...options,\n } as WithSpinnerSyncOptions<T>\n\n if (!spinner) {\n return operation()\n }\n\n spinner.start(message)\n try {\n return operation()\n } finally {\n spinner.stop()\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,gBAAmB;AACnB,0BAA4C;AAO5C,0BAAqD;AACrD,2BAAyB;AACzB,qBAAuB;AACvB,qBAA2C;AA6B3C,MAAM,aAA0C;AAAA,EAC9C,WAAW;AAAA,EACX,OAAO,CAAC,GAAG,GAAG,CAAC;AAAA,EACf,MAAM,CAAC,GAAG,GAAG,GAAG;AAAA,EAChB,YAAY,CAAC,KAAK,KAAK,GAAG;AAAA,EAC1B,MAAM,CAAC,GAAG,KAAK,GAAG;AAAA,EAClB,YAAY,CAAC,GAAG,KAAK,GAAG;AAAA,EACxB,MAAM,CAAC,KAAK,KAAK,GAAG;AAAA,E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,YAAM,QAAQ,aAAa,IAAwC;AACnE,aAAO,OAAO,UAAU,aAAa,MAAM,KAAK,YAAY,IAAI;AAAA,IAClE;AAAA,EACF,CAAC;AACH,GAAG;AAuCH,eAAsB,YACpB,SACY;AACZ,QAAM,EAAE,SAAS,WAAW,SAAAC,SAAQ,IAAI;AAAA,IACtC,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AAEA,MAAI,CAACA,UAAS;AACZ,WAAO,MAAM,UAAU;AAAA,EACzB;AAEA,EAAAA,SAAQ,MAAM,OAAO;AACrB,MAAI;AACF,WAAO,MAAM,UAAU;AAAA,EACzB,UAAE;AACA,IAAAA,SAAQ,KAAK;AAAA,EACf;AACF;AAmCA,eAAsB,mBACpB,SACY;AACZ,QAAM,EAAE,WAAW,SAAAA,UAAS,YAAY,IAAI;AAAA,IAC1C,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AAEA,MAAI;AACF,WAAO,MAAM,UAAU;AAAA,EACzB,UAAE;AACA,QAAIA,YAAW,aAAa;AAC1B,MAAAA,SAAQ,MAAM;AAAA,IAChB;AAAA,EACF;AACF;AA8BO,SAAS,gBAAmB,SAAuC;AACxE,QAAM,EAAE,SAAS,WAAW,SAAAA,SAAQ,IAAI;AAAA,IACtC,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AAEA,MAAI,CAACA,UAAS;AACZ,WAAO,UAAU;AAAA,EACnB;AAEA,EAAAA,SAAQ,MAAM,OAAO;AACrB,MAAI;AACF,WAAO,UAAU;AAAA,EACnB,UAAE;AACA,IAAAA,SAAQ,KAAK;AAAA,EACf;AACF;",
6
6
  "names": ["yoctoSpinner", "options", "spinner"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/streams.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Stream processing utilities with streaming-iterables integration.\n * Provides async stream handling and transformation functions.\n */\n\nimport type { IterationOptions } from './promises'\nimport { normalizeIterationOptions, pRetry } from './promises'\n\nlet _streamingIterables:\n | {\n parallelMap: <T, U>(\n concurrency: number,\n mapper: (item: T) => Promise<U>,\n iterable: Iterable<T> | AsyncIterable<T>,\n ) => AsyncIterable<U>\n transform: <T, U>(\n concurrency: number,\n mapper: (item: T) => Promise<U>,\n iterable: Iterable<T> | AsyncIterable<T>,\n ) => AsyncIterable<U>\n }\n | undefined\n/**\n * Get the streaming-iterables module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getStreamingIterables() {\n if (_streamingIterables === undefined) {\n _streamingIterables = /*@__PURE__*/ require('../external/streaming-iterables')\n }\n return _streamingIterables\n}\n\n/**\n * Execute a function for each item in an iterable in parallel.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function parallelEach<T>(\n iterable: Iterable<T> | AsyncIterable<T>,\n func: (item: T) => Promise<unknown>,\n options?: number | IterationOptions,\n): Promise<void> {\n for await (const _ of parallelMap(iterable, func, options)) {\n /* empty block */\n }\n}\n\n/**\n * Map over an iterable in parallel with concurrency control.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function parallelMap<T, U>(\n iterable: Iterable<T> | AsyncIterable<T>,\n func: (item: T) => Promise<U>,\n options?: number | IterationOptions,\n): AsyncIterable<U> {\n const streamingIterables = getStreamingIterables()\n const opts = normalizeIterationOptions(options)\n const result = streamingIterables?.parallelMap(\n opts.concurrency,\n async (item: T) => {\n const result = await pRetry((...args: unknown[]) => func(args[0] as T), {\n ...opts.retries,\n args: [item],\n })\n return result as U\n },\n iterable,\n )\n return result as AsyncIterable<U>\n}\n\n/**\n * Transform an iterable with a function.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function transform<T, U>(\n iterable: Iterable<T> | AsyncIterable<T>,\n func: (item: T) => Promise<U>,\n options?: number | IterationOptions,\n): AsyncIterable<U> {\n const streamingIterables = getStreamingIterables()\n const opts = normalizeIterationOptions(options)\n const result = streamingIterables?.transform(\n opts.concurrency,\n async (item: T) => {\n const result = await pRetry((...args: unknown[]) => func(args[0] as T), {\n ...opts.retries,\n args: [item],\n })\n return result as U\n },\n iterable,\n )\n return result as AsyncIterable<U>\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,sBAAkD;AAElD,IAAI;AAAA;AAmBJ,SAAS,wBAAwB;AAC/B,MAAI,wBAAwB,QAAW;AACrC,0BAAoC,QAAQ,iCAAiC;AAAA,EAC/E;AACA,SAAO;AACT;AAAA;AAMA,eAAsB,aACpB,UACA,MACA,SACe;AACf,mBAAiB,KAAK,4BAAY,UAAU,MAAM,OAAO,GAAG;AAAA,EAE5D;AACF;AAAA;AAMO,SAAS,YACd,UACA,MACA,SACkB;AAClB,QAAM,qBAAqB,sCAAsB;AACjD,QAAM,WAAO,2CAA0B,OAAO;AAC9C,QAAM,SAAS,oBAAoB;AAAA,IACjC,KAAK;AAAA,IACL,OAAO,SAAY;AACjB,YAAMA,UAAS,UAAM,wBAAO,IAAI,SAAoB,KAAK,KAAK,CAAC,CAAM,GAAG;AAAA,QACtE,GAAG,KAAK;AAAA,QACR,MAAM,CAAC,IAAI;AAAA,MACb,CAAC;AACD,aAAOA;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACA,SAAO;AACT;AAAA;AAMO,SAAS,UACd,UACA,MACA,SACkB;AAClB,QAAM,qBAAqB,sCAAsB;AACjD,QAAM,WAAO,2CAA0B,OAAO;AAC9C,QAAM,SAAS,oBAAoB;AAAA,IACjC,KAAK;AAAA,IACL,OAAO,SAAY;AACjB,YAAMA,UAAS,UAAM,wBAAO,IAAI,SAAoB,KAAK,KAAK,CAAC,CAAM,GAAG;AAAA,QACtE,GAAG,KAAK;AAAA,QACR,MAAM,CAAC,IAAI;AAAA,MACb,CAAC;AACD,aAAOA;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * @fileoverview Stream processing utilities with streaming-iterables integration.\n * Provides async stream handling and transformation functions.\n */\n\nimport type { IterationOptions } from './promises'\nimport { normalizeIterationOptions, pRetry } from './promises'\n\nlet _streamingIterables:\n | {\n parallelMap: <T, U>(\n concurrency: number,\n mapper: (item: T) => Promise<U>,\n iterable: Iterable<T> | AsyncIterable<T>,\n ) => AsyncIterable<U>\n transform: <T, U>(\n concurrency: number,\n mapper: (item: T) => Promise<U>,\n iterable: Iterable<T> | AsyncIterable<T>,\n ) => AsyncIterable<U>\n }\n | undefined\n/**\n * Get the streaming-iterables module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getStreamingIterables() {\n if (_streamingIterables === undefined) {\n _streamingIterables = /*@__PURE__*/ require('./external/streaming-iterables')\n }\n return _streamingIterables\n}\n\n/**\n * Execute a function for each item in an iterable in parallel.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function parallelEach<T>(\n iterable: Iterable<T> | AsyncIterable<T>,\n func: (item: T) => Promise<unknown>,\n options?: number | IterationOptions,\n): Promise<void> {\n for await (const _ of parallelMap(iterable, func, options)) {\n /* empty block */\n }\n}\n\n/**\n * Map over an iterable in parallel with concurrency control.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function parallelMap<T, U>(\n iterable: Iterable<T> | AsyncIterable<T>,\n func: (item: T) => Promise<U>,\n options?: number | IterationOptions,\n): AsyncIterable<U> {\n const streamingIterables = getStreamingIterables()\n const opts = normalizeIterationOptions(options)\n const result = streamingIterables?.parallelMap(\n opts.concurrency,\n async (item: T) => {\n const result = await pRetry((...args: unknown[]) => func(args[0] as T), {\n ...opts.retries,\n args: [item],\n })\n return result as U\n },\n iterable,\n )\n return result as AsyncIterable<U>\n}\n\n/**\n * Transform an iterable with a function.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function transform<T, U>(\n iterable: Iterable<T> | AsyncIterable<T>,\n func: (item: T) => Promise<U>,\n options?: number | IterationOptions,\n): AsyncIterable<U> {\n const streamingIterables = getStreamingIterables()\n const opts = normalizeIterationOptions(options)\n const result = streamingIterables?.transform(\n opts.concurrency,\n async (item: T) => {\n const result = await pRetry((...args: unknown[]) => func(args[0] as T), {\n ...opts.retries,\n args: [item],\n })\n return result as U\n },\n iterable,\n )\n return result as AsyncIterable<U>\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,sBAAkD;AAElD,IAAI;AAAA;AAmBJ,SAAS,wBAAwB;AAC/B,MAAI,wBAAwB,QAAW;AACrC,0BAAoC,QAAQ,gCAAgC;AAAA,EAC9E;AACA,SAAO;AACT;AAAA;AAMA,eAAsB,aACpB,UACA,MACA,SACe;AACf,mBAAiB,KAAK,4BAAY,UAAU,MAAM,OAAO,GAAG;AAAA,EAE5D;AACF;AAAA;AAMO,SAAS,YACd,UACA,MACA,SACkB;AAClB,QAAM,qBAAqB,sCAAsB;AACjD,QAAM,WAAO,2CAA0B,OAAO;AAC9C,QAAM,SAAS,oBAAoB;AAAA,IACjC,KAAK;AAAA,IACL,OAAO,SAAY;AACjB,YAAMA,UAAS,UAAM,wBAAO,IAAI,SAAoB,KAAK,KAAK,CAAC,CAAM,GAAG;AAAA,QACtE,GAAG,KAAK;AAAA,QACR,MAAM,CAAC,IAAI;AAAA,MACb,CAAC;AACD,aAAOA;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACA,SAAO;AACT;AAAA;AAMO,SAAS,UACd,UACA,MACA,SACkB;AAClB,QAAM,qBAAqB,sCAAsB;AACjD,QAAM,WAAO,2CAA0B,OAAO;AAC9C,QAAM,SAAS,oBAAoB;AAAA,IACjC,KAAK;AAAA,IACL,OAAO,SAAY;AACjB,YAAMA,UAAS,UAAM,wBAAO,IAAI,SAAoB,KAAK,KAAK,CAAC,CAAM,GAAG;AAAA,QACtE,GAAG,KAAK;AAAA,QACR,MAAM,CAAC,IAAI;AAAA,MACb,CAAC;AACD,aAAOA;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACA,SAAO;AACT;",
6
6
  "names": ["result"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@socketsecurity/lib",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "license": "MIT",
5
5
  "description": "Core utilities and infrastructure for Socket.dev security tools",
6
6
  "keywords": [