@socketsecurity/cli-with-sentry 0.14.129 → 0.14.131

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.
Files changed (59) hide show
  1. package/bin/cli.js +37 -44
  2. package/bin/npx-cli.js +1 -3
  3. package/dist/{module-sync/cli.js → cli.js} +336 -338
  4. package/dist/cli.js.map +1 -0
  5. package/dist/constants.js +8 -25
  6. package/dist/constants.js.map +1 -1
  7. package/dist/instrument-with-sentry.js +3 -14
  8. package/dist/instrument-with-sentry.js.map +1 -1
  9. package/dist/{module-sync/shadow-bin.js → shadow-bin.js} +52 -1
  10. package/dist/shadow-bin.js.map +1 -0
  11. package/dist/{module-sync/shadow-npm-inject.js → shadow-npm-inject.js} +67 -48
  12. package/dist/shadow-npm-inject.js.map +1 -0
  13. package/dist/shadow-npm-paths.js.map +1 -0
  14. package/dist/{module-sync/vendor.js → vendor.js} +10320 -4778
  15. package/dist/vendor.js.map +1 -0
  16. package/package.json +16 -26
  17. package/dist/constants.d.ts +0 -285
  18. package/dist/instrument-with-sentry.d.ts +0 -1
  19. package/dist/module-sync/arborist-helpers.d.ts +0 -69
  20. package/dist/module-sync/artifact.d.ts +0 -63
  21. package/dist/module-sync/cli.d.ts +0 -2
  22. package/dist/module-sync/cli.js.map +0 -1
  23. package/dist/module-sync/cmd.d.ts +0 -4
  24. package/dist/module-sync/config.d.ts +0 -44
  25. package/dist/module-sync/constants.js +0 -3
  26. package/dist/module-sync/edge.d.ts +0 -78
  27. package/dist/module-sync/errors.d.ts +0 -29
  28. package/dist/module-sync/fs.d.ts +0 -63
  29. package/dist/module-sync/index.d.ts +0 -34
  30. package/dist/module-sync/node.d.ts +0 -121
  31. package/dist/module-sync/override-set.d.ts +0 -43
  32. package/dist/module-sync/package-environment.d.ts +0 -83
  33. package/dist/module-sync/path-resolve.d.ts +0 -15
  34. package/dist/module-sync/sdk.d.ts +0 -9
  35. package/dist/module-sync/semver.d.ts +0 -17
  36. package/dist/module-sync/shadow-bin.d.ts +0 -5
  37. package/dist/module-sync/shadow-bin.js.map +0 -1
  38. package/dist/module-sync/shadow-npm-inject.d.ts +0 -1
  39. package/dist/module-sync/shadow-npm-inject.js.map +0 -1
  40. package/dist/module-sync/shadow-npm-paths.d.ts +0 -27
  41. package/dist/module-sync/shadow-npm-paths.js.map +0 -1
  42. package/dist/module-sync/socket-package-alert.d.ts +0 -104
  43. package/dist/module-sync/vendor.d.ts +0 -0
  44. package/dist/module-sync/vendor.js.map +0 -1
  45. package/dist/require/cli.d.ts +0 -2
  46. package/dist/require/cli.js +0 -12361
  47. package/dist/require/cli.js.map +0 -1
  48. package/dist/require/constants.js +0 -3
  49. package/dist/require/shadow-bin.d.ts +0 -5
  50. package/dist/require/shadow-bin.js +0 -110
  51. package/dist/require/shadow-bin.js.map +0 -1
  52. package/dist/require/shadow-npm-inject.d.ts +0 -1
  53. package/dist/require/shadow-npm-inject.js +0 -2616
  54. package/dist/require/shadow-npm-inject.js.map +0 -1
  55. package/dist/require/shadow-npm-paths.d.ts +0 -27
  56. package/dist/require/shadow-npm-paths.js +0 -292
  57. package/dist/require/shadow-npm-paths.js.map +0 -1
  58. package/dist/require/vendor.js +0 -3
  59. /package/dist/{module-sync/shadow-npm-paths.js → shadow-npm-paths.js} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shadow-npm-inject.js","sources":["../src/utils/glob.ts","../src/utils/fs.ts","../src/utils/config.ts","../src/utils/errors.ts","../src/utils/sdk.ts","../src/utils/semver.ts","../src/shadow/npm/arborist/lib/arborist/types.ts","../src/shadow/npm/arborist/lib/dep-valid.ts","../src/shadow/npm/proc-log/index.ts","../src/shadow/npm/arborist/lib/override-set.ts","../src/shadow/npm/arborist/lib/node.ts","../src/shadow/npm/arborist/lib/edge.ts","../src/utils/arborist-helpers.ts","../src/utils/alert/artifact.ts","../src/utils/alert/fix.ts","../src/utils/objects.ts","../src/utils/strings.ts","../src/utils/alert/severity.ts","../src/utils/color-or-markdown.ts","../src/utils/socket-url.ts","../src/utils/translations.ts","../src/utils/socket-package-alert.ts","../src/utils/alerts-map.ts","../src/shadow/npm/arborist/lib/arborist/index.ts","../src/shadow/npm/arborist/index.ts","../src/shadow/npm/inject.ts"],"sourcesContent":["import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport ignore from 'ignore'\nimport micromatch from 'micromatch'\nimport { glob as tinyGlob } from 'tinyglobby'\nimport { parse as yamlParse } from 'yaml'\n\nimport { readPackageJson } from '@socketsecurity/registry/lib/packages'\nimport { isNonEmptyString } from '@socketsecurity/registry/lib/strings'\n\nimport constants from '../constants'\nimport { safeReadFile } from './fs'\n\nimport type { Agent } from './package-environment'\nimport type { SocketYml } from '@socketsecurity/config'\nimport type { SocketSdkReturnType } from '@socketsecurity/sdk'\nimport type { GlobOptions } from 'tinyglobby'\n\nconst { NPM, PNPM } = constants\n\nconst PNPM_WORKSPACE = `${PNPM}-workspace`\n\nconst ignoredDirs = [\n // Taken from ignore-by-default:\n // https://github.com/novemberborn/ignore-by-default/blob/v2.1.0/index.js\n '.git', // Git repository files, see <https://git-scm.com/>\n '.log', // Log files emitted by tools such as `tsserver`, see <https://github.com/Microsoft/TypeScript/wiki/Standalone-Server-%28tsserver%29>\n '.nyc_output', // Temporary directory where nyc stores coverage data, see <https://github.com/bcoe/nyc>\n '.sass-cache', // Cache folder for node-sass, see <https://github.com/sass/node-sass>\n '.yarn', // Where node modules are installed when using Yarn, see <https://yarnpkg.com/>\n 'bower_components', // Where Bower packages are installed, see <http://bower.io/>\n 'coverage', // Standard output directory for code coverage reports, see <https://github.com/gotwarlost/istanbul>\n 'node_modules', // Where Node modules are installed, see <https://nodejs.org/>\n // Taken from globby:\n // https://github.com/sindresorhus/globby/blob/v14.0.2/ignore.js#L11-L16\n 'flow-typed'\n] as const\n\nconst ignoredDirPatterns = ignoredDirs.map(i => `**/${i}`)\n\nasync function getWorkspaceGlobs(\n agent: Agent,\n cwd = process.cwd()\n): Promise<string[]> {\n let workspacePatterns\n if (agent === PNPM) {\n for (const workspacePath of [\n path.join(cwd, `${PNPM_WORKSPACE}.yaml`),\n path.join(cwd, `${PNPM_WORKSPACE}.yml`)\n ]) {\n // eslint-disable-next-line no-await-in-loop\n const yml = await safeReadFile(workspacePath)\n if (yml) {\n try {\n workspacePatterns = yamlParse(yml)?.packages\n } catch {}\n if (workspacePatterns) {\n break\n }\n }\n }\n } else {\n workspacePatterns = (await readPackageJson(cwd, { throws: false }))?.[\n 'workspaces'\n ]\n }\n return Array.isArray(workspacePatterns)\n ? workspacePatterns\n .filter(isNonEmptyString)\n .map(workspacePatternToGlobPattern)\n : []\n}\n\nfunction ignoreFileLinesToGlobPatterns(\n lines: string[] | readonly string[],\n filepath: string,\n cwd: string\n): string[] {\n const base = path.relative(cwd, path.dirname(filepath)).replace(/\\\\/g, '/')\n const patterns = []\n for (let i = 0, { length } = lines; i < length; i += 1) {\n const pattern = lines[i]!.trim()\n if (pattern.length > 0 && pattern.charCodeAt(0) !== 35 /*'#'*/) {\n patterns.push(\n ignorePatternToMinimatch(\n pattern.length && pattern.charCodeAt(0) === 33 /*'!'*/\n ? `!${path.posix.join(base, pattern.slice(1))}`\n : path.posix.join(base, pattern)\n )\n )\n }\n }\n return patterns\n}\n\nfunction ignoreFileToGlobPatterns(\n content: string,\n filepath: string,\n cwd: string\n): string[] {\n return ignoreFileLinesToGlobPatterns(content.split(/\\r?\\n/), filepath, cwd)\n}\n\n// Based on `@eslint/compat` convertIgnorePatternToMinimatch.\n// Apache v2.0 licensed\n// Copyright Nicholas C. Zakas\n// https://github.com/eslint/rewrite/blob/compat-v1.2.1/packages/compat/src/ignore-file.js#L28\nfunction ignorePatternToMinimatch(pattern: string): string {\n const isNegated = pattern.startsWith('!')\n const negatedPrefix = isNegated ? '!' : ''\n const patternToTest = (isNegated ? pattern.slice(1) : pattern).trimEnd()\n // Special cases.\n if (\n patternToTest === '' ||\n patternToTest === '**' ||\n patternToTest === '/**' ||\n patternToTest === '**'\n ) {\n return `${negatedPrefix}${patternToTest}`\n }\n const firstIndexOfSlash = patternToTest.indexOf('/')\n const matchEverywherePrefix =\n firstIndexOfSlash === -1 || firstIndexOfSlash === patternToTest.length - 1\n ? '**/'\n : ''\n const patternWithoutLeadingSlash =\n firstIndexOfSlash === 0 ? patternToTest.slice(1) : patternToTest\n // Escape `{` and `(` because in gitignore patterns they are just\n // literal characters without any specific syntactic meaning,\n // while in minimatch patterns they can form brace expansion or extglob syntax.\n //\n // For example, gitignore pattern `src/{a,b}.js` ignores file `src/{a,b}.js`.\n // But, the same minimatch pattern `src/{a,b}.js` ignores files `src/a.js` and `src/b.js`.\n // Minimatch pattern `src/\\{a,b}.js` is equivalent to gitignore pattern `src/{a,b}.js`.\n const escapedPatternWithoutLeadingSlash =\n patternWithoutLeadingSlash.replaceAll(\n /(?=((?:\\\\.|[^{(])*))\\1([{(])/guy,\n '$1\\\\$2'\n )\n const matchInsideSuffix = patternToTest.endsWith('/**') ? '/*' : ''\n return `${negatedPrefix}${matchEverywherePrefix}${escapedPatternWithoutLeadingSlash}${matchInsideSuffix}`\n}\n\nfunction workspacePatternToGlobPattern(workspace: string): string {\n const { length } = workspace\n if (!length) {\n return ''\n }\n // If the workspace ends with \"/\"\n if (workspace.charCodeAt(length - 1) === 47 /*'/'*/) {\n return `${workspace}/*/package.json`\n }\n // If the workspace ends with \"/**\"\n if (\n workspace.charCodeAt(length - 1) === 42 /*'*'*/ &&\n workspace.charCodeAt(length - 2) === 42 /*'*'*/ &&\n workspace.charCodeAt(length - 3) === 47 /*'/'*/\n ) {\n return `${workspace}/*/**/package.json`\n }\n // Things like \"packages/a\" or \"packages/*\"\n return `${workspace}/package.json`\n}\n\nexport async function filterGlobResultToSupportedFiles(\n entries: string[] | readonly string[],\n supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data']\n): Promise<string[]> {\n const patterns = ['golang', NPM, 'maven', 'pypi', 'gem', 'nuget'].reduce(\n (r: string[], n: string) => {\n const supported = supportedFiles[n]\n r.push(\n ...(supported\n ? Object.values(supported).map(p => `**/${p.pattern}`)\n : [])\n )\n return r\n },\n []\n )\n return entries.filter(p => micromatch.some(p, patterns))\n}\n\ntype GlobWithGitIgnoreOptions = GlobOptions & {\n socketConfig?: SocketYml | undefined\n}\n\nexport async function globWithGitIgnore(\n patterns: string[] | readonly string[],\n options: GlobWithGitIgnoreOptions\n) {\n const {\n cwd = process.cwd(),\n socketConfig,\n ...additionalOptions\n } = { __proto__: null, ...options } as GlobWithGitIgnoreOptions\n const projectIgnorePaths = socketConfig?.projectIgnorePaths\n const ignoreFiles = await tinyGlob(['**/.gitignore'], {\n absolute: true,\n cwd,\n expandDirectories: true\n })\n const ignores = [\n ...ignoredDirPatterns,\n ...(Array.isArray(projectIgnorePaths)\n ? ignoreFileLinesToGlobPatterns(\n projectIgnorePaths,\n path.join(cwd, '.gitignore'),\n cwd\n )\n : []),\n ...(\n await Promise.all(\n ignoreFiles.map(async filepath =>\n ignoreFileToGlobPatterns(\n await fs.readFile(filepath, 'utf8'),\n filepath,\n cwd\n )\n )\n )\n ).flat()\n ]\n const hasNegatedPattern = ignores.some(p => p.charCodeAt(0) === 33 /*'!'*/)\n const globOptions = {\n absolute: true,\n cwd,\n expandDirectories: false,\n ignore: hasNegatedPattern ? [] : ignores,\n ...additionalOptions\n }\n const result = await tinyGlob(patterns as string[], globOptions)\n if (!hasNegatedPattern) {\n return result\n }\n const { absolute } = globOptions\n\n // Note: the input files must be INSIDE the cwd. If you get strange looking\n // relative path errors here, most likely your path is outside the given cwd.\n const filtered = ignore()\n .add(ignores)\n .filter(absolute ? result.map(p => path.relative(cwd, p)) : result)\n return absolute ? filtered.map(p => path.resolve(cwd, p)) : filtered\n}\n\nexport async function globNodeModules(cwd = process.cwd()): Promise<string[]> {\n return await tinyGlob('**/node_modules/**', {\n absolute: true,\n cwd\n })\n}\n\nexport async function globWorkspace(\n agent: Agent,\n cwd = process.cwd()\n): Promise<string[]> {\n const workspaceGlobs = await getWorkspaceGlobs(agent, cwd)\n return workspaceGlobs.length\n ? await tinyGlob(workspaceGlobs, {\n absolute: true,\n cwd,\n ignore: ['**/node_modules/**', '**/bower_components/**']\n })\n : []\n}\n\nexport function pathsToGlobPatterns(\n paths: string[] | readonly string[]\n): string[] {\n // TODO: Does not support `~/` paths.\n return paths.map(p => (p === '.' || p === './' ? '**/*' : p))\n}\n","import { promises as fs, readFileSync as fsReadFileSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { remove } from '@socketsecurity/registry/lib/fs'\n\nimport constants from '../constants'\nimport { globNodeModules } from './glob'\n\nimport type { Remap } from '@socketsecurity/registry/lib/objects'\nimport type { Abortable } from 'node:events'\nimport type {\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n PathOrFileDescriptor\n} from 'node:fs'\nimport type { FileHandle } from 'node:fs/promises'\n\nconst { abortSignal } = constants\n\nexport async function removeNodeModules(cwd = process.cwd()) {\n const nodeModulesPaths = await globNodeModules(cwd)\n await Promise.all(nodeModulesPaths.map(p => remove(p)))\n}\n\nexport type FindUpOptions = {\n cwd?: string | undefined\n signal?: AbortSignal | undefined\n}\n\nexport async function findUp(\n name: string | string[],\n { cwd = process.cwd(), signal = abortSignal }: FindUpOptions\n): Promise<string | undefined> {\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const names = [name].flat()\n while (dir && dir !== root) {\n for (const name of names) {\n if (signal?.aborted) {\n return undefined\n }\n const filePath = path.join(dir, name)\n try {\n // eslint-disable-next-line no-await-in-loop\n const stats = await fs.stat(filePath)\n if (stats.isFile()) {\n return filePath\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\nexport type ReadFileOptions = Remap<\n ObjectEncodingOptions &\n Abortable & {\n flag?: OpenMode | undefined\n }\n>\n\nexport async function readFileBinary(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | undefined\n): Promise<Buffer> {\n return (await fs.readFile(filepath, {\n signal: abortSignal,\n ...options,\n encoding: 'binary'\n } as ReadFileOptions)) as Buffer\n}\n\nexport async function readFileUtf8(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | undefined\n): Promise<string> {\n return await fs.readFile(filepath, {\n signal: abortSignal,\n ...options,\n encoding: 'utf8'\n })\n}\n\nexport async function safeReadFile(\n filepath: PathLike | FileHandle,\n options?: 'utf8' | 'utf-8' | { encoding: 'utf8' | 'utf-8' } | undefined\n): Promise<string | undefined>\n\nexport async function safeReadFile(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | NodeJS.BufferEncoding | undefined\n): Promise<Awaited<ReturnType<typeof fs.readFile>> | undefined> {\n try {\n return await fs.readFile(filepath, {\n encoding: 'utf8',\n signal: abortSignal,\n ...(typeof options === 'string' ? { encoding: options } : options)\n })\n } catch {}\n return undefined\n}\n\nexport function safeReadFileSync(\n filepath: PathOrFileDescriptor,\n options?: 'utf8' | 'utf-8' | { encoding: 'utf8' | 'utf-8' } | undefined\n): string | undefined\n\nexport function safeReadFileSync(\n filepath: PathOrFileDescriptor,\n options?:\n | {\n encoding?: NodeJS.BufferEncoding | undefined\n flag?: string | undefined\n }\n | NodeJS.BufferEncoding\n | undefined\n): ReturnType<typeof fsReadFileSync> | undefined {\n try {\n return fsReadFileSync(filepath, {\n encoding: 'utf8',\n ...(typeof options === 'string' ? { encoding: options } : options)\n })\n } catch {}\n return undefined\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport config from '@socketsecurity/config'\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\nimport { logger } from '@socketsecurity/registry/lib/logger'\n\nimport { safeReadFileSync } from './fs'\nimport constants from '../constants'\n\nconst { LOCALAPPDATA, SOCKET_APP_DIR, XDG_DATA_HOME } = constants\n\nexport interface LocalConfig {\n apiBaseUrl?: string | null | undefined\n // @deprecated ; use apiToken. when loading a config, if this prop exists it\n // is deleted and set to apiToken instead, and then persisted.\n // should only happen once for legacy users.\n apiKey?: string | null | undefined\n apiProxy?: string | null | undefined\n apiToken?: string | null | undefined\n defaultOrg?: string\n enforcedOrgs?: string[] | readonly string[] | null | undefined\n}\n\nexport const supportedConfigKeys: Map<keyof LocalConfig, string> = new Map([\n ['apiBaseUrl', 'Base URL of the API endpoint'],\n ['apiProxy', 'A proxy through which to access the API'],\n ['apiToken', 'The API token required to access most API endpoints'],\n [\n 'defaultOrg',\n 'The default org slug to use; usually the org your API token has access to. When set, all orgSlug arguments are implied to be this value.'\n ],\n [\n 'enforcedOrgs',\n 'Orgs in this list have their security policies enforced on this machine'\n ]\n])\n\nexport const sensitiveConfigKeys: Set<keyof LocalConfig> = new Set(['apiToken'])\n\nlet _cachedConfig: LocalConfig | undefined\n// When using --config or SOCKET_CLI_CONFIG, do not persist the config.\nlet _readOnlyConfig = false\n\nexport function overrideCachedConfig(\n jsonConfig: unknown\n): { ok: true; message: undefined } | { ok: false; message: string } {\n debugLog('Overriding entire config, marking config as read-only')\n\n let config\n try {\n config = JSON.parse(String(jsonConfig))\n if (!config || typeof config !== 'object') {\n // Just throw to reuse the error message. `null` is valid json,\n // so are primitive values. They're not valid config objects :)\n throw new Error()\n }\n } catch {\n return {\n ok: false,\n message:\n \"Could not JSON parse the config override. Make sure it's a proper JSON object (double-quoted keys and strings, no unquoted `undefined`) and try again.\"\n }\n }\n\n // @ts-ignore Override an illegal object.\n _cachedConfig = config as LocalConfig\n _readOnlyConfig = true\n\n // Normalize apiKey to apiToken.\n if (_cachedConfig['apiKey']) {\n if (_cachedConfig['apiToken']) {\n logger.warn(\n 'Note: The config override had both apiToken and apiKey. Using the apiToken value. Remove the apiKey to get rid of this message.'\n )\n }\n _cachedConfig['apiToken'] = _cachedConfig['apiKey']\n delete _cachedConfig['apiKey']\n }\n\n return { ok: true, message: undefined }\n}\n\nexport function overrideConfigApiToken(apiToken: unknown) {\n debugLog('Overriding API token, marking config as read-only')\n // Set token to the local cached config and mark it read-only so it doesn't persist\n _cachedConfig = {\n ...config,\n ...(apiToken === undefined ? {} : { apiToken: String(apiToken) })\n } as LocalConfig\n _readOnlyConfig = true\n}\n\nfunction getConfigValues(): LocalConfig {\n if (_cachedConfig === undefined) {\n _cachedConfig = {} as LocalConfig\n // Order: env var > --config flag > file\n const configPath = getConfigPath()\n if (configPath) {\n const raw = safeReadFileSync(configPath)\n if (raw) {\n try {\n Object.assign(\n _cachedConfig,\n JSON.parse(Buffer.from(raw, 'base64').toString())\n )\n } catch {\n logger.warn(`Failed to parse config at ${configPath}`)\n }\n // Normalize apiKey to apiToken and persist it.\n // This is a one time migration per user.\n if (_cachedConfig['apiKey']) {\n const token = _cachedConfig['apiKey']\n delete _cachedConfig['apiKey']\n updateConfigValue('apiToken', token)\n }\n } else {\n fs.mkdirSync(path.dirname(configPath), { recursive: true })\n }\n }\n }\n return _cachedConfig\n}\n\nlet _configPath: string | undefined\nlet _warnedConfigPathWin32Missing = false\nfunction getConfigPath(): string | undefined {\n // Get the OS app data folder:\n // - Win: %LOCALAPPDATA% or fail?\n // - Mac: %XDG_DATA_HOME% or fallback to \"~/Library/Application Support/\"\n // - Linux: %XDG_DATA_HOME% or fallback to \"~/.local/share/\"\n // Note: LOCALAPPDATA is typically: C:\\Users\\USERNAME\\AppData\n // Note: XDG stands for \"X Desktop Group\", nowadays \"freedesktop.org\"\n // On most systems that path is: $HOME/.local/share\n // Then append `socket/settings`, so:\n // - Win: %LOCALAPPDATA%\\socket\\settings or return undefined\n // - Mac: %XDG_DATA_HOME%/socket/settings or \"~/Library/Application Support/socket/settings\"\n // - Linux: %XDG_DATA_HOME%/socket/settings or \"~/.local/share/socket/settings\"\n\n if (_configPath === undefined) {\n // Lazily access constants.WIN32.\n const { WIN32 } = constants\n let dataHome: string | undefined = WIN32\n ? // Lazily access constants.ENV[LOCALAPPDATA]\n constants.ENV[LOCALAPPDATA]\n : // Lazily access constants.ENV[XDG_DATA_HOME]\n constants.ENV[XDG_DATA_HOME]\n if (!dataHome) {\n if (WIN32) {\n if (!_warnedConfigPathWin32Missing) {\n _warnedConfigPathWin32Missing = true\n logger.warn(`Missing %${LOCALAPPDATA}%`)\n }\n } else {\n dataHome = path.join(\n os.homedir(),\n ...(process.platform === 'darwin'\n ? ['Library', 'Application Support']\n : ['.local', 'share'])\n )\n }\n }\n _configPath = dataHome ? path.join(dataHome, SOCKET_APP_DIR) : undefined\n }\n return _configPath\n}\n\nfunction normalizeConfigKey(key: keyof LocalConfig): keyof LocalConfig {\n // Note: apiKey was the old name of the token. When we load a config with\n // property apiKey, we'll copy that to apiToken and delete the old property.\n const normalizedKey = key === 'apiKey' ? 'apiToken' : key\n if (!supportedConfigKeys.has(normalizedKey)) {\n throw new Error(`Invalid config key: ${normalizedKey}`)\n }\n return normalizedKey\n}\n\nexport function findSocketYmlSync(dir = process.cwd()) {\n let prevDir = null\n while (dir !== prevDir) {\n let ymlPath = path.join(dir, 'socket.yml')\n let yml = safeReadFileSync(ymlPath)\n if (yml === undefined) {\n ymlPath = path.join(dir, 'socket.yaml')\n yml = safeReadFileSync(ymlPath)\n }\n if (typeof yml === 'string') {\n try {\n return {\n path: ymlPath,\n parsed: config.parseSocketConfig(yml)\n }\n } catch {\n throw new Error(`Found file but was unable to parse ${ymlPath}`)\n }\n }\n prevDir = dir\n dir = path.join(dir, '..')\n }\n return null\n}\n\nexport function getConfigValue<Key extends keyof LocalConfig>(\n key: Key\n): LocalConfig[Key] {\n const localConfig = getConfigValues()\n return localConfig[normalizeConfigKey(key)] as LocalConfig[Key]\n}\nexport function isReadOnlyConfig() {\n return _readOnlyConfig\n}\n\nlet _pendingSave = false\nexport function updateConfigValue<Key extends keyof LocalConfig>(\n key: keyof LocalConfig,\n value: LocalConfig[Key]\n): void {\n const localConfig = getConfigValues()\n localConfig[normalizeConfigKey(key) as Key] = value\n if (_readOnlyConfig) {\n logger.warn(\n 'Not persisting config change; current config overridden through env var or flag'\n )\n } else if (!_pendingSave) {\n _pendingSave = true\n process.nextTick(() => {\n _pendingSave = false\n const configPath = getConfigPath()\n if (configPath) {\n fs.writeFileSync(\n configPath,\n Buffer.from(JSON.stringify(localConfig)).toString('base64')\n )\n }\n })\n }\n}\n","import { setTimeout as wait } from 'node:timers/promises'\n\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\n\nimport constants from '../constants'\n\nconst {\n kInternalsSymbol,\n [kInternalsSymbol as unknown as 'Symbol(kInternalsSymbol)']: { getSentry }\n} = constants\n\ntype EventHintOrCaptureContext = { [key: string]: any } | Function\n\nexport class AuthError extends Error {}\n\nexport class InputError extends Error {\n public body: string | undefined\n\n constructor(message: string, body?: string) {\n super(message)\n this.body = body\n }\n}\n\nexport async function captureException(\n exception: unknown,\n hint?: EventHintOrCaptureContext | undefined\n): Promise<string> {\n const result = captureExceptionSync(exception, hint)\n // \"Sleep\" for a second, just in case, hopefully enough time to initiate fetch.\n await wait(1000)\n return result\n}\n\nexport function captureExceptionSync(\n exception: unknown,\n hint?: EventHintOrCaptureContext | undefined\n): string {\n const Sentry = getSentry()\n if (!Sentry) {\n return ''\n }\n debugLog('captureException: Sending exception to Sentry')\n return Sentry.captureException(exception, hint) as string\n}\n\nexport function isErrnoException(\n value: unknown\n): value is NodeJS.ErrnoException {\n if (!(value instanceof Error)) {\n return false\n }\n return (value as NodeJS.ErrnoException).code !== undefined\n}\n","import process from 'node:process'\n\nimport { HttpsProxyAgent } from 'hpagent'\n\nimport isInteractive from '@socketregistry/is-interactive/index.cjs'\nimport { SOCKET_PUBLIC_API_TOKEN } from '@socketsecurity/registry/lib/constants'\nimport { password } from '@socketsecurity/registry/lib/prompts'\nimport { isNonEmptyString } from '@socketsecurity/registry/lib/strings'\nimport { SocketSdk, createUserAgentFromPkgJson } from '@socketsecurity/sdk'\n\nimport { getConfigValue } from './config'\nimport { AuthError } from './errors'\nimport constants from '../constants'\n\nconst {\n SOCKET_CLI_NO_API_TOKEN,\n SOCKET_SECURITY_API_BASE_URL,\n SOCKET_SECURITY_API_PROXY,\n SOCKET_SECURITY_API_TOKEN\n} = constants\n\n// The API server that should be used for operations.\nfunction getDefaultApiBaseUrl(): string | undefined {\n const baseUrl =\n // Lazily access constants.ENV[SOCKET_SECURITY_API_BASE_URL].\n constants.ENV[SOCKET_SECURITY_API_BASE_URL] || getConfigValue('apiBaseUrl')\n return isNonEmptyString(baseUrl) ? baseUrl : undefined\n}\n\n// The API server that should be used for operations.\nfunction getDefaultHttpProxy(): string | undefined {\n const apiProxy =\n // Lazily access constants.ENV[SOCKET_SECURITY_API_PROXY].\n constants.ENV[SOCKET_SECURITY_API_PROXY] || getConfigValue('apiProxy')\n return isNonEmptyString(apiProxy) ? apiProxy : undefined\n}\n\n// This API key should be stored globally for the duration of the CLI execution.\nlet _defaultToken: string | undefined\nexport function getDefaultToken(): string | undefined {\n // Lazily access constants.ENV[SOCKET_CLI_NO_API_TOKEN].\n if (constants.ENV[SOCKET_CLI_NO_API_TOKEN]) {\n _defaultToken = undefined\n } else {\n const key =\n // Lazily access constants.ENV[SOCKET_SECURITY_API_TOKEN].\n constants.ENV[SOCKET_SECURITY_API_TOKEN] ||\n getConfigValue('apiToken') ||\n _defaultToken\n _defaultToken = isNonEmptyString(key) ? key : undefined\n }\n return _defaultToken\n}\n\nexport function getPublicToken(): string {\n return (\n // Lazily access constants.ENV[SOCKET_SECURITY_API_TOKEN].\n (constants.ENV[SOCKET_SECURITY_API_TOKEN] || getDefaultToken()) ??\n SOCKET_PUBLIC_API_TOKEN\n )\n}\n\nexport async function setupSdk(\n apiToken: string | undefined = getDefaultToken(),\n apiBaseUrl: string | undefined = getDefaultApiBaseUrl(),\n proxy: string | undefined = getDefaultHttpProxy()\n): Promise<SocketSdk> {\n if (typeof apiToken !== 'string' && isInteractive()) {\n apiToken = await password({\n message:\n 'Enter your Socket.dev API key (not saved, use socket login to persist)'\n })\n _defaultToken = apiToken\n }\n if (!apiToken) {\n throw new AuthError('You need to provide an API key')\n }\n return new SocketSdk(apiToken, {\n agent: proxy ? new HttpsProxyAgent({ proxy }) : undefined,\n baseUrl: apiBaseUrl,\n userAgent: createUserAgentFromPkgJson({\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_NAME']\".\n name: process.env['INLINED_SOCKET_CLI_NAME'] as string,\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_VERSION']\".\n version: process.env['INLINED_SOCKET_CLI_VERSION'] as string,\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_HOMEPAGE']\".\n homepage: process.env['INLINED_SOCKET_CLI_HOMEPAGE'] as string\n })\n })\n}\n","import semver from 'semver'\n\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\n\nexport const RangeStyles = ['caret', 'gt', 'lt', 'pin', 'preserve', 'tilde']\n\nexport type RangeStyle =\n | 'caret'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'pin'\n | 'preserve'\n | 'tilde'\n\nexport function applyRange(\n refRange: string,\n version: string,\n style: RangeStyle = 'preserve'\n): string {\n switch (style) {\n case 'caret':\n return `^${version}`\n case 'gt':\n return `>${version}`\n case 'gte':\n return `>=${version}`\n case 'lt':\n return `<${version}`\n case 'lte':\n return `<=${version}`\n case 'preserve': {\n const comparators = [...new semver.Range(refRange).set].flat()\n const { length } = comparators\n return !length || length > 1\n ? version\n : `${comparators[0]!.operator}${version}`\n }\n case 'tilde':\n return `~${version}`\n case 'pin':\n default:\n return version\n }\n}\n\nexport function getMajor(version: string): number | null {\n const coerced = semver.coerce(version)\n if (coerced) {\n try {\n return semver.major(coerced)\n } catch (e) {\n debugLog(`Error parsing '${version}'`, e)\n }\n }\n return null\n}\n","import type { SafeNode } from '../node'\nimport type {\n Options as ArboristOptions,\n Advisory as BaseAdvisory,\n Arborist as BaseArborist,\n AuditReport as BaseAuditReport,\n Diff as BaseDiff,\n BuildIdealTreeOptions,\n ReifyOptions\n} from '@npmcli/arborist'\n\nexport type ArboristClass = ArboristInstance & {\n new (...args: any): ArboristInstance\n}\n\nexport type ArboristInstance = Omit<\n typeof BaseArborist,\n | 'actualTree'\n | 'auditReport'\n | 'buildIdealTree'\n | 'diff'\n | 'idealTree'\n | 'loadActual'\n | 'loadVirtual'\n | 'reify'\n> & {\n auditReport?: AuditReportInstance | null | undefined\n actualTree?: SafeNode | null | undefined\n diff: Diff | null\n idealTree?: SafeNode | null | undefined\n buildIdealTree(options?: BuildIdealTreeOptions): Promise<SafeNode>\n loadActual(options?: ArboristOptions): Promise<SafeNode>\n loadVirtual(options?: ArboristOptions): Promise<SafeNode>\n reify(options?: ArboristReifyOptions): Promise<SafeNode>\n}\n\nexport type ArboristReifyOptions = ReifyOptions & ArboristOptions\n\nexport type AuditReportInstance = Omit<BaseAuditReport, 'report'> & {\n report: { [dependency: string]: AuditAdvisory[] }\n}\n\nexport type AuditAdvisory = Omit<BaseAdvisory, 'id'> & {\n id: number\n cwe: string[]\n cvss: {\n score: number\n vectorString: string\n }\n vulnerable_versions: string\n}\n\nexport enum DiffAction {\n add = 'ADD',\n change = 'CHANGE',\n remove = 'REMOVE'\n}\n\nexport type Diff = Omit<\n BaseDiff,\n | 'actual'\n | 'children'\n | 'filterSet'\n | 'ideal'\n | 'leaves'\n | 'removed'\n | 'shrinkwrapInflated'\n | 'unchanged'\n> & {\n actual: SafeNode\n children: Diff[]\n filterSet: Set<SafeNode>\n ideal: SafeNode\n leaves: SafeNode[]\n parent: Diff | null\n removed: SafeNode[]\n shrinkwrapInflated: Set<SafeNode>\n unchanged: SafeNode[]\n}\n","import { getArboristDepValidPath } from '../../paths'\n\nimport type { SafeNode } from './node'\n\nexport const depValid: (\n child: SafeNode,\n requested: string,\n accept: string | undefined,\n requester: SafeNode\n) => boolean = require(getArboristDepValidPath())\n","import constants from '../../../constants'\nimport { getNpmRequire } from '../paths'\n\nconst { UNDEFINED_TOKEN } = constants\n\ninterface RequireKnownModules {\n npmlog: typeof import('npmlog')\n // The DefinitelyTyped definition of 'proc-log' does NOT have the log method.\n // The return type of the log method is the same as `typeof import('proc-log')`.\n 'proc-log': typeof import('proc-log')\n}\n\ntype RequireTransformer<T extends keyof RequireKnownModules> = (\n mod: RequireKnownModules[T]\n) => RequireKnownModules[T]\n\nfunction tryRequire<T extends keyof RequireKnownModules>(\n req: NodeJS.Require,\n ...ids: Array<T | [T, RequireTransformer<T>]>\n): RequireKnownModules[T] | undefined {\n for (const data of ids) {\n let id: string | undefined\n let transformer: RequireTransformer<T> | undefined\n if (Array.isArray(data)) {\n id = data[0]\n transformer = data[1] as RequireTransformer<T>\n } else {\n id = data as keyof RequireKnownModules\n transformer = mod => mod\n }\n try {\n // Check that the transformed value isn't `undefined` because older\n // versions of packages like 'proc-log' may not export a `log` method.\n const exported = transformer(req(id))\n if (exported !== undefined) {\n return exported\n }\n } catch {}\n }\n return undefined\n}\n\nexport type Logger =\n | typeof import('npmlog')\n | typeof import('proc-log')\n | undefined\n\nlet _log: Logger | {} | undefined = UNDEFINED_TOKEN\nexport function getLogger(): Logger {\n if (_log === UNDEFINED_TOKEN) {\n _log = tryRequire(\n getNpmRequire(),\n [\n 'proc-log/lib/index.js' as 'proc-log',\n // The proc-log DefinitelyTyped definition is incorrect. The type definition\n // is really that of its export log.\n mod => (mod as any).log as RequireKnownModules['proc-log']\n ],\n 'npmlog/lib/log.js' as 'npmlog'\n )\n }\n return _log as Logger | undefined\n}\n","import npa from 'npm-package-arg'\nimport semver from 'semver'\n\nimport { getArboristOverrideSetClassPath } from '../../paths'\nimport { getLogger } from '../../proc-log'\n\nimport type { SafeEdge } from './edge'\nimport type { SafeNode } from './node'\nimport type { AliasResult, RegistryResult } from 'npm-package-arg'\n\ninterface OverrideSetClass {\n children: Map<string, SafeOverrideSet>\n key: string | undefined\n keySpec: string | undefined\n name: string | undefined\n parent: SafeOverrideSet | undefined\n value: string | undefined\n version: string | undefined\n // eslint-disable-next-line @typescript-eslint/no-misused-new\n new (...args: any[]): OverrideSetClass\n get isRoot(): boolean\n get ruleset(): Map<string, SafeOverrideSet>\n ancestry(): Generator<SafeOverrideSet>\n childrenAreEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean\n getEdgeRule(edge: SafeEdge): SafeOverrideSet\n getNodeRule(node: SafeNode): SafeOverrideSet\n getMatchingRule(node: SafeNode): SafeOverrideSet | null\n isEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean\n}\n\nconst OverrideSet: OverrideSetClass = require(getArboristOverrideSetClassPath())\n\n// Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/override-set.js:\nexport class SafeOverrideSet extends OverrideSet {\n // Patch adding doOverrideSetsConflict is based on\n // https://github.com/npm/cli/pull/8089.\n static doOverrideSetsConflict(\n first: SafeOverrideSet | undefined,\n second: SafeOverrideSet | undefined\n ) {\n // If override sets contain one another then we can try to use the more\n // specific one. If neither one is more specific, then we consider them to\n // be in conflict.\n return this.findSpecificOverrideSet(first, second) === undefined\n }\n\n // Patch adding findSpecificOverrideSet is based on\n // https://github.com/npm/cli/pull/8089.\n static findSpecificOverrideSet(\n first: SafeOverrideSet | undefined,\n second: SafeOverrideSet | undefined\n ) {\n for (\n let overrideSet = second;\n overrideSet;\n overrideSet = overrideSet.parent\n ) {\n if (overrideSet.isEqual(first)) {\n return second\n }\n }\n for (\n let overrideSet = first;\n overrideSet;\n overrideSet = overrideSet.parent\n ) {\n if (overrideSet.isEqual(second)) {\n return first\n }\n }\n // The override sets are incomparable. Neither one contains the other.\n const log = getLogger()\n log?.silly('Conflicting override sets', first, second)\n return undefined\n }\n\n // Patch adding childrenAreEqual is based on\n // https://github.com/npm/cli/pull/8089.\n override childrenAreEqual(otherOverrideSet: SafeOverrideSet) {\n if (this.children.size !== otherOverrideSet.children.size) {\n return false\n }\n for (const { 0: key, 1: childOverrideSet } of this.children) {\n const otherChildOverrideSet = otherOverrideSet.children.get(key)\n if (!otherChildOverrideSet) {\n return false\n }\n if (childOverrideSet.value !== otherChildOverrideSet.value) {\n return false\n }\n if (!childOverrideSet.childrenAreEqual(otherChildOverrideSet)) {\n return false\n }\n }\n return true\n }\n\n override getEdgeRule(edge: SafeEdge): SafeOverrideSet {\n for (const rule of this.ruleset.values()) {\n if (rule.name !== edge.name) {\n continue\n }\n // If keySpec is * we found our override.\n if (rule.keySpec === '*') {\n return rule\n }\n // Patch replacing\n // let spec = npa(`${edge.name}@${edge.spec}`)\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // We need to use the rawSpec here, because the spec has the overrides\n // applied to it already. The rawSpec can be undefined, so we need to use\n // the fallback value of spec if it is.\n let spec = npa(`${edge.name}@${edge.rawSpec || edge.spec}`)\n if (spec.type === 'alias') {\n spec = (spec as AliasResult).subSpec\n }\n if (spec.type === 'git') {\n if (spec.gitRange && semver.intersects(spec.gitRange, rule.keySpec!)) {\n return rule\n }\n continue\n }\n if (spec.type === 'range' || spec.type === 'version') {\n if (\n semver.intersects((spec as RegistryResult).fetchSpec, rule.keySpec!)\n ) {\n return rule\n }\n continue\n }\n // If we got this far, the spec type is one of tag, directory or file\n // which means we have no real way to make version comparisons, so we\n // just accept the override.\n return rule\n }\n return this\n }\n\n // Patch adding isEqual is based on\n // https://github.com/npm/cli/pull/8089.\n override isEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean {\n if (this === otherOverrideSet) {\n return true\n }\n if (!otherOverrideSet) {\n return false\n }\n if (\n this.key !== otherOverrideSet.key ||\n this.value !== otherOverrideSet.value\n ) {\n return false\n }\n if (!this.childrenAreEqual(otherOverrideSet)) {\n return false\n }\n if (!this.parent) {\n return !otherOverrideSet.parent\n }\n return this.parent.isEqual(otherOverrideSet.parent)\n }\n}\n","import semver from 'semver'\n\nimport { SafeOverrideSet } from './override-set'\nimport { getArboristNodeClassPath } from '../../paths'\nimport { getLogger } from '../../proc-log'\n\nimport type { SafeEdge } from './edge'\nimport type { Node as BaseNode, Link } from '@npmcli/arborist'\n\ntype NodeClass = Omit<\n BaseNode,\n | 'addEdgeIn'\n | 'addEdgeOut'\n | 'canDedupe'\n | 'canReplace'\n | 'canReplaceWith'\n | 'children'\n | 'deleteEdgeIn'\n | 'edgesIn'\n | 'edgesOut'\n | 'from'\n | 'hasShrinkwrap'\n | 'inDepBundle'\n | 'inShrinkwrap'\n | 'integrity'\n | 'isTop'\n | 'matches'\n | 'meta'\n | 'name'\n | 'overrides'\n | 'packageName'\n | 'parent'\n | 'recalculateOutEdgesOverrides'\n | 'resolve'\n | 'resolveParent'\n | 'root'\n | 'updateOverridesEdgeInAdded'\n | 'updateOverridesEdgeInRemoved'\n | 'version'\n | 'versions'\n> & {\n name: string\n version: string\n children: Map<string, SafeNode | Link>\n edgesIn: Set<SafeEdge>\n edgesOut: Map<string, SafeEdge>\n from: SafeNode | null\n hasShrinkwrap: boolean\n inShrinkwrap: boolean | undefined\n integrity?: string | null\n isTop: boolean | undefined\n meta: BaseNode['meta'] & {\n addEdge(edge: SafeEdge): void\n }\n overrides: SafeOverrideSet | undefined\n versions: string[]\n get inDepBundle(): boolean\n get packageName(): string | null\n get parent(): SafeNode | null\n set parent(value: SafeNode | null)\n get resolveParent(): SafeNode | null\n get root(): SafeNode | null\n set root(value: SafeNode | null)\n new (...args: any): NodeClass\n addEdgeIn(edge: SafeEdge): void\n addEdgeOut(edge: SafeEdge): void\n canDedupe(preferDedupe?: boolean): boolean\n canReplace(node: SafeNode, ignorePeers?: string[]): boolean\n canReplaceWith(node: SafeNode, ignorePeers?: string[]): boolean\n deleteEdgeIn(edge: SafeEdge): void\n matches(node: SafeNode): boolean\n recalculateOutEdgesOverrides(): void\n resolve(name: string): SafeNode\n updateOverridesEdgeInAdded(\n otherOverrideSet: SafeOverrideSet | undefined\n ): boolean\n updateOverridesEdgeInRemoved(otherOverrideSet: SafeOverrideSet): boolean\n}\n\nconst Node: NodeClass = require(getArboristNodeClassPath())\n\n// Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/node.js:\nexport class SafeNode extends Node {\n // Return true if it's safe to remove this node, because anything that is\n // depending on it would be fine with the thing that they would resolve to if\n // it was removed, or nothing is depending on it in the first place.\n override canDedupe(preferDedupe = false) {\n // Not allowed to mess with shrinkwraps or bundles.\n if (this.inDepBundle || this.inShrinkwrap) {\n return false\n }\n // It's a top level pkg, or a dep of one.\n if (!this.resolveParent?.resolveParent) {\n return false\n }\n // No one wants it, remove it.\n if (this.edgesIn.size === 0) {\n return true\n }\n const other = this.resolveParent.resolveParent.resolve(this.name)\n // Nothing else, need this one.\n if (!other) {\n return false\n }\n // If it's the same thing, then always fine to remove.\n if (other.matches(this)) {\n return true\n }\n // If the other thing can't replace this, then skip it.\n if (!other.canReplace(this)) {\n return false\n }\n // Patch replacing\n // if (preferDedupe || semver.gte(other.version, this.version)) {\n // return true\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If we prefer dedupe, or if the version is equal, take the other.\n if (preferDedupe || semver.eq(other.version, this.version)) {\n return true\n }\n // If our current version isn't the result of an override, then prefer to\n // take the greater version.\n if (!this.overridden && semver.gt(other.version, this.version)) {\n return true\n }\n return false\n }\n\n // Is it safe to replace one node with another? check the edges to\n // make sure no one will get upset. Note that the node might end up\n // having its own unmet dependencies, if the new node has new deps.\n // Note that there are cases where Arborist will opt to insert a node\n // into the tree even though this function returns false! This is\n // necessary when a root dependency is added or updated, or when a\n // root dependency brings peer deps along with it. In that case, we\n // will go ahead and create the invalid state, and then try to resolve\n // it with more tree construction, because it's a user request.\n override canReplaceWith(node: SafeNode, ignorePeers?: string[]): boolean {\n if (this.name !== node.name || this.packageName !== node.packageName) {\n return false\n }\n // Patch replacing\n // if (node.overrides !== this.overrides) {\n // return false\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If this node has no dependencies, then it's irrelevant to check the\n // override rules of the replacement node.\n if (this.edgesOut.size) {\n // XXX need to check for two root nodes?\n if (node.overrides) {\n if (!node.overrides.isEqual(this.overrides)) {\n return false\n }\n } else {\n if (this.overrides) {\n return false\n }\n }\n }\n // To satisfy the patch we ensure `node.overrides === this.overrides`\n // so that the condition we want to replace,\n // if (this.overrides !== node.overrides) {\n // , is not hit.`\n const oldOverrideSet = this.overrides\n let result = true\n if (oldOverrideSet !== node.overrides) {\n this.overrides = node.overrides\n }\n try {\n result = super.canReplaceWith(node, ignorePeers)\n this.overrides = oldOverrideSet\n } catch (e) {\n this.overrides = oldOverrideSet\n throw e\n }\n return result\n }\n\n // Patch adding deleteEdgeIn is based on https://github.com/npm/cli/pull/8089.\n override deleteEdgeIn(edge: SafeEdge) {\n this.edgesIn.delete(edge)\n const { overrides } = edge\n if (overrides) {\n this.updateOverridesEdgeInRemoved(overrides)\n }\n }\n\n override addEdgeIn(edge: SafeEdge): void {\n // Patch replacing\n // if (edge.overrides) {\n // this.overrides = edge.overrides\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // We need to handle the case where the new edge in has an overrides field\n // which is different from the current value.\n if (!this.overrides || !this.overrides.isEqual(edge.overrides)) {\n this.updateOverridesEdgeInAdded(edge.overrides)\n }\n this.edgesIn.add(edge)\n // Try to get metadata from the yarn.lock file.\n this.root.meta?.addEdge(edge)\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get overridden() {\n // Patch replacing\n // return !!(this.overrides && this.overrides.value && this.overrides.name === this.name)\n // is based on https://github.com/npm/cli/pull/8089.\n if (\n !this.overrides ||\n !this.overrides.value ||\n this.overrides.name !== this.name\n ) {\n return false\n }\n // The overrides rule is for a package with this name, but some override\n // rules only apply to specific versions. To make sure this package was\n // actually overridden, we check whether any edge going in had the rule\n // applied to it, in which case its overrides set is different than its\n // source node.\n for (const edge of this.edgesIn) {\n if (\n edge.overrides &&\n edge.overrides.name === this.name &&\n edge.overrides.value === this.version\n ) {\n if (!edge.overrides.isEqual(edge.from?.overrides)) {\n return true\n }\n }\n }\n return false\n }\n\n override set parent(newParent: SafeNode) {\n // Patch removing\n // if (parent.overrides) {\n // this.overrides = parent.overrides.getNodeRule(this)\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // The \"parent\" setter is a really large and complex function. To satisfy\n // the patch we hold on to the old overrides value and set `this.overrides`\n // to `undefined` so that the condition we want to remove is not hit.\n const { overrides } = this\n if (overrides) {\n this.overrides = undefined\n }\n try {\n super.parent = newParent\n this.overrides = overrides\n } catch (e) {\n this.overrides = overrides\n throw e\n }\n }\n\n // Patch adding recalculateOutEdgesOverrides is based on\n // https://github.com/npm/cli/pull/8089.\n override recalculateOutEdgesOverrides() {\n // For each edge out propagate the new overrides through.\n for (const edge of this.edgesOut.values()) {\n edge.reload(true)\n if (edge.to) {\n edge.to.updateOverridesEdgeInAdded(edge.overrides)\n }\n }\n }\n\n // @ts-ignore: Incorrectly typed to accept null.\n override set root(newRoot: SafeNode) {\n // Patch removing\n // if (!this.overrides && this.parent && this.parent.overrides) {\n // this.overrides = this.parent.overrides.getNodeRule(this)\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // The \"root\" setter is a really large and complex function. To satisfy the\n // patch we add a dummy value to `this.overrides` so that the condition we\n // want to remove is not hit.\n if (!this.overrides) {\n this.overrides = new SafeOverrideSet({ overrides: '' })\n }\n try {\n super.root = newRoot\n this.overrides = undefined\n } catch (e) {\n this.overrides = undefined\n throw e\n }\n }\n\n // Patch adding updateOverridesEdgeInAdded is based on\n // https://github.com/npm/cli/pull/7025.\n //\n // This logic isn't perfect either. When we have two edges in that have\n // different override sets, then we have to decide which set is correct. This\n // function assumes the more specific override set is applicable, so if we have\n // dependencies A->B->C and A->C and an override set that specifies what happens\n // for C under A->B, this will work even if the new A->C edge comes along and\n // tries to change the override set. The strictly correct logic is not to allow\n // two edges with different overrides to point to the same node, because even\n // if this node can satisfy both, one of its dependencies might need to be\n // different depending on the edge leading to it. However, this might cause a\n // lot of duplication, because the conflict in the dependencies might never\n // actually happen.\n override updateOverridesEdgeInAdded(\n otherOverrideSet: SafeOverrideSet | undefined\n ) {\n if (!otherOverrideSet) {\n // Assuming there are any overrides at all, the overrides field is never\n // undefined for any node at the end state of the tree. So if the new edge's\n // overrides is undefined it will be updated later. So we can wait with\n // updating the node's overrides field.\n return false\n }\n if (!this.overrides) {\n this.overrides = otherOverrideSet\n this.recalculateOutEdgesOverrides()\n return true\n }\n if (this.overrides.isEqual(otherOverrideSet)) {\n return false\n }\n const newOverrideSet = SafeOverrideSet.findSpecificOverrideSet(\n this.overrides,\n otherOverrideSet\n )\n if (newOverrideSet) {\n if (this.overrides.isEqual(newOverrideSet)) {\n return false\n }\n this.overrides = newOverrideSet\n this.recalculateOutEdgesOverrides()\n return true\n }\n // This is an error condition. We can only get here if the new override set\n // is in conflict with the existing.\n const log = getLogger()\n log?.silly('Conflicting override sets', this.name)\n return false\n }\n\n // Patch adding updateOverridesEdgeInRemoved is based on\n // https://github.com/npm/cli/pull/7025.\n override updateOverridesEdgeInRemoved(otherOverrideSet: SafeOverrideSet) {\n // If this edge's overrides isn't equal to this node's overrides,\n // then removing it won't change newOverrideSet later.\n if (!this.overrides || !this.overrides.isEqual(otherOverrideSet)) {\n return false\n }\n let newOverrideSet\n for (const edge of this.edgesIn) {\n const { overrides: edgeOverrides } = edge\n if (newOverrideSet && edgeOverrides) {\n newOverrideSet = SafeOverrideSet.findSpecificOverrideSet(\n edgeOverrides,\n newOverrideSet\n )\n } else {\n newOverrideSet = edgeOverrides\n }\n }\n if (this.overrides.isEqual(newOverrideSet)) {\n return false\n }\n this.overrides = newOverrideSet\n if (newOverrideSet) {\n // Optimization: If there's any override set at all, then no non-extraneous\n // node has an empty override set. So if we temporarily have no override set\n // (for example, we removed all the edges in), there's no use updating all\n // the edges out right now. Let's just wait until we have an actual override\n // set later.\n this.recalculateOutEdgesOverrides()\n }\n return true\n }\n}\n","import { depValid } from './dep-valid'\nimport { SafeNode } from './node'\nimport { SafeOverrideSet } from './override-set'\nimport { getArboristEdgeClassPath } from '../../paths'\n\nimport type { Edge as BaseEdge, DependencyProblem } from '@npmcli/arborist'\n\ntype EdgeClass = Omit<\n BaseEdge,\n | 'accept'\n | 'detach'\n | 'optional'\n | 'overrides'\n | 'peer'\n | 'peerConflicted'\n | 'rawSpec'\n | 'reload'\n | 'satisfiedBy'\n | 'spec'\n | 'to'\n> & {\n optional: boolean\n overrides: SafeOverrideSet | undefined\n peer: boolean\n peerConflicted: boolean\n rawSpec: string\n get accept(): string | undefined\n get spec(): string\n get to(): SafeNode | null\n new (...args: any): EdgeClass\n detach(): void\n reload(hard?: boolean): void\n satisfiedBy(node: SafeNode): boolean\n}\n\nexport type EdgeOptions = {\n type: string\n name: string\n spec: string\n from: SafeNode\n accept?: string | undefined\n overrides?: SafeOverrideSet | undefined\n to?: SafeNode | undefined\n}\n\nexport type ErrorStatus = DependencyProblem | 'OK'\n\nexport type Explanation = {\n type: string\n name: string\n spec: string\n bundled: boolean\n overridden: boolean\n error: ErrorStatus | undefined\n rawSpec: string | undefined\n from: object | undefined\n} | null\n\nexport const Edge: EdgeClass = require(getArboristEdgeClassPath())\n\n// The Edge class makes heavy use of private properties which subclasses do NOT\n// have access to. So we have to recreate any functionality that relies on those\n// private properties and use our own \"safe\" prefixed non-conflicting private\n// properties. Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/edge.js.\n//\n// The npm application\n// Copyright (c) npm, Inc. and Contributors\n// Licensed on the terms of The Artistic License 2.0\n//\n// An edge in the dependency graph.\n// Represents a dependency relationship of some kind.\nexport class SafeEdge extends Edge {\n #safeError: ErrorStatus | null\n #safeExplanation: Explanation | undefined\n #safeFrom: SafeNode | null\n #safeTo: SafeNode | null\n\n constructor(options: EdgeOptions) {\n const { from } = options\n // Defer to supper to validate options and assign non-private values.\n super(options)\n if (from.constructor !== SafeNode) {\n Reflect.setPrototypeOf(from, SafeNode.prototype)\n }\n this.#safeError = null\n this.#safeExplanation = null\n this.#safeFrom = from\n this.#safeTo = null\n this.reload(true)\n }\n\n override get bundled() {\n return !!this.#safeFrom?.package?.bundleDependencies?.includes(this.name)\n }\n\n override get error() {\n if (!this.#safeError) {\n if (!this.#safeTo) {\n if (this.optional) {\n this.#safeError = null\n } else {\n this.#safeError = 'MISSING'\n }\n } else if (\n this.peer &&\n this.#safeFrom === this.#safeTo.parent &&\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n !this.#safeFrom?.isTop\n ) {\n this.#safeError = 'PEER LOCAL'\n } else if (!this.satisfiedBy(this.#safeTo)) {\n this.#safeError = 'INVALID'\n }\n // Patch adding \"else if\" condition is based on\n // https://github.com/npm/cli/pull/8089.\n else if (\n this.overrides &&\n this.#safeTo.edgesOut.size &&\n SafeOverrideSet.doOverrideSetsConflict(\n this.overrides,\n this.#safeTo.overrides\n )\n ) {\n // Any inconsistency between the edge's override set and the target's\n // override set is potentially problematic. But we only say the edge is\n // in error if the override sets are plainly conflicting. Note that if\n // the target doesn't have any dependencies of their own, then this\n // inconsistency is irrelevant.\n this.#safeError = 'INVALID'\n } else {\n this.#safeError = 'OK'\n }\n }\n if (this.#safeError === 'OK') {\n return null\n }\n return this.#safeError\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get from() {\n return this.#safeFrom\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get spec(): string {\n if (\n this.overrides?.value &&\n this.overrides.value !== '*' &&\n this.overrides.name === this.name\n ) {\n if (this.overrides.value.startsWith('$')) {\n const ref = this.overrides.value.slice(1)\n // We may be a virtual root, if we are we want to resolve reference\n // overrides from the real root, not the virtual one.\n //\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n const pkg = this.#safeFrom?.sourceReference\n ? this.#safeFrom?.sourceReference.root.package\n : this.#safeFrom?.root?.package\n if (pkg?.devDependencies?.[ref]) {\n return pkg.devDependencies[ref] as string\n }\n if (pkg?.optionalDependencies?.[ref]) {\n return pkg.optionalDependencies[ref] as string\n }\n if (pkg?.dependencies?.[ref]) {\n return pkg.dependencies[ref] as string\n }\n if (pkg?.peerDependencies?.[ref]) {\n return pkg.peerDependencies[ref] as string\n }\n throw new Error(`Unable to resolve reference ${this.overrides.value}`)\n }\n return this.overrides.value\n }\n return this.rawSpec\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get to() {\n return this.#safeTo\n }\n\n override detach() {\n this.#safeExplanation = null\n // Patch replacing\n // if (this.#to) {\n // this.#to.edgesIn.delete(this)\n // }\n // this.#from.edgesOut.delete(this.#name)\n // is based on https://github.com/npm/cli/pull/8089.\n this.#safeTo?.deleteEdgeIn(this)\n this.#safeFrom?.edgesOut.delete(this.name)\n this.#safeTo = null\n this.#safeError = 'DETACHED'\n this.#safeFrom = null\n }\n\n // Return the edge data, and an explanation of how that edge came to be here.\n // @ts-ignore: Edge#explain is defined with an unused `seen = []` param.\n override explain() {\n if (!this.#safeExplanation) {\n const explanation: Explanation = {\n type: this.type,\n name: this.name,\n spec: this.spec,\n bundled: false,\n overridden: false,\n error: undefined,\n from: undefined,\n rawSpec: undefined\n }\n if (this.rawSpec !== this.spec) {\n explanation.rawSpec = this.rawSpec\n explanation.overridden = true\n }\n if (this.bundled) {\n explanation.bundled = this.bundled\n }\n if (this.error) {\n explanation.error = this.error\n }\n if (this.#safeFrom) {\n explanation.from = this.#safeFrom.explain()\n }\n this.#safeExplanation = explanation\n }\n return this.#safeExplanation\n }\n\n override reload(hard = false) {\n this.#safeExplanation = null\n // Patch replacing\n // if (this.#from.overrides) {\n // is based on https://github.com/npm/cli/pull/8089.\n let needToUpdateOverrideSet = false\n let newOverrideSet\n let oldOverrideSet\n if (this.#safeFrom?.overrides) {\n newOverrideSet = this.#safeFrom.overrides.getEdgeRule(this)\n if (newOverrideSet && !newOverrideSet.isEqual(this.overrides)) {\n // If there's a new different override set we need to propagate it to\n // the nodes. If we're deleting the override set then there's no point\n // propagating it right now since it will be filled with another value\n // later.\n needToUpdateOverrideSet = true\n oldOverrideSet = this.overrides\n this.overrides = newOverrideSet\n }\n } else {\n this.overrides = undefined\n }\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n const newTo = this.#safeFrom?.resolve(this.name)\n if (newTo !== this.#safeTo) {\n // Patch replacing\n // this.#to.edgesIn.delete(this)\n // is based on https://github.com/npm/cli/pull/8089.\n this.#safeTo?.deleteEdgeIn(this)\n this.#safeTo = (newTo as SafeNode) ?? null\n this.#safeError = null\n this.#safeTo?.addEdgeIn(this)\n } else if (hard) {\n this.#safeError = null\n }\n // Patch adding \"else if\" condition based on\n // https://github.com/npm/cli/pull/8089.\n else if (needToUpdateOverrideSet && this.#safeTo) {\n // Propagate the new override set to the target node.\n this.#safeTo.updateOverridesEdgeInRemoved(oldOverrideSet!)\n this.#safeTo.updateOverridesEdgeInAdded(newOverrideSet)\n }\n }\n\n override satisfiedBy(node: SafeNode) {\n // Patch replacing\n // if (node.name !== this.#name) {\n // return false\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n if (node.name !== this.name || !this.#safeFrom) {\n return false\n }\n // NOTE: this condition means we explicitly do not support overriding\n // bundled or shrinkwrapped dependencies\n if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) {\n return depValid(node, this.rawSpec, this.accept, this.#safeFrom)\n }\n // Patch replacing\n // return depValid(node, this.spec, this.#accept, this.#from)\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If there's no override we just use the spec.\n if (!this.overrides?.keySpec) {\n return depValid(node, this.spec, this.accept, this.#safeFrom)\n }\n // There's some override. If the target node satisfies the overriding spec\n // then it's okay.\n if (depValid(node, this.spec, this.accept, this.#safeFrom)) {\n return true\n }\n // If it doesn't, then it should at least satisfy the original spec.\n if (!depValid(node, this.rawSpec, this.accept, this.#safeFrom)) {\n return false\n }\n // It satisfies the original spec, not the overriding spec. We need to make\n // sure it doesn't use the overridden spec.\n // For example:\n // we might have an ^8.0.0 rawSpec, and an override that makes\n // keySpec=8.23.0 and the override value spec=9.0.0.\n // If the node is 9.0.0, then it's okay because it's consistent with spec.\n // If the node is 8.24.0, then it's okay because it's consistent with the rawSpec.\n // If the node is 8.23.0, then it's not okay because even though it's consistent\n // with the rawSpec, it's also consistent with the keySpec.\n // So we're looking for ^8.0.0 or 9.0.0 and not 8.23.0.\n return !depValid(node, this.overrides.keySpec, this.accept, this.#safeFrom)\n }\n}\n","import semver from 'semver'\n\nimport { PackageURL } from '@socketregistry/packageurl-js'\nimport { getManifestData } from '@socketsecurity/registry'\nimport { hasOwn } from '@socketsecurity/registry/lib/objects'\nimport {\n EditablePackageJson,\n fetchPackagePackument\n} from '@socketsecurity/registry/lib/packages'\n\nimport constants from '../constants'\nimport { applyRange, getMajor } from './semver'\nimport { DiffAction } from '../shadow/npm/arborist/lib/arborist/types'\nimport { Edge } from '../shadow/npm/arborist/lib/edge'\n\nimport type { RangeStyle } from './semver'\nimport type { Diff } from '../shadow/npm/arborist/lib/arborist/types'\nimport type { SafeEdge } from '../shadow/npm/arborist/lib/edge'\nimport type { SafeNode } from '../shadow/npm/arborist/lib/node'\n\nconst { LOOP_SENTINEL, NPM, NPM_REGISTRY_URL } = constants\n\nfunction getUrlOrigin(input: string): string {\n try {\n // TODO: URL.parse is available in Node 22.1.0. We can use it when we drop Node 18.\n // https://nodejs.org/docs/latest-v22.x/api/url.html#urlparseinput-base\n // return URL.parse(input)?.origin ?? ''\n return new URL(input).origin ?? ''\n } catch {}\n return ''\n}\n\nexport function findBestPatchVersion(\n node: SafeNode,\n availableVersions: string[],\n vulnerableVersionRange?: string,\n _firstPatchedVersionIdentifier?: string | undefined\n): string | null {\n const manifestData = getManifestData(NPM, node.name)\n let eligibleVersions\n if (manifestData && manifestData.name === manifestData.package) {\n const major = getMajor(manifestData.version)\n if (typeof major !== 'number') {\n return null\n }\n eligibleVersions = availableVersions.filter(v => getMajor(v) === major)\n } else {\n const major = getMajor(node.version)\n if (typeof major !== 'number') {\n return null\n }\n eligibleVersions = availableVersions.filter(\n v =>\n // Filter for versions that are within the current major version and\n // are NOT in the vulnerable range.\n getMajor(v) === major &&\n (!vulnerableVersionRange ||\n !semver.satisfies(v, vulnerableVersionRange))\n )\n }\n return eligibleVersions ? semver.maxSatisfying(eligibleVersions, '*') : null\n}\n\nexport function findPackageNode(\n tree: SafeNode,\n name: string,\n version?: string | undefined\n): SafeNode | undefined {\n const queue: SafeNode[] = [tree]\n let sentinel = 0\n while (queue.length) {\n if (sentinel++ === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop in findPackageNodes')\n }\n const currentNode = queue.pop()!\n const node = currentNode.children.get(name)\n if (node && (typeof version !== 'string' || node.version === version)) {\n return node as unknown as SafeNode\n }\n const children = [...currentNode.children.values()]\n for (let i = children.length - 1; i >= 0; i -= 1) {\n queue.push(children[i] as unknown as SafeNode)\n }\n }\n}\n\nexport function findPackageNodes(\n tree: SafeNode,\n name: string,\n version?: string | undefined\n): SafeNode[] {\n const queue: SafeNode[] = [tree]\n const matches: SafeNode[] = []\n let sentinel = 0\n while (queue.length) {\n if (sentinel++ === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop in findPackageNodes')\n }\n const currentNode = queue.pop()!\n const node = currentNode.children.get(name)\n if (node && (typeof version !== 'string' || node.version === version)) {\n matches.push(node as unknown as SafeNode)\n }\n const children = [...currentNode.children.values()]\n for (let i = children.length - 1; i >= 0; i -= 1) {\n queue.push(children[i] as unknown as SafeNode)\n }\n }\n return matches\n}\n\nexport type DiffQueryIncludeFilter = {\n unchanged?: boolean | undefined\n unknownOrigin?: boolean | undefined\n}\n\nexport type DiffQueryOptions = {\n include?: DiffQueryIncludeFilter | undefined\n}\n\nexport type PackageDetail = {\n node: SafeNode\n existing?: SafeNode | undefined\n}\n\nexport function getDetailsFromDiff(\n diff_: Diff | null,\n options?: DiffQueryOptions | undefined\n): PackageDetail[] {\n const details: PackageDetail[] = []\n // `diff_` is `null` when `npm install --package-lock-only` is passed.\n if (!diff_) {\n return details\n }\n\n const include = {\n __proto__: null,\n unchanged: false,\n unknownOrigin: false,\n ...({ __proto__: null, ...options } as DiffQueryOptions).include\n } as DiffQueryIncludeFilter\n\n const queue: Diff[] = [...diff_.children]\n let pos = 0\n let { length: queueLength } = queue\n while (pos < queueLength) {\n if (pos === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop while walking Arborist diff')\n }\n const diff = queue[pos++]!\n const { action } = diff\n if (action) {\n // The `pkgNode`, i.e. the `ideal` node, will be `undefined` if the diff\n // action is 'REMOVE'\n // The `oldNode`, i.e. the `actual` node, will be `undefined` if the diff\n // action is 'ADD'.\n const { actual: oldNode, ideal: pkgNode } = diff\n let existing: SafeNode | undefined\n let keep = false\n if (action === DiffAction.change) {\n if (pkgNode?.package.version !== oldNode?.package.version) {\n keep = true\n if (\n oldNode?.package.name &&\n oldNode.package.name === pkgNode?.package.name\n ) {\n existing = oldNode\n }\n } else {\n // TODO: This debug log has too much information. We should narrow it down.\n // debugLog('SKIPPING META CHANGE ON', diff)\n }\n } else {\n keep = action !== DiffAction.remove\n }\n if (keep && pkgNode?.resolved && (!oldNode || oldNode.resolved)) {\n if (\n include.unknownOrigin ||\n getUrlOrigin(pkgNode.resolved) === NPM_REGISTRY_URL\n ) {\n details.push({\n node: pkgNode,\n existing\n })\n }\n }\n }\n for (const child of diff.children) {\n queue[queueLength++] = child\n }\n }\n if (include.unchanged) {\n const { unchanged } = diff_!\n for (let i = 0, { length } = unchanged; i < length; i += 1) {\n const pkgNode = unchanged[i]!\n if (\n include.unknownOrigin ||\n getUrlOrigin(pkgNode.resolved!) === NPM_REGISTRY_URL\n ) {\n details.push({\n node: pkgNode,\n existing: pkgNode\n })\n }\n }\n }\n return details\n}\n\nexport function isTopLevel(tree: SafeNode, node: SafeNode): boolean {\n return tree.children.get(node.name) === node\n}\n\nexport type Packument = Exclude<\n Awaited<ReturnType<typeof fetchPackagePackument>>,\n null\n>\n\nexport function updateNode(\n node: SafeNode,\n newVersion: string,\n newVersionPackument: Packument['versions'][number]\n): void {\n // Object.defineProperty is needed to set the version property and replace\n // the old value with newVersion.\n Object.defineProperty(node, 'version', {\n configurable: true,\n enumerable: true,\n get: () => newVersion\n })\n // Update package.version associated with the node.\n node.package.version = newVersion\n // Update node.resolved.\n const purlObj = PackageURL.fromString(`pkg:npm/${node.name}`)\n node.resolved = `${NPM_REGISTRY_URL}/${node.name}/-/${purlObj.name}-${newVersion}.tgz`\n // Update node.integrity with the targetPackument.dist.integrity value if available\n // else delete node.integrity so a new value is resolved for the target version.\n const { integrity } = newVersionPackument.dist\n if (integrity) {\n node.integrity = integrity\n } else {\n delete node.integrity\n }\n // Update node.package.deprecated based on targetPackument.deprecated.\n if (hasOwn(newVersionPackument, 'deprecated')) {\n node.package['deprecated'] = newVersionPackument.deprecated as string\n } else {\n delete node.package['deprecated']\n }\n // Update node.package.dependencies.\n const newDeps = { ...newVersionPackument.dependencies }\n const { dependencies: oldDeps } = node.package\n node.package.dependencies = newDeps\n if (oldDeps) {\n for (const oldDepName of Object.keys(oldDeps)) {\n if (!hasOwn(newDeps, oldDepName)) {\n // Detach old edges for dependencies that don't exist on the updated\n // node.package.dependencies.\n node.edgesOut.get(oldDepName)?.detach()\n }\n }\n }\n for (const newDepName of Object.keys(newDeps)) {\n if (!hasOwn(oldDeps, newDepName)) {\n // Add new edges for dependencies that don't exist on the old\n // node.package.dependencies.\n node.addEdgeOut(\n new Edge({\n from: node,\n name: newDepName,\n spec: newDeps[newDepName],\n type: 'prod'\n }) as unknown as SafeEdge\n )\n }\n }\n}\n\nexport function updatePackageJsonFromNode(\n editablePkgJson: EditablePackageJson,\n tree: SafeNode,\n node: SafeNode,\n newVersion: string,\n rangeStyle?: RangeStyle | undefined\n): boolean {\n let result = false\n if (!isTopLevel(tree, node)) {\n return result\n }\n const { name } = node\n for (const depField of [\n 'dependencies',\n 'optionalDependencies',\n 'peerDependencies'\n ]) {\n const depObject = editablePkgJson.content[depField] as\n | { [key: string]: string }\n | undefined\n if (depObject) {\n const oldRange = depObject[name]\n if (oldRange) {\n const newRange = applyRange(oldRange, newVersion, rangeStyle)\n if (oldRange !== newRange) {\n result = true\n editablePkgJson.update({\n [depField]: {\n ...depObject,\n [name]: newRange\n }\n })\n }\n }\n }\n }\n return result\n}\n","import constants from '../../constants'\n\nimport type { Remap } from '@socketsecurity/registry/lib/objects'\nimport type { components, operations } from '@socketsecurity/sdk/types/api'\n\nexport type ALERT_ACTION = 'error' | 'monitor' | 'warn' | 'ignore'\n\nexport type ALERT_TYPE = keyof NonNullable<\n operations['getOrgSecurityPolicy']['responses']['200']['content']['application/json']['securityPolicyRules']\n>\n\nexport type CVE_ALERT_TYPE = 'cve' | 'mediumCVE' | 'mildCVE' | 'criticalCVE'\n\nexport type ArtifactAlertCve = Remap<\n Omit<CompactSocketArtifactAlert, 'type'> & {\n type: CVE_ALERT_TYPE\n }\n>\n\nexport type ArtifactAlertCveFixable = Remap<\n Omit<CompactSocketArtifactAlert, 'props' | 'type'> & {\n type: CVE_ALERT_TYPE\n props: {\n firstPatchedVersionIdentifier: string\n vulnerableVersionRange: string\n [key: string]: any\n }\n }\n>\n\nexport type ArtifactAlertUpgrade = Remap<\n Omit<CompactSocketArtifactAlert, 'type'> & {\n type: 'socketUpgradeAvailable'\n }\n>\n\nexport type CompactSocketArtifactAlert = Remap<\n Omit<SocketArtifactAlert, 'category' | 'end' | 'file' | 'start'>\n>\n\nexport type CompactSocketArtifact = Remap<\n Omit<SocketArtifact, 'alerts' | 'batchIndex' | 'size'> & {\n alerts: CompactSocketArtifactAlert[]\n }\n>\n\nexport type SocketArtifact = Remap<\n Omit<components['schemas']['SocketArtifact'], 'alerts'> & {\n alerts?: SocketArtifactAlert[]\n }\n>\n\nexport type SocketArtifactAlert = Remap<\n Omit<components['schemas']['SocketAlert'], 'action' | 'props' | 'type'> & {\n type: ALERT_TYPE\n action?: 'error' | 'monitor' | 'warn' | 'ignore'\n props?: any | undefined\n }\n>\n\nconst {\n ALERT_TYPE_CRITICAL_CVE,\n ALERT_TYPE_CVE,\n ALERT_TYPE_MEDIUM_CVE,\n ALERT_TYPE_MILD_CVE\n} = constants\n\nexport function isArtifactAlertCve(\n alert: CompactSocketArtifactAlert\n): alert is ArtifactAlertCve {\n const { type } = alert\n return (\n type === ALERT_TYPE_CVE ||\n type === ALERT_TYPE_MEDIUM_CVE ||\n type === ALERT_TYPE_MILD_CVE ||\n type === ALERT_TYPE_CRITICAL_CVE\n )\n}\n","export enum ALERT_FIX_TYPE {\n cve = 'cve',\n remove = 'remove',\n upgrade = 'upgrade'\n}\n","export function pick<T extends Record<string, any>, K extends keyof T>(\n input: T,\n keys: K[] | readonly K[]\n): Pick<T, K> {\n const result: Partial<Pick<T, K>> = {}\n for (const key of keys) {\n result[key] = input[key]\n }\n return result as Pick<T, K>\n}\n","export function stringJoinWithSeparateFinalSeparator(\n list: string[],\n separator: string = ' and '\n): string {\n const values = list.filter(Boolean)\n const { length } = values\n if (!length) {\n return ''\n }\n if (length === 1) {\n return values[0]!\n }\n const finalValue = values.pop()\n return `${values.join(', ')}${separator}${finalValue}`\n}\n","import { pick } from '../objects'\nimport { stringJoinWithSeparateFinalSeparator } from '../strings'\n\nimport type { SocketSdkReturnType } from '@socketsecurity/sdk'\n\nexport enum ALERT_SEVERITY {\n critical = 'critical',\n high = 'high',\n middle = 'middle',\n low = 'low'\n}\n\nexport type SocketSdkAlertList =\n SocketSdkReturnType<'getIssuesByNPMPackage'>['data']\n\nexport type SocketSdkAlert = SocketSdkAlertList[number]['value'] extends\n | infer U\n | undefined\n ? U\n : never\n\n// Ordered from most severe to least.\nexport const ALERT_SEVERITIES_SORTED: ReadonlyArray<\n SocketSdkAlert['severity']\n> = Object.freeze(['critical', 'high', 'middle', 'low'])\n\nfunction getDesiredSeverities(\n lowestToInclude: SocketSdkAlert['severity'] | undefined\n): Array<SocketSdkAlert['severity']> {\n const result: Array<SocketSdkAlert['severity']> = []\n for (const severity of ALERT_SEVERITIES_SORTED) {\n result.push(severity)\n if (severity === lowestToInclude) {\n break\n }\n }\n return result\n}\n\nexport function formatSeverityCount(\n severityCount: Record<SocketSdkAlert['severity'], number>\n): string {\n const summary: string[] = []\n for (const severity of ALERT_SEVERITIES_SORTED) {\n if (severityCount[severity]) {\n summary.push(`${severityCount[severity]} ${severity}`)\n }\n }\n return stringJoinWithSeparateFinalSeparator(summary)\n}\n\nexport function getSeverityCount(\n issues: SocketSdkAlertList,\n lowestToInclude: SocketSdkAlert['severity'] | undefined\n): Record<SocketSdkAlert['severity'], number> {\n const severityCount = pick(\n { low: 0, middle: 0, high: 0, critical: 0 },\n getDesiredSeverities(lowestToInclude)\n ) as Record<SocketSdkAlert['severity'], number>\n\n for (const issue of issues) {\n const { value } = issue\n if (!value) {\n continue\n }\n const { severity } = value\n if (severityCount[severity] !== undefined) {\n severityCount[severity] += 1\n }\n }\n return severityCount\n}\n","import terminalLink from 'terminal-link'\nimport colors from 'yoctocolors-cjs'\n\nimport indentString from '@socketregistry/indent-string/index.cjs'\n\nexport class ColorOrMarkdown {\n public useMarkdown: boolean\n\n constructor(useMarkdown: boolean) {\n this.useMarkdown = !!useMarkdown\n }\n\n bold(text: string): string {\n return this.useMarkdown ? `**${text}**` : colors.bold(`${text}`)\n }\n\n header(text: string, level = 1): string {\n return this.useMarkdown\n ? `\\n${''.padStart(level, '#')} ${text}\\n`\n : colors.underline(`\\n${level === 1 ? colors.bold(text) : text}\\n`)\n }\n\n hyperlink(\n text: string,\n url: string | undefined,\n {\n fallback = true,\n fallbackToUrl\n }: {\n fallback?: boolean | undefined\n fallbackToUrl?: boolean | undefined\n } = {}\n ) {\n if (url) {\n return this.useMarkdown\n ? `[${text}](${url})`\n : terminalLink(text, url, {\n fallback: fallbackToUrl ? (_text, url) => url : fallback\n })\n }\n return text\n }\n\n indent(\n ...args: Parameters<typeof indentString>\n ): ReturnType<typeof indentString> {\n return indentString(...args)\n }\n\n italic(text: string): string {\n return this.useMarkdown ? `_${text}_` : colors.italic(`${text}`)\n }\n\n json(value: any): string {\n return this.useMarkdown\n ? '```json\\n' + JSON.stringify(value) + '\\n```'\n : JSON.stringify(value)\n }\n\n list(items: string[]): string {\n const indentedContent = items.map(item => this.indent(item).trimStart())\n return this.useMarkdown\n ? `* ${indentedContent.join('\\n* ')}\\n`\n : `${indentedContent.join('\\n')}\\n`\n }\n}\n","export function getSocketDevAlertUrl(alertType: string): string {\n return `https://socket.dev/alerts/${alertType}`\n}\n\nexport function getSocketDevPackageOverviewUrl(\n eco: string,\n name: string,\n version?: string | undefined\n): string {\n return `https://socket.dev/${eco}/package/${name}${version ? `/overview/${version}` : ''}`\n}\n","import path from 'node:path'\n\nimport constants from '../constants'\n\nlet _translations: typeof import('../../translations.json') | undefined\n\nexport function getTranslations() {\n if (_translations === undefined) {\n _translations = require(\n // Lazily access constants.rootPath.\n path.join(constants.rootPath, 'translations.json')\n )\n }\n return _translations!\n}\n","import semver from 'semver'\nimport colors from 'yoctocolors-cjs'\n\nimport { PackageURL } from '@socketregistry/packageurl-js'\nimport { getManifestData } from '@socketsecurity/registry'\nimport { hasOwn } from '@socketsecurity/registry/lib/objects'\nimport { resolvePackageName } from '@socketsecurity/registry/lib/packages'\nimport { naturalCompare } from '@socketsecurity/registry/lib/sorts'\n\nimport { isArtifactAlertCve } from './alert/artifact'\nimport { ALERT_FIX_TYPE } from './alert/fix'\nimport { ALERT_SEVERITY } from './alert/severity'\nimport { ColorOrMarkdown } from './color-or-markdown'\nimport { getSocketDevPackageOverviewUrl } from './socket-url'\nimport { getTranslations } from './translations'\nimport constants from '../constants'\nimport { findSocketYmlSync } from './config'\n\nimport type {\n ALERT_ACTION,\n ALERT_TYPE,\n CompactSocketArtifact,\n CompactSocketArtifactAlert\n} from './alert/artifact'\nimport type { Spinner } from '@socketsecurity/registry/lib/spinner'\n\nexport enum ALERT_SEVERITY_COLOR {\n critical = 'magenta',\n high = 'red',\n middle = 'yellow',\n low = 'white'\n}\n\nexport enum ALERT_SEVERITY_ORDER {\n critical = 0,\n high = 1,\n middle = 2,\n low = 3,\n none = 4\n}\n\nexport type SocketPackageAlert = {\n name: string\n version: string\n key: string\n type: string\n blocked: boolean\n critical: boolean\n fixable: boolean\n raw: CompactSocketArtifactAlert\n upgradable: boolean\n}\n\nexport type AlertsByPkgId = Map<string, SocketPackageAlert[]>\n\nconst { CVE_ALERT_PROPS_FIRST_PATCHED_VERSION_IDENTIFIER, NPM } = constants\n\nconst MIN_ABOVE_THE_FOLD_COUNT = 3\n\nconst MIN_ABOVE_THE_FOLD_ALERT_COUNT = 1\n\nconst format = new ColorOrMarkdown(false)\n\nfunction alertsHaveBlocked(alerts: SocketPackageAlert[]): boolean {\n return alerts.find(a => a.blocked) !== undefined\n}\n\nfunction alertsHaveSeverity(\n alerts: SocketPackageAlert[],\n severity: `${ALERT_SEVERITY}`\n): boolean {\n return alerts.find(a => a.raw.severity === severity) !== undefined\n}\n\nfunction alertSeverityComparator(\n a: SocketPackageAlert,\n b: SocketPackageAlert\n): number {\n return getAlertSeverityOrder(a) - getAlertSeverityOrder(b)\n}\n\nfunction getAlertSeverityOrder(alert: SocketPackageAlert): number {\n const { severity } = alert.raw\n return severity === ALERT_SEVERITY.critical\n ? 0\n : severity === ALERT_SEVERITY.high\n ? 1\n : severity === ALERT_SEVERITY.middle\n ? 2\n : severity === ALERT_SEVERITY.low\n ? 3\n : 4\n}\n\nfunction getAlertsSeverityOrder(alerts: SocketPackageAlert[]): number {\n return alertsHaveBlocked(alerts) ||\n alertsHaveSeverity(alerts, ALERT_SEVERITY.critical)\n ? 0\n : alertsHaveSeverity(alerts, ALERT_SEVERITY.high)\n ? 1\n : alertsHaveSeverity(alerts, ALERT_SEVERITY.middle)\n ? 2\n : alertsHaveSeverity(alerts, ALERT_SEVERITY.low)\n ? 3\n : 4\n}\n\nexport type RiskCounts = {\n critical: number\n high: number\n middle: number\n low: number\n}\n\nfunction getHiddenRiskCounts(hiddenAlerts: SocketPackageAlert[]): RiskCounts {\n const riskCounts = {\n critical: 0,\n high: 0,\n middle: 0,\n low: 0\n }\n for (const alert of hiddenAlerts) {\n switch (getAlertSeverityOrder(alert)) {\n case ALERT_SEVERITY_ORDER.critical:\n riskCounts.critical += 1\n break\n case ALERT_SEVERITY_ORDER.high:\n riskCounts.high += 1\n break\n case ALERT_SEVERITY_ORDER.middle:\n riskCounts.middle += 1\n break\n case ALERT_SEVERITY_ORDER.low:\n riskCounts.low += 1\n break\n }\n }\n return riskCounts\n}\n\nfunction getHiddenRisksDescription(riskCounts: RiskCounts): string {\n const descriptions: string[] = []\n if (riskCounts.critical) {\n descriptions.push(`${riskCounts.critical} ${getSeverityLabel('critical')}`)\n }\n if (riskCounts.high) {\n descriptions.push(`${riskCounts.high} ${getSeverityLabel('high')}`)\n }\n if (riskCounts.middle) {\n descriptions.push(`${riskCounts.middle} ${getSeverityLabel('middle')}`)\n }\n if (riskCounts.low) {\n descriptions.push(`${riskCounts.low} ${getSeverityLabel('low')}`)\n }\n return `(${descriptions.join('; ')})`\n}\n\nfunction getSeverityLabel(severity: `${ALERT_SEVERITY}`): string {\n return severity === 'middle' ? 'moderate' : severity\n}\n\nexport type AlertIncludeFilter = {\n actions?: ALERT_ACTION[] | undefined\n blocked?: boolean | undefined\n critical?: boolean | undefined\n cve?: boolean | undefined\n existing?: boolean | undefined\n unfixable?: boolean | undefined\n upgradable?: boolean | undefined\n}\n\nexport type AddSocketArtifactAlertToAlertsMapOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n overrides?: { [key: string]: string } | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function addArtifactToAlertsMap<T extends AlertsByPkgId>(\n artifact: CompactSocketArtifact,\n alertsByPkgId: T,\n options?: AddSocketArtifactAlertToAlertsMapOptions | undefined\n): Promise<T> {\n // Make TypeScript happy.\n if (!artifact.name || !artifact.version || !artifact.alerts?.length) {\n return alertsByPkgId\n }\n const {\n consolidate = false,\n include: _include,\n overrides\n } = {\n __proto__: null,\n ...options\n } as AddSocketArtifactAlertToAlertsMapOptions\n\n const include = {\n __proto__: null,\n actions: undefined,\n blocked: true,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgradable: false,\n ..._include\n } as AlertIncludeFilter\n\n const name = resolvePackageName(artifact)\n const { version } = artifact\n const pkgId = `${name}@${version}`\n const major = semver.major(version)\n const socketYml = findSocketYmlSync()\n const enabledState = {\n __proto__: null,\n ...socketYml?.parsed.issueRules\n } as Partial<Record<ALERT_TYPE, boolean>>\n let sockPkgAlerts: SocketPackageAlert[] = []\n for (const alert of artifact.alerts) {\n const action = alert.action ?? ''\n const enabledFlag = enabledState[alert.type]\n if (\n (action === 'ignore' && enabledFlag !== true) ||\n enabledFlag === false\n ) {\n continue\n }\n const blocked = action === 'error'\n const critical = alert.severity === ALERT_SEVERITY.critical\n const cve = isArtifactAlertCve(alert)\n const fixType = alert.fix?.type ?? ''\n const fixableCve = fixType === ALERT_FIX_TYPE.cve\n const fixableUpgrade = fixType === ALERT_FIX_TYPE.upgrade\n const fixable = fixableCve || fixableUpgrade\n const upgradable = fixableUpgrade && !hasOwn(overrides, name)\n if (\n (include.blocked && blocked) ||\n (include.critical && critical) ||\n (include.cve && cve) ||\n (include.unfixable && !fixable) ||\n (include.upgradable && upgradable)\n ) {\n sockPkgAlerts.push({\n name,\n version,\n key: alert.key,\n type: alert.type,\n blocked,\n critical,\n fixable,\n raw: alert,\n upgradable\n })\n }\n }\n if (!sockPkgAlerts.length) {\n return alertsByPkgId\n }\n if (consolidate) {\n const highestForCve = new Map<\n number,\n { alert: SocketPackageAlert; version: string }\n >()\n const highestForUpgrade = new Map<\n number,\n { alert: SocketPackageAlert; version: string }\n >()\n const unfixableAlerts: SocketPackageAlert[] = []\n for (const sockPkgAlert of sockPkgAlerts) {\n const alert = sockPkgAlert.raw\n const fixType = alert.fix?.type ?? ''\n if (fixType === ALERT_FIX_TYPE.cve) {\n const patchedVersion =\n alert.props[CVE_ALERT_PROPS_FIRST_PATCHED_VERSION_IDENTIFIER]\n const patchedMajor = semver.major(patchedVersion)\n const oldHighest = highestForCve.get(patchedMajor)\n const highest = oldHighest?.version ?? '0.0.0'\n if (semver.gt(patchedVersion, highest)) {\n highestForCve.set(patchedMajor, {\n alert: sockPkgAlert,\n version: patchedVersion\n })\n }\n } else if (fixType === ALERT_FIX_TYPE.upgrade) {\n const oldHighest = highestForUpgrade.get(major)\n const highest = oldHighest?.version ?? '0.0.0'\n if (semver.gt(version, highest)) {\n highestForUpgrade.set(major, { alert: sockPkgAlert, version })\n }\n } else {\n unfixableAlerts.push(sockPkgAlert)\n }\n }\n sockPkgAlerts = [\n ...unfixableAlerts,\n ...[...highestForCve.values()].map(d => d.alert),\n ...[...highestForUpgrade.values()].map(d => d.alert)\n ]\n }\n if (sockPkgAlerts.length) {\n sockPkgAlerts.sort((a, b) => naturalCompare(a.type, b.type))\n alertsByPkgId.set(pkgId, sockPkgAlerts)\n }\n return alertsByPkgId\n}\n\nexport type CveExcludeFilter = {\n upgradable?: boolean | undefined\n}\n\nexport type CveInfoByPkgId = Map<\n string,\n Array<{\n firstPatchedVersionIdentifier: string\n vulnerableVersionRange: string\n }>\n>\n\nexport type GetCveInfoByPackageOptions = {\n exclude?: CveExcludeFilter | undefined\n}\n\nexport function getCveInfoByAlertsMap(\n alertsMap: AlertsByPkgId,\n options?: GetCveInfoByPackageOptions | undefined\n): CveInfoByPkgId | null {\n const exclude = {\n upgradable: true,\n ...({ __proto__: null, ...options } as GetCveInfoByPackageOptions).exclude\n }\n let infoByPkg: CveInfoByPkgId | null = null\n for (const [pkgId, sockPkgAlerts] of alertsMap) {\n const purlObj = PackageURL.fromString(`pkg:npm/${pkgId}`)\n const name = resolvePackageName(purlObj)\n for (const sockPkgAlert of sockPkgAlerts) {\n const alert = sockPkgAlert.raw\n if (\n alert.fix?.type !== ALERT_FIX_TYPE.cve ||\n (exclude.upgradable && getManifestData(NPM, name))\n ) {\n continue\n }\n if (!infoByPkg) {\n infoByPkg = new Map()\n }\n let infos = infoByPkg.get(name)\n if (!infos) {\n infos = []\n infoByPkg.set(name, infos)\n }\n const { firstPatchedVersionIdentifier, vulnerableVersionRange } =\n alert.props\n infos.push({\n firstPatchedVersionIdentifier,\n vulnerableVersionRange: new semver.Range(\n vulnerableVersionRange\n ).format()\n })\n }\n }\n return infoByPkg\n}\n\nexport type LogAlertsMapOptions = {\n hideAt?: `${ALERT_SEVERITY}` | 'none' | undefined\n output?: NodeJS.WriteStream | undefined\n}\n\nexport function logAlertsMap(\n alertsMap: AlertsByPkgId,\n options: LogAlertsMapOptions\n) {\n const { hideAt = 'middle', output = process.stderr } = {\n __proto__: null,\n ...options\n } as LogAlertsMapOptions\n\n const translations = getTranslations()\n const sortedEntries = [...alertsMap.entries()].sort(\n (a, b) => getAlertsSeverityOrder(a[1]) - getAlertsSeverityOrder(b[1])\n )\n\n const aboveTheFoldPkgIds = new Set<string>()\n const viewableAlertsByPkgId = new Map<string, SocketPackageAlert[]>()\n const hiddenAlertsByPkgId = new Map<string, SocketPackageAlert[]>()\n\n for (let i = 0, { length } = sortedEntries; i < length; i += 1) {\n const { 0: pkgId, 1: alerts } = sortedEntries[i]!\n const hiddenAlerts: typeof alerts = []\n const viewableAlerts = alerts.filter(a => {\n const keep =\n a.blocked || getAlertSeverityOrder(a) < ALERT_SEVERITY_ORDER[hideAt]\n if (!keep) {\n hiddenAlerts.push(a)\n }\n return keep\n })\n if (hiddenAlerts.length) {\n hiddenAlertsByPkgId.set(pkgId, hiddenAlerts.sort(alertSeverityComparator))\n }\n if (!viewableAlerts.length) {\n continue\n }\n viewableAlerts.sort(alertSeverityComparator)\n viewableAlertsByPkgId.set(pkgId, viewableAlerts)\n if (\n viewableAlerts.find(\n (a: SocketPackageAlert) =>\n a.blocked || getAlertSeverityOrder(a) < ALERT_SEVERITY_ORDER.middle\n )\n ) {\n aboveTheFoldPkgIds.add(pkgId)\n }\n }\n\n // If MIN_ABOVE_THE_FOLD_COUNT is NOT met add more from viewable pkg ids.\n for (const { 0: pkgId } of viewableAlertsByPkgId.entries()) {\n if (aboveTheFoldPkgIds.size >= MIN_ABOVE_THE_FOLD_COUNT) {\n break\n }\n aboveTheFoldPkgIds.add(pkgId)\n }\n // If MIN_ABOVE_THE_FOLD_COUNT is STILL NOT met add more from hidden pkg ids.\n for (const { 0: pkgId, 1: hiddenAlerts } of hiddenAlertsByPkgId.entries()) {\n if (aboveTheFoldPkgIds.size >= MIN_ABOVE_THE_FOLD_COUNT) {\n break\n }\n aboveTheFoldPkgIds.add(pkgId)\n const viewableAlerts = viewableAlertsByPkgId.get(pkgId) ?? []\n if (viewableAlerts.length < MIN_ABOVE_THE_FOLD_ALERT_COUNT) {\n const neededCount = MIN_ABOVE_THE_FOLD_ALERT_COUNT - viewableAlerts.length\n let removedHiddenAlerts: SocketPackageAlert[] | undefined\n if (hiddenAlerts.length - neededCount > 0) {\n removedHiddenAlerts = hiddenAlerts.splice(\n 0,\n MIN_ABOVE_THE_FOLD_ALERT_COUNT\n )\n } else {\n removedHiddenAlerts = hiddenAlerts\n hiddenAlertsByPkgId.delete(pkgId)\n }\n viewableAlertsByPkgId.set(pkgId, [\n ...viewableAlerts,\n ...removedHiddenAlerts\n ])\n }\n }\n\n const mentionedPkgIdsWithHiddenAlerts = new Set<string>()\n for (\n let i = 0,\n prevAboveTheFold = true,\n entries = [...viewableAlertsByPkgId.entries()],\n { length } = entries;\n i < length;\n i += 1\n ) {\n const { 0: pkgId, 1: alerts } = entries[i]!\n const lines = new Set<string>()\n for (const alert of alerts) {\n const { type } = alert\n const severity = alert.raw.severity ?? ''\n const attributes = [\n ...(severity\n ? [colors[ALERT_SEVERITY_COLOR[severity]](getSeverityLabel(severity))]\n : []),\n ...(alert.blocked ? [colors.bold(colors.red('blocked'))] : []),\n ...(alert.fixable ? ['fixable'] : [])\n ]\n const maybeAttributes = attributes.length\n ? ` ${colors.italic(`(${attributes.join('; ')})`)}`\n : ''\n // Based data from { pageProps: { alertTypes } } of:\n // https://socket.dev/_next/data/94666139314b6437ee4491a0864e72b264547585/en-US.json\n const info = (translations.alerts as any)[type]\n const title = info?.title ?? type\n const maybeDesc = info?.description ? ` - ${info.description}` : ''\n const content = `${title}${maybeAttributes}${maybeDesc}`\n // TODO: emoji seems to mis-align terminals sometimes\n lines.add(` ${content}`)\n }\n const purlObj = PackageURL.fromString(`pkg:npm/${pkgId}`)\n const hyperlink = format.hyperlink(\n pkgId,\n getSocketDevPackageOverviewUrl(\n NPM,\n resolvePackageName(purlObj),\n purlObj.version\n )\n )\n const isAboveTheFold = aboveTheFoldPkgIds.has(pkgId)\n if (isAboveTheFold) {\n aboveTheFoldPkgIds.add(pkgId)\n output.write(`${i ? '\\n' : ''}${hyperlink}:\\n`)\n } else {\n output.write(`${prevAboveTheFold ? '\\n' : ''}${hyperlink}:\\n`)\n }\n for (const line of lines) {\n output.write(`${line}\\n`)\n }\n const hiddenAlerts = hiddenAlertsByPkgId.get(pkgId) ?? []\n const { length: hiddenAlertsCount } = hiddenAlerts\n if (hiddenAlertsCount) {\n mentionedPkgIdsWithHiddenAlerts.add(pkgId)\n if (hiddenAlertsCount === 1) {\n output.write(\n ` ${colors.dim(`+1 Hidden ${getSeverityLabel(hiddenAlerts[0]!.raw.severity ?? 'low')} risk alert`)}\\n`\n )\n } else {\n output.write(\n ` ${colors.dim(`+${hiddenAlertsCount} Hidden alerts ${colors.italic(getHiddenRisksDescription(getHiddenRiskCounts(hiddenAlerts)))}`)}\\n`\n )\n }\n }\n prevAboveTheFold = isAboveTheFold\n }\n\n const additionalHiddenCount =\n hiddenAlertsByPkgId.size - mentionedPkgIdsWithHiddenAlerts.size\n if (additionalHiddenCount) {\n const totalRiskCounts = {\n critical: 0,\n high: 0,\n middle: 0,\n low: 0\n }\n for (const { 0: pkgId, 1: alerts } of hiddenAlertsByPkgId.entries()) {\n if (mentionedPkgIdsWithHiddenAlerts.has(pkgId)) {\n continue\n }\n const riskCounts = getHiddenRiskCounts(alerts)\n totalRiskCounts.critical += riskCounts.critical\n totalRiskCounts.high += riskCounts.high\n totalRiskCounts.middle += riskCounts.middle\n totalRiskCounts.low += riskCounts.low\n }\n output.write(\n `${aboveTheFoldPkgIds.size ? '\\n' : ''}${colors.dim(`${aboveTheFoldPkgIds.size ? '+' : ''}${additionalHiddenCount} Packages with hidden alerts ${colors.italic(getHiddenRisksDescription(totalRiskCounts))}`)}\\n`\n )\n }\n output.write('\\n')\n}\n","import { detectDepTypes } from '@pnpm/lockfile.detect-dep-types'\n\nimport { arrayUnique } from '@socketsecurity/registry/lib/arrays'\n\nimport { getDetailsFromDiff } from './arborist-helpers'\nimport { getPublicToken, setupSdk } from './sdk'\nimport { addArtifactToAlertsMap } from './socket-package-alert'\n\nimport type { CompactSocketArtifact } from './alert/artifact'\nimport type { AlertIncludeFilter, AlertsByPkgId } from './socket-package-alert'\nimport type { SafeArborist } from '../shadow/npm/arborist/lib/arborist'\nimport type { LockfileObject } from '@pnpm/lockfile.fs'\nimport type { Spinner } from '@socketsecurity/registry/lib/spinner'\n\nexport type GetAlertsMapFromArboristOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n nothrow?: boolean | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function getAlertsMapFromArborist(\n arb: SafeArborist,\n options_?: GetAlertsMapFromArboristOptions | undefined\n): Promise<AlertsByPkgId> {\n const options = {\n __proto__: null,\n consolidate: false,\n nothrow: false,\n ...options_\n } as GetAlertsMapFromArboristOptions\n\n const include = {\n __proto__: null,\n actions: undefined,\n blocked: true,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgradable: false,\n ...options.include\n } as AlertIncludeFilter\n\n const needInfoOn = getDetailsFromDiff(arb.diff, {\n include: {\n unchanged: include.existing\n }\n })\n const purls = needInfoOn.map(d => `pkg:npm/${d.node.pkgid}`)\n\n let overrides: { [key: string]: string } | undefined\n const overridesMap = (\n arb.actualTree ??\n arb.idealTree ??\n (await arb.loadActual())\n )?.overrides?.children\n if (overridesMap) {\n overrides = Object.fromEntries(\n [...overridesMap.entries()].map(([key, overrideSet]) => {\n return [key, overrideSet.value!]\n })\n )\n }\n\n return await getAlertsMapFromPurls(purls, {\n overrides,\n ...options\n })\n}\n\nexport type GetAlertsMapFromPnpmLockfileOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n overrides?: { [key: string]: string } | undefined\n nothrow?: boolean | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function getAlertsMapFromPnpmLockfile(\n lockfile: LockfileObject,\n options_?: GetAlertsMapFromPnpmLockfileOptions | undefined\n): Promise<AlertsByPkgId> {\n const options = {\n __proto__: null,\n consolidate: false,\n nothrow: false,\n ...options_\n } as GetAlertsMapFromPnpmLockfileOptions\n\n const depTypes = detectDepTypes(lockfile)\n const purls = Object.keys(depTypes).map(id => `pkg:npm/${id}`)\n\n return await getAlertsMapFromPurls(purls, {\n overrides: lockfile.overrides,\n ...options\n })\n}\n\nexport type GetAlertsMapFromPurlsOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n overrides?: { [key: string]: string } | undefined\n nothrow?: boolean | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function getAlertsMapFromPurls(\n purls: string[] | readonly string[],\n options_?: GetAlertsMapFromPurlsOptions | undefined\n): Promise<AlertsByPkgId> {\n const options = {\n __proto__: null,\n consolidate: false,\n nothrow: false,\n ...options_\n } as GetAlertsMapFromPurlsOptions\n\n const include = {\n __proto__: null,\n actions: undefined,\n blocked: true,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgradable: false,\n ...options.include\n } as AlertIncludeFilter\n\n const { spinner } = options\n\n const uniqPurls = arrayUnique(purls)\n let { length: remaining } = uniqPurls\n const alertsByPkgId: AlertsByPkgId = new Map()\n if (!remaining) {\n return alertsByPkgId\n }\n const getText = () => `Looking up data for ${remaining} packages`\n\n spinner?.start(getText())\n\n const sockSdk = await setupSdk(getPublicToken())\n\n const toAlertsMapOptions = {\n overrides: options.overrides,\n consolidate: options.consolidate,\n include,\n spinner\n }\n\n for await (const batchResult of sockSdk.batchPackageStream(\n {\n alerts: 'true',\n compact: 'true',\n ...(include.actions ? { actions: include.actions.join(',') } : {}),\n ...(include.unfixable ? {} : { fixable: 'true' })\n },\n {\n components: uniqPurls.map(purl => ({ purl }))\n }\n )) {\n if (batchResult.success) {\n await addArtifactToAlertsMap(\n batchResult.data as CompactSocketArtifact,\n alertsByPkgId,\n toAlertsMapOptions\n )\n } else if (!options.nothrow) {\n const statusCode = batchResult.status ?? 'unknown'\n const statusMessage = batchResult.error ?? 'No status message'\n throw new Error(\n `Socket API server error (${statusCode}): ${statusMessage}`\n )\n }\n remaining -= 1\n if (spinner && remaining > 0) {\n spinner.start()\n spinner.setText(getText())\n }\n }\n\n spinner?.stop()\n\n return alertsByPkgId\n}\n","import process from 'node:process'\n\nimport { codeBlock } from 'common-tags'\n\nimport { logger } from '@socketsecurity/registry/lib/logger'\n\nimport constants from '../../../../../constants'\nimport { getAlertsMapFromArborist } from '../../../../../utils/alerts-map'\nimport { logAlertsMap } from '../../../../../utils/socket-package-alert'\nimport { getArboristClassPath } from '../../../paths'\n\nimport type { ArboristClass, ArboristReifyOptions } from './types'\nimport type { SafeNode } from '../node'\n\nconst {\n NPM,\n NPX,\n SOCKET_CLI_ACCEPT_RISKS,\n SOCKET_CLI_SAFE_BIN,\n SOCKET_CLI_SAFE_PROGRESS,\n SOCKET_CLI_VIEW_ALL_RISKS,\n kInternalsSymbol,\n [kInternalsSymbol as unknown as 'Symbol(kInternalsSymbol)']: { getIpc }\n} = constants\n\nexport const SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES = {\n __proto__: null,\n audit: false,\n dryRun: true,\n fund: false,\n ignoreScripts: true,\n progress: false,\n save: false,\n saveBundle: false,\n silent: true\n}\n\nexport const kCtorArgs = Symbol('ctorArgs')\n\nexport const kRiskyReify = Symbol('riskyReify')\n\nexport const Arborist: ArboristClass = require(getArboristClassPath())\n\n// Implementation code not related to our custom behavior is based on\n// https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/arborist/index.js:\nexport class SafeArborist extends Arborist {\n constructor(...ctorArgs: ConstructorParameters<ArboristClass>) {\n super(\n {\n path:\n (ctorArgs.length ? ctorArgs[0]?.path : undefined) ?? process.cwd(),\n ...(ctorArgs.length ? ctorArgs[0] : undefined),\n ...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES\n },\n ...ctorArgs.slice(1)\n )\n ;(this as any)[kCtorArgs] = ctorArgs\n }\n\n async [kRiskyReify](\n ...args: Parameters<InstanceType<ArboristClass>['reify']>\n ): Promise<SafeNode> {\n const ctorArgs = (this as any)[kCtorArgs]\n const arb = new Arborist(\n {\n ...(ctorArgs.length ? ctorArgs[0] : undefined),\n progress: false\n },\n ...ctorArgs.slice(1)\n )\n const ret = await (arb.reify as (...args: any[]) => Promise<SafeNode>)(\n {\n ...(args.length ? args[0] : undefined),\n progress: false\n },\n ...args.slice(1)\n )\n Object.assign(this, arb)\n return ret\n }\n\n // @ts-ignore Incorrectly typed.\n override async reify(\n this: SafeArborist,\n ...args: Parameters<InstanceType<ArboristClass>['reify']>\n ): Promise<SafeNode> {\n const options = {\n __proto__: null,\n ...(args.length ? args[0] : undefined)\n } as ArboristReifyOptions\n const ipc = await getIpc()\n const binName = ipc[SOCKET_CLI_SAFE_BIN]\n if (!binName) {\n return await this[kRiskyReify](...args)\n }\n await super.reify(\n {\n ...options,\n ...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES,\n progress: false\n },\n // @ts-ignore: TypeScript gets grumpy about rest parameters.\n ...args.slice(1)\n )\n // Lazily access constants.ENV[SOCKET_CLI_ACCEPT_RISKS].\n const acceptRisks = constants.ENV[SOCKET_CLI_ACCEPT_RISKS]\n // Lazily access constants.ENV[SOCKET_CLI_VIEW_ALL_RISKS].\n const viewAllRisks = constants.ENV[SOCKET_CLI_VIEW_ALL_RISKS]\n const progress = ipc[SOCKET_CLI_SAFE_PROGRESS]\n const spinner =\n options['silent'] || !progress\n ? undefined\n : // Lazily access constants.spinner.\n constants.spinner\n const isSafeNpm = binName === NPM\n const isSafeNpx = binName === NPX\n const alertsMap = await getAlertsMapFromArborist(this, {\n spinner,\n include:\n acceptRisks || options.dryRun || options['yes']\n ? {\n actions: ['error'],\n blocked: true,\n critical: false,\n cve: false,\n existing: true,\n unfixable: false\n }\n : {\n existing: isSafeNpx,\n unfixable: isSafeNpm\n }\n })\n if (alertsMap.size) {\n process.exitCode = 1\n logAlertsMap(alertsMap, {\n hideAt: viewAllRisks ? 'none' : 'middle',\n output: process.stderr\n })\n throw new Error(\n codeBlock`\n Socket ${binName} exiting due to risks.${\n viewAllRisks\n ? ''\n : `\\nView all risks - Rerun with environment variable ${SOCKET_CLI_VIEW_ALL_RISKS}=1.`\n }${\n acceptRisks\n ? ''\n : `\\nAccept risks - Rerun with environment variable ${SOCKET_CLI_ACCEPT_RISKS}=1.`\n }\n `\n )\n } else if (!options['silent']) {\n logger.success(\n `Socket ${binName} ${acceptRisks ? 'accepted' : 'found no'} risks`\n )\n if (binName === NPX) {\n logger.log(`Running ${options.add![0]}`)\n }\n }\n return await this[kRiskyReify](...args)\n }\n}\n","import {\n getArboristClassPath,\n getArboristEdgeClassPath,\n getArboristNodeClassPath,\n getArboristOverrideSetClassPath\n} from '../paths'\nimport { SafeArborist } from './lib/arborist'\nimport { SafeEdge } from './lib/edge'\nimport { SafeNode } from './lib/node'\nimport { SafeOverrideSet } from './lib/override-set'\n\nexport function installSafeArborist() {\n // Override '@npmcli/arborist' module exports with patched variants based on\n // https://github.com/npm/cli/pull/8089.\n const cache: { [key: string]: any } = require.cache\n cache[getArboristClassPath()] = { exports: SafeArborist }\n cache[getArboristEdgeClassPath()] = { exports: SafeEdge }\n cache[getArboristNodeClassPath()] = { exports: SafeNode }\n cache[getArboristOverrideSetClassPath()] = { exports: SafeOverrideSet }\n}\n","import { installSafeArborist } from './arborist'\n\ninstallSafeArborist()\n"],"names":["PNPM","workspacePatterns","throws","length","cwd","__proto__","absolute","expandDirectories","ignore","abortSignal","signal","root","dir","encoding","XDG_DATA_HOME","ok","message","_cachedConfig","_readOnlyConfig","logger","updateConfigValue","recursive","WIN32","constants","_warnedConfigPathWin32Missing","dataHome","_configPath","yml","path","parsed","prevDir","localConfig","_pendingSave","getSentry","constructor","SOCKET_SECURITY_API_TOKEN","_defaultToken","agent","proxy","baseUrl","name","version","homepage","RangeStyles","debugLog","DiffAction","UNDEFINED_TOKEN","id","transformer","mod","canDedupe","canReplaceWith","overrides","recalculateOutEdgesOverrides","edge","newOverrideSet","from","detach","explain","bundled","overridden","error","rawSpec","explanation","reload","needToUpdateOverrideSet","NPM_REGISTRY_URL","eligibleVersions","getMajor","queue","matches","unchanged","unknownOrigin","action","actual","ideal","keep","existing","node","Object","configurable","enumerable","integrity","dependencies","spec","type","result","ALERT_TYPE_MILD_CVE","ALERT_FIX_TYPE","ALERT_SEVERITY","low","middle","high","critical","value","severity","severityCount","header","hyperlink","fallback","fallbackToUrl","_translations","ALERT_SEVERITY_COLOR","ALERT_SEVERITY_ORDER","NPM","descriptions","consolidate","include","actions","cve","upgradable","raw","highestForCve","alert","highestForUpgrade","unfixableAlerts","sockPkgAlerts","alertsByPkgId","infoByPkg","infos","vulnerableVersionRange","hideAt","hiddenAlerts","viewableAlerts","viewableAlertsByPkgId","aboveTheFoldPkgIds","removedHiddenAlerts","hiddenAlertsByPkgId","lines","output","mentionedPkgIdsWithHiddenAlerts","prevAboveTheFold","totalRiskCounts","nothrow","unfixable","blocked","spinner","alerts","compact","fixable","components","purl","remaining","getIpc","audit","dryRun","fund","ignoreScripts","progress","save","saveBundle","silent","cache","exports","installSafeArborist"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA;;AAAaA;AAAK;AAElB;AAEA;AACE;AACA;AACA;AAAQ;AACR;AAAQ;AACR;AAAe;AACf;AAAe;AACf;AAAS;AACT;AAAoB;AACpB;AAAY;AACZ;AAAgB;AAChB;AACA;AACA;AAGF;AAEA;AAIE;;;AAMI;AACA;AACA;;AAEIC;;AAEF;AACE;AACF;AACF;AACF;AACF;AACEA;AAAkDC;;AAGpD;AACA;AAKF;AAEA;;;AAOE;AAAkBC;;;AAEhB;;AAQA;AACF;AACA;AACF;AAEA;AAKE;AACF;;AAEA;AACA;AACA;AACA;AACA;AACE;AACA;AACA;AACA;AACA;AAME;AACF;AACA;AACA;AAIA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AAQF;AAEA;;AACUA;AAAO;;AAEb;AACF;AACA;;;AAGA;AACA;AACA;;AAMA;AACA;;AAEF;AAEO;;AAMD;;AAMA;;AAIJ;AACF;AAMO;;AAKHC;;;AAGF;AAAMC;;;AACN;;AAEEC;;AAEAC;AACF;AACA;AAqBA;AACA;AACED;;AAEAC;AACAC;;;;;AAKA;AACF;;AACQF;AAAS;;AAEjB;AACA;AACA;AAGA;AACF;AAEO;AACL;AACEA;AACAF;AACF;AACF;AAEO;;;AAOCE;;AAEAE;;AAGR;AAEO;AAGL;AACA;AACF;;AC9PA;AAAQC;AAAY;AAEb;AACL;AACA;AACF;AAOO;AAEHL;AAAqBM;AAAoC;AAE3D;;AACQC;AAAK;;AAEb;AACE;;AAEI;AACF;;;AAGE;;AAEA;AACE;AACF;;AAEJ;AACAC;AACF;AACA;AACF;AASO;AAIL;AACEF;AACA;AACAG;AACF;AACF;AAEO;AAIL;AACEH;AACA;AACAG;AACF;AACF;AAOO;;AAKH;AACEA;AACAH;AACA;AAAoCG;AAAkB;AACxD;;AAEF;AACF;AAOO;;;AAYDA;AACA;AAAoCA;AAAkB;AACxD;;AAEF;AACF;;ACnHA;;;AAAsCC;AAAc;;AA4B7C;AAEP;AACA;AACA;AAEO;;AAKL;;;AAGE;AACE;AACA;;AAEF;AACF;;AAEIC;AACAC;;AAGJ;;AAEA;AACAC;AACAC;;AAEA;AACA;AACE;AACEC;AAGF;AACAF;;AAEF;;AAESF;AAAUC;;AACrB;AAEO;;AAEL;AACAC;AACE;AACA;;;;AAEFC;AACF;AAEA;;;AAGI;AACA;AACA;AACE;AACA;;;AAME;AACEC;AACF;AACA;AACA;AACA;AACE;;AAEAC;AACF;AACF;;AAC2CC;AAAgB;AAC3D;AACF;AACF;AACA;AACF;AAEA;AACA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGE;;AACQC;AAAM;;AAEV;AACAC;AACA;AACAA;;AAEF;;AAEIC;AACAL;AACF;AACF;AACEM;AAMF;AACF;AACAC;AACF;AACA;AACF;AAEA;AACE;AACA;;AAEA;AACE;AACF;AACA;AACF;AAEO;;;;AAIH;;;AAGEC;AACF;AACA;;;AAGMC;AACAC;;AAEJ;AACE;AACF;AACF;AACAC;;AAEF;AACA;AACF;AAEO;AAGL;AACA;AACF;AACO;AACL;AACF;AAEA;AACO;AAIL;AACAC;AACA;AACEZ;AAGF;AACEa;;AAEEA;AACA;AACA;;AAKA;AACF;AACF;AACF;;ACxOA;;AAEE;AAA+DC;AAAU;AAC3E;AAIO;AAEA;AAGLC;;;AAGA;AACF;AAEO;AAIL;AACA;;AAEA;AACF;AAEO;AAIL;;AAEE;AACF;;AAEA;AACF;;AC9BA;;;;AAIEC;AACF;;AAEA;AACA;AACE;AACE;;AAEF;AACF;;AAEA;AACA;AACE;AACE;;AAEF;AACF;;AAEA;AACA;AACO;AACL;AACA;AACEC;AACF;AACE;AACE;;;AAKJ;AACA;AACF;AAEO;AACL;AACE;;AAEuB;AAE3B;AAEO;;;AAODpB;AAEF;AACAoB;AACF;;AAEE;AACF;AACA;AACEC;AAAqCC;;AACrCC;;AAEE;AACAC;AACA;AACAC;AACA;AACAC;;AAEJ;AACF;;ACrFaC;AAYN;AAKL;AACE;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;AAAiB;AACf;;AACQxC;AAAO;AACf;AAGF;AACA;;AAEA;AACA;AACE;AACJ;AACF;AAEO;AACL;AACA;;AAEI;;AAEAyC;AACF;AACF;AACA;AACF;;ACLYC;;;;AAAU;AAAA;;AChDf;;ACDP;AAAQC;AAAgB;AAaxB;AAIE;AACE;AACA;AACA;AACEC;AACAC;AACF;AACED;;AAEF;;AAEE;AACA;;;AAGE;AACF;;AAEJ;AACA;AACF;AAOA;AACO;;;AAMC;AACA;AACAE;AAIN;AACA;AACF;;AChCA;;AAEA;AACA;AACO;AACL;AACA;AACA;AAIE;AACA;AACA;;AAEF;;AAEA;AACA;AACA;AAIE;AAKE;AACE;AACF;AACF;AACA;AAKE;AACE;AACF;AACF;AACA;AACA;;AAEA;AACF;;AAEA;AACA;;;AAGI;AACF;AACA;AAAa;AAAQ;AAAoB;;;AAGrC;AACF;AACA;AACE;AACF;AACA;AACE;AACF;AACF;AACA;AACF;;;AAII;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACE;AACE;AACF;AACA;AACF;;AAEE;AAGE;AACF;AACA;AACF;AACA;AACA;AACA;AACA;AACF;AACA;AACF;;AAEA;AACA;;;AAGI;AACF;;AAEE;AACF;AACA;AAIE;AACF;AACA;AACE;AACF;AACA;;AAEA;;AAEF;AACF;;ACpFA;;AAEA;AACA;AACO;AACL;AACA;AACA;AACSC;AACP;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;;AAEE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACE;AACF;AACA;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACSC;AACP;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;;;AAGI;AACF;AACF;;AAEI;AACF;AACF;AACF;AACA;AACA;AACA;AACA;AACA;;AAEA;AACE;AACF;;;;;;AAME;AACF;AACA;AACF;;AAEA;;AAEE;;AACQC;AAAU;AAClB;AACE;AACF;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;;AAEF;;AAEA;;AAEE;AACA;AACA;;AAME;AACF;AACA;AACA;AACA;AACA;AACA;AACA;;AAMI;AACE;AACF;AACF;AACF;AACA;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACQA;AAAU;AAClB;;AAEA;;;;;;AAME;AACF;AACF;;AAEA;AACA;AACSC;AACP;;AAEEC;;;AAGA;AACF;AACF;;AAEA;;AAEE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AAAuCF;AAAc;AACvD;;;;;;AAME;AACF;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAKI;AACA;AACA;AACA;AACA;AACF;AACA;;;AAGE;AACF;;AAEE;AACF;;AAKA;;AAEI;AACF;;;AAGA;AACF;AACA;AACA;AACA;;AAEA;AACF;;AAEA;AACA;;AAEE;AACA;AACA;AACE;AACF;AACA;AACA;;AACUA;AAAyB;;;AAMjC;AACEG;AACF;AACF;;AAEE;AACF;;AAEA;AACE;AACA;AACA;AACA;AACA;;AAEF;AACA;AACF;AACF;;ACrUO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACL;AACA;AACA;AACA;;;AAGUC;AAAK;AACb;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACF;;AAGE;AACF;;AAGE;AACE;;AAEI;AACF;AACE;AACF;AACF;AAGE;AACA;AACA;AAEA;AACF;AACE;AACF;AACA;AACA;AAAA;AASE;AACA;AACA;AACA;AACA;AACA;AACF;AACE;AACF;AACF;AACA;AACE;AACF;;AAEF;;AAEA;;;AAGA;;AAEA;;;;;AASM;AACA;AACA;AACA;AACA;;AAIA;AACE;AACF;AACA;AACE;AACF;AACA;AACE;AACF;AACA;AACE;AACF;;AAEF;AACA;AACF;;AAEF;;AAEA;;;AAGA;AAESC;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACF;;AAEA;AACA;AACSC;AACP;AACE;;;;AAIEC;AACAC;AACAC;AACAL;AACAM;;AAEF;AACEC;;AAEF;;AAEEA;AACF;;AAEEA;AACF;AACA;;AAEA;AACA;AACF;;AAEF;AAESC;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGI;AACA;AACA;AACA;AACAC;;;AAGF;AACF;;AAEA;AACA;AACA;AACA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACF;AACA;AACA;AAAA;AAEE;AACA;AACA;AACF;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;;AAEE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF;AACF;;AC9SA;;;AAA4BC;AAAiB;AAE7C;;AAEI;AACA;AACA;;;AAGF;AACF;AAEO;;AAOL;;AAEE;AACA;AACE;AACF;AACAC;AACF;AACE;AACA;AACE;AACF;AACAA;AAEI;AACA;AACAC;AAIN;;AAEF;AAEO;AAKL;;;AAGE;AACE;AACF;AACA;;AAEA;AACE;AACF;;AAEA;AACEC;AACF;AACF;AACF;AAEO;AAKL;;;;AAIE;AACE;AACF;AACA;;AAEA;AACEC;AACF;;AAEA;AACED;AACF;AACF;AACA;AACF;AAgBO;;AAKL;;AAEE;AACF;AAEA;AACEhE;AACAkE;AACAC;;AACMnE;;AAA4B;;AAGpC;;;AAEMF;AAAoB;;;AAGtB;AACF;AACA;;AACQsE;AAAO;AACf;AACE;AACA;AACA;AACA;;AACQC;AAAiBC;AAAe;AACxC;;AAEA;;AAEIC;AACA;AAIEC;AACF;AACF;AAIF;AACED;AACF;AACA;AACE;;AAKIE;AACAD;AACF;AACF;AACF;AACF;AACA;AACER;AACF;AACF;;;AAEUE;AAAU;AAClB;AAAkBpE;;AAChB;AACA;;AAKI2E;AACAD;AACF;AACF;AACF;AACF;AACA;AACF;AAEO;;AAEP;AAOO;AAKL;AACA;AACAE;AACEC;AACAC;;AAEF;AACA;AACAH;AACA;;AAEAA;AACA;AACA;;AACQI;;AACR;;AAEA;;AAEA;AACA;AACA;;AAEA;AACE;AACF;AACA;AACA;AAAkB;;;AACVC;;AACRL;AACA;;AAEI;AACE;AACA;;AAEF;AACF;AACF;;AAEE;AACE;AACA;AACAA;AAEItB;AACAhB;AACA4C;AACAC;AACF;AAEJ;AACF;AACF;AAEO;;AAQL;AACE;AACF;;AACQ7C;AAAK;;AAMX;AAGA;AACE;AACA;;;AAGI8C;;AAEE;AACE;AACA;AACF;AACF;AACF;AACF;AACF;AACF;AACA;AACF;;AC/PA;;;;AAIEC;AACF;AAEO;;AAGGF;AAAK;AACb;AAMF;;AC7EYG;;;;AAAc;AAAA;;ACAnB;;AAKL;AACEF;AACF;AACA;AACF;;ACTO;AAIL;;AACQnF;AAAO;;AAEb;AACF;;;AAGA;AACA;;AAEF;;ACTYsF;;;;;AAAc;AAAA;AAgB1B;AACO;AAIP;;AAIE;AACEH;;AAEE;AACF;AACF;AACA;AACF;AAEO;;AAIL;AACE;;AAEA;AACF;;AAEF;AAEO;;AAKDI;AAAQC;AAAWC;AAASC;AAAY;AAI5C;;AACUC;AAAM;;AAEZ;AACF;;AACQC;AAAS;AACjB;AACEC;AACF;AACF;AACA;AACF;;AClEO;;AAIH;AACF;;AAGE;AACF;AAEAC;AACE;AAGF;AAEAC;AAIIC;AACAC;;AAMF;AACE;;AAII;AACN;AACA;AACF;;AAKE;AACF;;AAGE;AACF;;;AAMA;;AAGE;;AAIF;AACF;;ACjEO;;AAEP;AAEO;AAKL;AACF;;ACNA;AAEO;;AAEHC;AACE;;AAGJ;AACA;AACF;;ACYYC;;;;;AAAoB;AAAA;AAOpBC;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAoB;AAAA;AAsBhC;;AAA0DC;AAAI;AAE9D;AAEA;AAEA;AAEA;;AAEA;AAEA;AAIE;AACF;AAEA;;AAKA;AAEA;;AACUT;;AACR;AASF;AAEA;;AAWA;AASA;AACE;AACEF;AACAD;AACAD;AACAD;;AAEF;;;;AAIM;;;AAGA;;;AAGA;;;AAGA;AACJ;AACF;AACA;AACF;AAEA;;;AAGIe;AACF;;AAEEA;AACF;;AAEEA;AACF;;AAEEA;AACF;AACA;AACF;AAEA;AACE;AACF;AAmBO;AAKL;AACA;AACE;AACF;;AAEEC;AACAC;AACAvD;AACF;AACE/C;;;AAIF;AACEA;AACAuG;AAEAf;AACAgB;AACAhC;AAEAiC;;;AAIF;;AACQrE;AAAQ;AAChB;AACA;AACA;AACA;AACEpC;;;;AAIF;AACE;AACA;;AAKE;AACF;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;;;;;;;;AAeI0G;AACAD;AACF;AACF;AACF;AACA;AACE;AACF;AACA;AACE;AAIA;;AAKA;AACE;;AAEA;AACE;AAEA;AACA;AACA;;AAEEE;AACEC;AACAxE;AACF;AACF;AACF;AACE;AACA;;AAEEyE;AAA+BD;AAAqBxE;AAAQ;AAC9D;AACF;AACE0E;AACF;AACF;AACAC;AAKF;;AAEEA;AACAC;AACF;AACA;AACF;AAkBO;AAIL;AACEP;;AACMzG;;AAA4B;;;;;AAKlC;AACA;AACE;;AAKE;AACF;;AAEEiH;AACF;AACA;;AAEEC;AACAD;AACF;;;AACuCE;;;;;AAOvC;AACF;AACF;AACA;AACF;AAOO;;AAIGC;;AAA2C;AACjDpH;;;AAIF;AACA;AAIA;AACA;AACA;AAEA;AAAkBF;;;AACR;AAAU;AAAU;;AAE5B;AACE;;AAGEuH;AACF;AACA;AACF;;;AAGA;AACA;AACE;AACF;AACAC;AACAC;AACA;AAMEC;AACF;AACF;;AAEA;AACA;AAAa;AAAS;AACpB;AACE;AACF;AACAA;AACF;AACA;AACA;AAAa;AAAU;AAAgB;AACrC;AACE;AACF;AACAA;;AAEA;AACE;AACA;AACA;;AAKA;AACEC;AACAC;AACF;AACAH;AAIF;AACF;AAEA;AACA;AAIMzH;;;AAII;AAAU;AAAU;AAC5B;AACA;;AACUkF;AAAK;;;;AAYb;AACA;AACA;AACA;AACA;;AAEA;AACA2C;AACF;;;AAUA;AACA;AACEH;AACAI;AACF;AACEA;AACF;AACA;AACEA;AACF;;;AAEQ9H;AAA0B;AAClC;AACE+H;;;AAKA;;AAIA;AACF;AACAC;AACF;;AAIA;AACE;AACEtC;AACAD;AACAD;AACAD;;AAEF;AAAa;AAAU;AAAU;AAC/B;AACE;AACF;AACA;AACA0C;AACAA;AACAA;AACAA;AACF;AACAH;AAGF;AACAA;AACF;;ACxgBO;AAIL;AACE5H;AACAqG;AACA2B;;;AAIF;AACEhI;AACAuG;AAKA0B;;AAKF;AACE3B;;AAEA;AACF;AACA;AAEA;;AAMA;;AAGM;AACF;AAEJ;AAEA;;;AAGA;AACF;AAUO;AAIL;AACEtG;AACAqG;AACA2B;;;AAIF;AACA;AAEA;;;AAGA;AACF;AAUO;AAIL;AACEhI;AACAqG;AACA2B;;;AAIF;AACEhI;AACAuG;AACA2B;AACA1C;AACAgB;AACAhC;AACAyD;AACAxB;AACA;;;AAGM0B;AAAQ;AAEhB;;AACMrI;AAAkB;AACxB;;AAEE;AACF;AACA;AAEAqI;;AAIA;;;;AAIEA;;AAGF;AAEIC;AACAC;;AACwB9B;;AACxB;AAA+B+B;;AACjC;AAEEC;AAAqCC;AAAK;AAC5C;;;AAQA;AACE;AACA;;AAIF;AACAC;AACA;;AAEEN;AACF;AACF;;AAIA;AACF;;AC3KA;;;;;;;;AAQE;AAA+DO;AAAO;AACxE;AAEO;AACL1I;AACA2I;AACAC;AACAC;AACAC;AACAC;AACAC;AACAC;AACAC;AACF;AAEO;AAEA;AAEA;;AAEP;AACA;AACO;;AAEH;AAEI3H;;;;AAOF;AACJ;AAEA;AAGE;AACA;;AAGIwH;;AAIJ;;AAGIA;;AAIJrE;AACA;AACF;;AAEA;AACA;AAIE;AACE1E;;;AAGF;AACA;;;AAGA;;AAGI;AACA;AACA+I;;AAEF;AACA;AAEF;AACA;AACA;AACA;AACA;;AAIM;AACA7H;AACN;AACA;AACA;;;;AAMUgH;AACA1C;AACAgB;AACAhC;AACAyD;AACF;AAEEzD;AACAyD;AACF;AACR;;;;AAIIb;;AAEF;;AAGN;AAQA;AAGI;AACEtG;;;AAKA;AACF;;AAEF;AACF;;ACvJO;AACL;AACA;AACA;AACAqI;AAAkCC;;AAClCD;AAAsCC;;AACtCD;AAAsCC;;AACtCD;AAA6CC;;AAC/C;;ACjBAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","debugId":"c02ab858-0e49-4840-879d-c47d5d79aaff"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shadow-npm-paths.js","sources":["../src/utils/path-resolve.ts","../src/shadow/npm/paths.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs'\nimport path from 'node:path'\n\nimport which from 'which'\n\nimport { debugLog, isDebug } from '@socketsecurity/registry/lib/debug'\nimport { resolveBinPath } from '@socketsecurity/registry/lib/npm'\nimport { pluralize } from '@socketsecurity/registry/lib/words'\n\nimport constants from '../constants'\nimport {\n filterGlobResultToSupportedFiles,\n globWithGitIgnore,\n pathsToGlobPatterns\n} from './glob'\n\nimport type { SocketYml } from '@socketsecurity/config'\nimport type { SocketSdkReturnType } from '@socketsecurity/sdk'\n\nconst { NODE_MODULES, NPM, shadowBinPath } = constants\n\nexport function findBinPathDetailsSync(binName: string): {\n name: string\n path: string | undefined\n shadowed: boolean\n} {\n const binPaths =\n which.sync(binName, {\n all: true,\n nothrow: true\n }) ?? []\n let shadowIndex = -1\n let theBinPath: string | undefined\n for (let i = 0, { length } = binPaths; i < length; i += 1) {\n const binPath = binPaths[i]!\n // Skip our bin directory if it's in the front.\n if (path.dirname(binPath) === shadowBinPath) {\n shadowIndex = i\n } else {\n theBinPath = resolveBinPath(binPath)\n break\n }\n }\n return { name: binName, path: theBinPath, shadowed: shadowIndex !== -1 }\n}\n\nexport function findNpmPathSync(npmBinPath: string): string | undefined {\n // Lazily access constants.WIN32.\n const { WIN32 } = constants\n let thePath = npmBinPath\n while (true) {\n const libNmNpmPath = path.join(thePath, 'lib', NODE_MODULES, NPM)\n // mise puts its npm bin in a path like:\n // /Users/SomeUsername/.local/share/mise/installs/node/vX.X.X/bin/npm.\n // HOWEVER, the location of the npm install is:\n // /Users/SomeUsername/.local/share/mise/installs/node/vX.X.X/lib/node_modules/npm.\n if (\n // Use existsSync here because statsSync, even with { throwIfNoEntry: false },\n // will throw an ENOTDIR error for paths like ./a-file-that-exists/a-directory-that-does-not.\n // See https://github.com/nodejs/node/issues/56993.\n existsSync(libNmNpmPath) &&\n statSync(libNmNpmPath, { throwIfNoEntry: false })?.isDirectory()\n ) {\n thePath = path.join(libNmNpmPath, NPM)\n }\n const nmPath = path.join(thePath, NODE_MODULES)\n if (\n // npm bin paths may look like:\n // /usr/local/share/npm/bin/npm\n // /Users/SomeUsername/.nvm/versions/node/vX.X.X/bin/npm\n // C:\\Users\\SomeUsername\\AppData\\Roaming\\npm\\bin\\npm.cmd\n // OR\n // C:\\Program Files\\nodejs\\npm.cmd\n //\n // In practically all cases the npm path contains a node_modules folder:\n // /usr/local/share/npm/bin/npm/node_modules\n // C:\\Program Files\\nodejs\\node_modules\n existsSync(nmPath) &&\n statSync(nmPath, { throwIfNoEntry: false })?.isDirectory() &&\n // Optimistically look for the default location.\n (path.basename(thePath) === NPM ||\n // Chocolatey installs npm bins in the same directory as node bins.\n (WIN32 && existsSync(path.join(thePath, `${NPM}.cmd`))))\n ) {\n return thePath\n }\n const parent = path.dirname(thePath)\n if (parent === thePath) {\n return undefined\n }\n thePath = parent\n }\n}\n\nexport async function getPackageFilesForScan(\n cwd: string,\n inputPaths: string[],\n supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data'],\n config?: SocketYml | undefined\n): Promise<string[]> {\n debugLog(\n `getPackageFilesForScan: resolving ${inputPaths.length} paths:\\n`,\n inputPaths\n )\n\n // Lazily access constants.spinner.\n const { spinner } = constants\n\n const patterns = pathsToGlobPatterns(inputPaths)\n\n spinner.start('Searching for local files to include in scan...')\n\n const entries = await globWithGitIgnore(patterns, {\n cwd,\n socketConfig: config\n })\n\n if (isDebug()) {\n spinner.stop()\n debugLog(\n `Resolved ${inputPaths.length} paths to ${entries.length} local paths:\\n`,\n entries\n )\n spinner.start('Searching for files now...')\n } else {\n spinner.start(\n `Resolved ${inputPaths.length} paths to ${entries.length} local paths, searching for files now...`\n )\n }\n\n const packageFiles = await filterGlobResultToSupportedFiles(\n entries,\n supportedFiles\n )\n\n spinner.successAndStop(\n `Found ${packageFiles.length} local ${pluralize('file', packageFiles.length)}`\n )\n debugLog('Absolute paths:\\n', packageFiles)\n\n return packageFiles\n}\n","import { existsSync } from 'node:fs'\nimport Module from 'node:module'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { logger } from '@socketsecurity/registry/lib/logger'\nimport { normalizePath } from '@socketsecurity/registry/lib/path'\n\nimport constants from '../../constants'\nimport {\n findBinPathDetailsSync,\n findNpmPathSync\n} from '../../utils/path-resolve'\n\nconst { NODE_MODULES, NPM, NPX, SOCKET_CLI_ISSUES_URL } = constants\n\nfunction exitWithBinPathError(binName: string): never {\n logger.fail(\n `Socket unable to locate ${binName}; ensure it is available in the PATH environment variable`\n )\n // The exit code 127 indicates that the command or binary being executed\n // could not be found.\n // eslint-disable-next-line n/no-process-exit\n process.exit(127)\n}\n\nlet _npmBinPathDetails: ReturnType<typeof findBinPathDetailsSync> | undefined\nfunction getNpmBinPathDetails(): ReturnType<typeof findBinPathDetailsSync> {\n if (_npmBinPathDetails === undefined) {\n _npmBinPathDetails = findBinPathDetailsSync(NPM)\n }\n return _npmBinPathDetails\n}\n\nlet _npxBinPathDetails: ReturnType<typeof findBinPathDetailsSync> | undefined\nfunction getNpxBinPathDetails(): ReturnType<typeof findBinPathDetailsSync> {\n if (_npxBinPathDetails === undefined) {\n _npxBinPathDetails = findBinPathDetailsSync(NPX)\n }\n return _npxBinPathDetails\n}\n\nlet _npmBinPath: string | undefined\nexport function getNpmBinPath(): string {\n if (_npmBinPath === undefined) {\n _npmBinPath = getNpmBinPathDetails().path\n if (!_npmBinPath) {\n exitWithBinPathError(NPM)\n }\n }\n return _npmBinPath\n}\n\nexport function isNpmBinPathShadowed() {\n return getNpmBinPathDetails().shadowed\n}\n\nlet _npxBinPath: string | undefined\nexport function getNpxBinPath(): string {\n if (_npxBinPath === undefined) {\n _npxBinPath = getNpxBinPathDetails().path\n if (!_npxBinPath) {\n exitWithBinPathError(NPX)\n }\n }\n return _npxBinPath\n}\n\nexport function isNpxBinPathShadowed() {\n return getNpxBinPathDetails().shadowed\n}\n\nlet _npmPath: string | undefined\nexport function getNpmPath() {\n if (_npmPath === undefined) {\n const npmBinPath = getNpmBinPath()\n _npmPath = npmBinPath ? findNpmPathSync(npmBinPath) : undefined\n if (!_npmPath) {\n let message = 'Unable to find npm CLI install directory.'\n if (npmBinPath) {\n message += `\\nSearched parent directories of ${path.dirname(npmBinPath)}.`\n }\n message += `\\n\\nThis is may be a bug with socket-npm related to changes to the npm CLI.\\nPlease report to ${SOCKET_CLI_ISSUES_URL}.`\n logger.fail(message)\n // The exit code 127 indicates that the command or binary being executed\n // could not be found.\n // eslint-disable-next-line n/no-process-exit\n process.exit(127)\n }\n }\n return _npmPath\n}\n\nlet _npmRequire: NodeJS.Require | undefined\nexport function getNpmRequire(): NodeJS.Require {\n if (_npmRequire === undefined) {\n const npmPath = getNpmPath()\n const npmNmPath = path.join(npmPath, NODE_MODULES, NPM)\n _npmRequire = Module.createRequire(\n path.join(existsSync(npmNmPath) ? npmNmPath : npmPath, '<dummy-basename>')\n )\n }\n return _npmRequire\n}\n\nlet _arboristPkgPath: string | undefined\nexport function getArboristPackagePath() {\n if (_arboristPkgPath === undefined) {\n const pkgName = '@npmcli/arborist'\n const mainPathWithForwardSlashes = normalizePath(\n getNpmRequire().resolve(pkgName)\n )\n const arboristPkgPathWithForwardSlashes = mainPathWithForwardSlashes.slice(\n 0,\n mainPathWithForwardSlashes.lastIndexOf(pkgName) + pkgName.length\n )\n // Lazily access constants.WIN32.\n _arboristPkgPath = constants.WIN32\n ? path.normalize(arboristPkgPathWithForwardSlashes)\n : arboristPkgPathWithForwardSlashes\n }\n return _arboristPkgPath\n}\n\nlet _arboristClassPath: string | undefined\nexport function getArboristClassPath() {\n if (_arboristClassPath === undefined) {\n _arboristClassPath = path.join(\n getArboristPackagePath(),\n 'lib/arborist/index.js'\n )\n }\n return _arboristClassPath\n}\n\nlet _arboristDepValidPath: string | undefined\nexport function getArboristDepValidPath() {\n if (_arboristDepValidPath === undefined) {\n _arboristDepValidPath = path.join(\n getArboristPackagePath(),\n 'lib/dep-valid.js'\n )\n }\n return _arboristDepValidPath\n}\n\nlet _arboristEdgeClassPath: string | undefined\nexport function getArboristEdgeClassPath() {\n if (_arboristEdgeClassPath === undefined) {\n _arboristEdgeClassPath = path.join(getArboristPackagePath(), 'lib/edge.js')\n }\n return _arboristEdgeClassPath\n}\n\nlet _arboristNodeClassPath: string | undefined\nexport function getArboristNodeClassPath() {\n if (_arboristNodeClassPath === undefined) {\n _arboristNodeClassPath = path.join(getArboristPackagePath(), 'lib/node.js')\n }\n return _arboristNodeClassPath\n}\n\nlet _arboristOverrideSetClassPath: string | undefined\nexport function getArboristOverrideSetClassPath() {\n if (_arboristOverrideSetClassPath === undefined) {\n _arboristOverrideSetClassPath = path.join(\n getArboristPackagePath(),\n 'lib/override-set.js'\n )\n }\n return _arboristOverrideSetClassPath\n}\n"],"names":["shadowBinPath","all","nothrow","length","shadowIndex","theBinPath","name","path","WIN32","existsSync","throwIfNoEntry","thePath","spinner","socketConfig","debugLog","SOCKET_CLI_ISSUES_URL","logger","process","_npmBinPathDetails","_npxBinPathDetails","_npmBinPath","_npxBinPath","_arboristPkgPath"],"mappings":";;;;;;;;;;;;;;;AAmBA;;;AAA2BA;AAAc;AAElC;AAKL;AAEIC;AACAC;;;AAGJ;AACA;AAAkBC;;AAChB;AACA;;AAEEC;AACF;AACEC;AACA;AACF;AACF;;AACSC;AAAeC;;;AAC1B;AAEO;AACL;;AACQC;AAAM;;AAEd;AACE;AACA;AACA;AACA;AACA;AACA;AACE;AACA;AACA;AACAC;AACyBC;AAAsB;;AAGjD;;AAEA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAD;AACmBC;AAAsB;AACzC;AACCH;AACC;AACCC;AAEH;AACF;AACA;;AAEE;AACF;AACAG;AACF;AACF;AAEO;;;AAWL;;AACQC;AAAQ;AAEhB;AAEAA;AAEA;;AAEEC;AACF;;;AAIEC;AAIAF;AACF;AACEA;AAGF;;AAOAA;AAGAE;AAEA;AACF;;AC/HA;;;;AAAgCC;AAAsB;AAEtD;AACEC;AAGA;AACA;AACA;AACAC;AACF;AAEA;AACA;;AAEIC;AACF;AACA;AACF;AAEA;AACA;;AAEIC;AACF;AACA;AACF;AAEA;AACO;;AAEHC;;;AAGA;AACF;AACA;AACF;AAEO;AACL;AACF;AAEA;AACO;;AAEHC;;;AAGA;AACF;AACA;AACF;AAEO;AACL;AACF;AAEA;AACO;;AAEH;;;;AAIE;;AAEA;;AAEAL;AACA;AACA;AACA;AACAC;AACF;AACF;AACA;AACF;AAEA;AACO;;AAEH;;;AAKF;AACA;AACF;AAEA;AACO;;;AAGH;AAGA;AAIA;AACAK;AAGF;AACA;AACF;AAEA;AACO;;;AAML;AACA;AACF;AAEA;AACO;;;AAML;AACA;AACF;AAEA;AACO;;;AAGL;AACA;AACF;AAEA;AACO;;;AAGL;AACA;AACF;AAEA;AACO;;;AAML;AACA;AACF;;;;;;;;;;;;","debugId":"75cc424a-e3b3-459b-ab4f-2559d82d5382"}