diff --git a/.config/vitest.config.mts b/.config/vitest.config.mts index 106bcea95..e0d25d26e 100644 --- a/.config/vitest.config.mts +++ b/.config/vitest.config.mts @@ -45,6 +45,8 @@ export default { 'upstream/**', ], coverage: { + reporter: ['text', 'json', 'json-summary'], + reportOnFailure: true, exclude: [ '**/{eslint,vitest}.config.*', '**/node_modules/**', diff --git a/README.md b/README.md index 42e827b2a..19f768d31 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # Socket CLI [![Socket Badge](https://socket.dev/api/badge/npm/package/socket)](https://socket.dev/npm/package/socket) + +[![Coverage](https://img.shields.io/badge/coverage-66%25-red)](https://github.com/SocketDev/socket-cli/actions) + [![Follow @SocketSecurity](assets/fleet/badge-follow-x.svg)](https://twitter.com/SocketSecurity) [![Follow @socket.dev on Bluesky](assets/fleet/badge-follow-bluesky.svg)](https://bsky.app/profile/socket.dev) diff --git a/package.json b/package.json index 020b0d4d6..9c249e8b7 100644 --- a/package.json +++ b/package.json @@ -62,8 +62,9 @@ "clean:dist:types": "del-cli 'dist/types'", "clean:external": "del-cli 'external'", "clean:node_modules": "del-cli '**/node_modules'", - "coverage": "run-s coverage:*", - "coverage:test": "run-s test:prepare test:unit:coverage", + "coverage": "pnpm run coverage:test && pnpm run coverage:type", + "coverage:badge": "node scripts/coverage-badge.mts", + "coverage:test": "run-s test:prepare test:unit:coverage coverage:badge", "coverage:type": "dotenvx -q run -f .env.local -- type-coverage --detail", "fix": "node scripts/lint.mts --fix", "knip:dependencies": "knip --dependencies", diff --git a/scripts/coverage-badge.mts b/scripts/coverage-badge.mts new file mode 100644 index 000000000..775fb83a8 --- /dev/null +++ b/scripts/coverage-badge.mts @@ -0,0 +1,68 @@ +import { readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { isMainModule } from './lib/is-main-module.mts' + +type CoverageSummary = { + total?: { + lines?: { + pct?: number + } + } +} + +const BADGE_MARKER = '' +const BADGE_END_MARKER = '' + +export function formatCoverageBadge(percentage: number): string { + if (!Number.isFinite(percentage) || percentage < 0 || percentage > 100) { + throw new RangeError(`Coverage percentage must be between 0 and 100`) + } + + const rounded = Math.round(percentage) + const color = rounded >= 90 ? 'brightgreen' : rounded >= 80 ? 'yellow' : 'red' + return `[![Coverage](https://img.shields.io/badge/coverage-${rounded}%25-${color})](https://github.com/SocketDev/socket-cli/actions)` +} + +export async function updateCoverageBadge({ + readmePath, + summaryPath, +}: { + readmePath: string + summaryPath: string +}): Promise { + const summary = JSON.parse( + await readFile(summaryPath, 'utf8'), + ) as CoverageSummary + const percentage = summary.total?.lines?.pct + if (typeof percentage !== 'number' || !Number.isFinite(percentage)) { + throw new Error(`Coverage summary is missing total line coverage`) + } + + const readme = await readFile(readmePath, 'utf8') + const start = readme.indexOf(BADGE_MARKER) + const end = readme.indexOf(BADGE_END_MARKER) + if (start === -1 || end < start) { + throw new Error(`README is missing the coverage badge markers`) + } + + const badgeStart = start + BADGE_MARKER.length + const updated = `${readme.slice(0, badgeStart)}\n${formatCoverageBadge(percentage)}\n${readme.slice(end)}` + await writeFile(readmePath, updated) +} + +const repositoryRoot = path.dirname( + path.dirname(fileURLToPath(import.meta.url)), +) + +export function isCoverageBadgeEntrypoint(entryPath?: string): boolean { + return isMainModule(import.meta.url, entryPath) +} + +if (isCoverageBadgeEntrypoint()) { + await updateCoverageBadge({ + readmePath: path.join(repositoryRoot, 'README.md'), + summaryPath: path.join(repositoryRoot, 'coverage', 'coverage-summary.json'), + }) +} diff --git a/src/commands/manifest/convert-conda-to-requirements.test.mts b/src/commands/manifest/convert-conda-to-requirements.test.mts index d5faa1924..136a50d78 100644 --- a/src/commands/manifest/convert-conda-to-requirements.test.mts +++ b/src/commands/manifest/convert-conda-to-requirements.test.mts @@ -225,3 +225,73 @@ dependencies: # List of packages to install `) }) }) + +describe('Conda requirements input sources', () => { + it('reports a missing manifest path with its resolved location', async () => { + const { join } = await import('node:path') + const { convertCondaToRequirements } = await import( + './convert-conda-to-requirements.mts' + ) + const projectPath = '/missing/project' + + await expect( + convertCondaToRequirements('environment.yml', projectPath, false), + ).resolves.toEqual({ + ok: false, + message: 'Manifest Generation Failed', + cause: `The file was not found at ${join(projectPath, 'environment.yml')}`, + }) + }) + + it('reports an empty Conda manifest file', async () => { + const { mkdtemp, rm, writeFile } = await import('node:fs/promises') + const { tmpdir } = await import('node:os') + const { join } = await import('node:path') + const { convertCondaToRequirements } = await import( + './convert-conda-to-requirements.mts' + ) + const directory = await mkdtemp(join(tmpdir(), 'socket-conda-empty-')) + + try { + await writeFile(join(directory, 'environment.yml'), '') + await expect( + convertCondaToRequirements('environment.yml', directory, false), + ).resolves.toMatchObject({ + ok: false, + message: 'Manifest Generation Failed', + cause: `File at ${join(directory, 'environment.yml')} is empty`, + }) + } finally { + await rm(directory, { force: true, recursive: true }) + } + }) + + it('normalizes terminal styling and surrounding whitespace from a manifest file', async () => { + const { mkdtemp, rm, writeFile } = await import('node:fs/promises') + const { tmpdir } = await import('node:os') + const { join } = await import('node:path') + const { convertCondaToRequirements } = await import( + './convert-conda-to-requirements.mts' + ) + const directory = await mkdtemp(join(tmpdir(), 'socket-conda-ansi-')) + + try { + await writeFile( + join(directory, 'environment.yml'), + '\u001b[32m dependencies:\n - pip:\n - requests==2.32.0 \u001b[0m\n', + ) + await expect( + convertCondaToRequirements('environment.yml', directory, false), + ).resolves.toEqual({ + ok: true, + data: { + content: + '\u001b[32m dependencies:\n - pip:\n - requests==2.32.0 \u001b[0m\n', + pip: 'requests==2.32.0 ', + }, + }) + } finally { + await rm(directory, { force: true, recursive: true }) + } + }) +}) diff --git a/src/commands/manifest/convert_gradle_to_maven.test.mts b/src/commands/manifest/convert_gradle_to_maven.test.mts new file mode 100644 index 000000000..a7c0ab909 --- /dev/null +++ b/src/commands/manifest/convert_gradle_to_maven.test.mts @@ -0,0 +1,116 @@ +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { loggerFail, loggerLog, loggerWarn, resolveBuildToolBin, spawn } = + vi.hoisted(() => ({ + loggerFail: vi.fn(), + loggerLog: vi.fn(), + loggerWarn: vi.fn(), + resolveBuildToolBin: vi.fn( + (_tool: string, _cwd: string, bin: string) => bin, + ), + spawn: vi.fn(), + })) + +vi.mock('./scripts/build-tool.mts', () => ({ resolveBuildToolBin })) +vi.mock('../../sea/runtime.mts', () => ({ isSea: () => false })) +vi.mock('../../utils/spawn.mts', () => ({ spawn })) +vi.mock('../../utils/logger.mts', () => ({ + logger: { + error: vi.fn(), + fail: loggerFail, + group: vi.fn(), + groupEnd: vi.fn(), + info: vi.fn(), + log: loggerLog, + success: vi.fn(), + warn: loggerWarn, + }, +})) + +import { convertGradleToMaven } from './convert_gradle_to_maven.mts' + +describe('Gradle POM conversion', () => { + let cwd: string + + beforeEach(async () => { + cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'socket-gradle-pom-')) + await fs.writeFile(path.join(cwd, 'gradlew'), '') + resolveBuildToolBin.mockClear() + spawn.mockReset() + loggerFail.mockClear() + loggerLog.mockClear() + loggerWarn.mockClear() + process.exitCode = 0 + }) + + afterEach(async () => { + process.exitCode = 0 + await fs.rm(cwd, { recursive: true, force: true }) + }) + + it('passes exclusions to Gradle and reports each generated POM', async () => { + spawn.mockResolvedValue({ + code: 0, + stdout: 'POM file copied to: service/pom.xml\n', + stderr: '', + }) + + await convertGradleToMaven({ + bin: './gradlew', + cwd, + excludePaths: [':docs', ':examples'], + gradleOpts: ['--offline'], + verbose: false, + }) + + expect(spawn).toHaveBeenCalledWith( + path.join(cwd, 'gradlew'), + expect.arrayContaining([ + '-Psocket.excludePaths=:docs,:examples', + '--offline', + 'pom', + ]), + { cwd }, + ) + expect(loggerLog).toHaveBeenCalledWith('- ', 'service/pom.xml') + }) + + it('streams Gradle output directly when verbose mode is enabled', async () => { + spawn.mockResolvedValue({ code: 0, stdout: '', stderr: '' }) + + await convertGradleToMaven({ + bin: './gradlew', + cwd, + gradleOpts: [], + verbose: true, + }) + + expect(spawn).toHaveBeenCalledWith( + path.join(cwd, 'gradlew'), + expect.any(Array), + { cwd, stdio: 'inherit' }, + ) + }) + + it('surfaces a failed Gradle exit and sets a nonzero process status', async () => { + spawn.mockResolvedValue({ + code: 17, + stdout: '', + stderr: 'configuration error', + }) + + await convertGradleToMaven({ + bin: './gradlew', + cwd, + gradleOpts: [], + verbose: false, + }) + + expect(process.exitCode).toBe(1) + expect(loggerFail).toHaveBeenCalledWith('Gradle exited with exit code 17') + }) +}) diff --git a/src/commands/manifest/convert_sbt_to_maven.test.mts b/src/commands/manifest/convert_sbt_to_maven.test.mts new file mode 100644 index 000000000..747cd047a --- /dev/null +++ b/src/commands/manifest/convert_sbt_to_maven.test.mts @@ -0,0 +1,155 @@ +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { log, loggerFail, loggerSuccess, resolveBuildToolBin, spawn } = + vi.hoisted(() => ({ + log: vi.fn(), + loggerFail: vi.fn(), + loggerSuccess: vi.fn(), + resolveBuildToolBin: vi.fn( + (_tool: string, _cwd: string, bin: string) => bin, + ), + spawn: vi.fn(), + })) + +vi.mock('./scripts/build-tool.mts', () => ({ resolveBuildToolBin })) +vi.mock('../../sea/runtime.mts', () => ({ isSea: () => false })) +vi.mock('../../utils/spawn.mts', () => ({ spawn })) +vi.mock('../../utils/logger.mts', () => ({ + logger: { + error: vi.fn(), + fail: loggerFail, + group: vi.fn(), + groupEnd: vi.fn(), + info: vi.fn(), + log, + success: loggerSuccess, + warn: vi.fn(), + }, +})) + +import { convertSbtToMaven } from './convert_sbt_to_maven.mts' + +describe('sbt POM conversion', () => { + let cwd: string + + beforeEach(async () => { + cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'socket-sbt-pom-')) + resolveBuildToolBin.mockClear() + spawn.mockReset() + log.mockClear() + loggerFail.mockClear() + loggerSuccess.mockClear() + process.exitCode = 0 + }) + + afterEach(async () => { + process.exitCode = 0 + await fs.rm(cwd, { recursive: true, force: true }) + }) + + it('copies one generated POM out of target into the requested project file', async () => { + const targetPom = path.join(cwd, 'module', 'target', 'generated.pom') + await fs.mkdir(path.dirname(targetPom), { recursive: true }) + await fs.writeFile(targetPom, '') + spawn.mockResolvedValue({ + stdout: `Wrote ${targetPom}\n`, + stderr: '', + }) + + await convertSbtToMaven({ + bin: './sbt', + cwd, + out: 'module/pom.xml', + sbtOpts: ['-Dsbt.supershell=false'], + verbose: false, + }) + + expect(await fs.readFile(path.join(cwd, 'module', 'pom.xml'), 'utf8')).toBe( + '', + ) + expect(spawn).toHaveBeenCalledWith( + './sbt', + ['makePom', '-Dsbt.supershell=false'], + { cwd }, + ) + expect(loggerSuccess).toHaveBeenCalledWith('Generated 1 pom file') + }) + + it('prints a generated POM when stdout is requested for one project', async () => { + const targetPom = path.join(cwd, 'target', 'generated.pom') + await fs.mkdir(path.dirname(targetPom), { recursive: true }) + await fs.writeFile(targetPom, '') + spawn.mockResolvedValue({ stdout: `Wrote ${targetPom}\n`, stderr: '' }) + + await convertSbtToMaven({ + bin: 'sbt', + cwd, + out: '-', + sbtOpts: [], + verbose: false, + }) + + expect(log).toHaveBeenCalledWith('') + expect(loggerSuccess).toHaveBeenCalledWith('OK') + }) + + it('rejects stdout when sbt generates multiple project POMs', async () => { + const firstPom = path.join(cwd, 'first', 'target', 'first.pom') + const secondPom = path.join(cwd, 'second', 'target', 'second.pom') + spawn.mockResolvedValue({ + stdout: `Wrote ${firstPom}\nWrote ${secondPom}\n`, + stderr: '', + }) + + await convertSbtToMaven({ + bin: 'sbt', + cwd, + out: '-', + sbtOpts: [], + verbose: false, + }) + + expect(process.exitCode).toBe(1) + expect(loggerFail).toHaveBeenCalledWith( + 'Requested output target was stdout but there are multiple generated files', + ) + }) + + it('sets a failing exit code when sbt reports errors on stderr', async () => { + spawn.mockResolvedValue({ stdout: '', stderr: 'build failed' }) + + await convertSbtToMaven({ + bin: 'sbt', + cwd, + out: 'pom.xml', + sbtOpts: [], + verbose: false, + }) + + expect(process.exitCode).toBe(1) + expect(loggerFail).toHaveBeenCalledWith( + 'There were errors while running sbt', + ) + }) + + it('reports when sbt exits successfully without generating a POM', async () => { + spawn.mockResolvedValue({ stdout: '', stderr: '' }) + + await convertSbtToMaven({ + bin: 'sbt', + cwd, + out: 'pom.xml', + sbtOpts: [], + verbose: false, + }) + + expect(process.exitCode).toBe(1) + expect(loggerFail).toHaveBeenCalledWith( + 'There were no errors from sbt but it seems to not have generated any poms either', + ) + }) +}) diff --git a/src/commands/manifest/output-requirements.test.mts b/src/commands/manifest/output-requirements.test.mts new file mode 100644 index 000000000..546230552 --- /dev/null +++ b/src/commands/manifest/output-requirements.test.mts @@ -0,0 +1,66 @@ +import fs, { promises as fsp } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { outputRequirements } from './output-requirements.mts' +import { logger } from '../../utils/logger.mts' + +describe('converted Conda requirements output', () => { + let temporaryDirectory: string | undefined + + afterEach(async () => { + vi.restoreAllMocks() + process.exitCode = 0 + if (temporaryDirectory) { + await fsp.rm(temporaryDirectory, { recursive: true, force: true }) + temporaryDirectory = undefined + } + }) + + it('writes pip requirements to the requested file in text mode', async () => { + temporaryDirectory = await fsp.mkdtemp( + path.join(os.tmpdir(), 'socket-requirements-'), + ) + const outputPath = path.join(temporaryDirectory, 'requirements.txt') + + await outputRequirements( + { ok: true, data: { content: 'ignored', pip: 'requests==2.32.0\n' } }, + 'text', + outputPath, + ) + + expect(fs.readFileSync(outputPath, 'utf8')).toBe('requests==2.32.0\n') + }) + + it('prints Markdown to stdout when the output target is a dash', async () => { + const log = vi.spyOn(logger, 'log').mockImplementation(() => undefined) + + await outputRequirements( + { ok: true, data: { content: '', pip: 'requests==2.32.0' } }, + 'markdown', + '-', + ) + + expect(log.mock.calls.map(([value]) => value).join('\n')).toContain( + '```file=requirements.txt\nrequests==2.32.0', + ) + }) + + it('returns JSON errors on stdout and uses the API exit code', async () => { + const log = vi.spyOn(logger, 'log').mockImplementation(() => undefined) + + await outputRequirements( + { ok: false, code: 7, message: 'conversion failed' }, + 'json', + '-', + ) + + expect(process.exitCode).toBe(7) + expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({ + ok: false, + message: 'conversion failed', + }) + }) +}) diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 7143cbac7..9b3967c31 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -1,3 +1,7 @@ +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + import { afterEach, describe, expect, it, vi } from 'vitest' // Simulates a real prompt: pressing Enter with nothing typed returns @@ -12,6 +16,7 @@ vi.mock('../../utils/prompts.mts', () => ({ import { setupDotnet, setupGradle, + setupManifestConfig, setupMaven, setupReachability, setupSbt, @@ -37,6 +42,44 @@ afterEach(() => { vi.mocked(select).mockClear() }) +describe('manifest setup selection', () => { + it('leaves the project unchanged when the user exits before choosing a generator', async () => { + const cwd = await fs.mkdtemp( + path.join(os.tmpdir(), 'socket-manifest-exit-'), + ) + try { + expect(await setupManifestConfig(cwd)).toEqual({ + ok: true, + data: { canceled: true }, + }) + await expect(fs.readdir(cwd)).resolves.toEqual([]) + } finally { + await fs.rm(cwd, { recursive: true, force: true }) + } + }) + + it('writes Maven defaults after the user selects Maven and confirms saving', async () => { + const cwd = await fs.mkdtemp( + path.join(os.tmpdir(), 'socket-manifest-maven-'), + ) + try { + vi.mocked(select) + .mockResolvedValueOnce('maven') + .mockResolvedValueOnce('') + .mockResolvedValueOnce('') + .mockResolvedValueOnce(true) + + expect(await setupManifestConfig(cwd)).toMatchObject({ ok: true }) + const savedConfig = JSON.parse( + await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), + ) as { defaults?: { manifest?: { maven?: { bin?: string } } } } + expect(savedConfig.defaults?.manifest?.maven).toBeDefined() + } finally { + await fs.rm(cwd, { recursive: true, force: true }) + } + }) +}) + describe('setup wizards', () => { it.for([ ['dotnet', setupDotnet], diff --git a/src/commands/scan/create-scan-from-github.test.mts b/src/commands/scan/create-scan-from-github.test.mts index 817c7468e..cfe8d0b22 100644 --- a/src/commands/scan/create-scan-from-github.test.mts +++ b/src/commands/scan/create-scan-from-github.test.mts @@ -1,6 +1,37 @@ -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' -import { runGithubScanLoop } from './create-scan-from-github.mts' +const mockFetchListAllRepos = vi.hoisted(() => vi.fn()) +const mockConfirm = vi.hoisted(() => vi.fn()) +const mockSelect = vi.hoisted(() => vi.fn()) +const mockGithubApiRequest = vi.hoisted(() => vi.fn()) +const mockLogger = vi.hoisted(() => ({ + fail: vi.fn(), + group: vi.fn(), + groupEnd: vi.fn(), + info: vi.fn(), + log: vi.fn(), + success: vi.fn(), + warn: vi.fn(), +})) + +vi.mock('../repository/fetch-list-all-repos.mts', () => ({ + fetchListAllRepos: mockFetchListAllRepos, +})) +vi.mock('../../utils/prompts.mts', () => ({ + confirm: mockConfirm, + select: mockSelect, +})) +vi.mock('../../utils/github-errors.mts', async importOriginal => { + const actual = + await importOriginal() + return { ...actual, githubApiRequest: mockGithubApiRequest } +}) +vi.mock('../../utils/logger.mts', () => ({ logger: mockLogger })) + +import { + createScanFromGithub, + runGithubScanLoop, +} from './create-scan-from-github.mts' import { GITHUB_ERR_AUTH_FAILED, GITHUB_ERR_RATE_LIMIT, @@ -101,3 +132,120 @@ describe('runGithubScanLoop GitHub blocking-error handling', () => { expect(result.ok ? '' : result.message).toBe('All repos failed to scan') }) }) + +const baseGithubScanOptions = { + all: true, + githubApiUrl: 'https://api.github.test', + githubToken: 'github-token', + interactive: false, + orgGithub: 'socketdev', + orgSlug: 'socket-org', + outputKind: 'json' as const, + repos: '', +} + +describe('GitHub repository scan selection', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('returns the repository listing error before starting scans', async () => { + mockFetchListAllRepos.mockResolvedValue({ + ok: false, + message: 'repository listing unavailable', + cause: 'Socket API request failed', + }) + + await expect(createScanFromGithub(baseGithubScanOptions)).resolves.toEqual({ + ok: false, + message: 'repository listing unavailable', + cause: 'Socket API request failed', + }) + expect(mockGithubApiRequest).not.toHaveBeenCalled() + }) + + it('explains that no repositories were found when the API returns an empty list', async () => { + mockFetchListAllRepos.mockResolvedValue({ + ok: true, + data: { results: [] }, + }) + + await expect( + createScanFromGithub(baseGithubScanOptions), + ).resolves.toMatchObject({ + ok: false, + message: 'No repo found', + cause: expect.stringContaining('zero repos'), + }) + }) + + it('stops when the user cancels confirmation for a large all-repository scan', async () => { + mockFetchListAllRepos.mockResolvedValue({ + ok: true, + data: { + results: Array.from({ length: 11 }, (_, index) => ({ + slug: `repo-${index}`, + })), + }, + }) + mockConfirm.mockResolvedValue(false) + + await expect( + createScanFromGithub({ ...baseGithubScanOptions, interactive: true }), + ).resolves.toEqual({ + ok: false, + message: 'User canceled', + cause: 'Action canceled by user', + }) + expect(mockConfirm).toHaveBeenCalledWith({ + message: 'Are you sure you want to run this for 11 repos?', + default: false, + }) + expect(mockGithubApiRequest).not.toHaveBeenCalled() + }) + + it('continues after a user selects one repository from an interactive list', async () => { + mockFetchListAllRepos.mockResolvedValue({ + ok: true, + data: { results: [{ slug: 'repo-a' }, { slug: 'repo-b' }] }, + }) + mockSelect.mockResolvedValue('repo-b') + mockGithubApiRequest.mockResolvedValue({ + ok: false, + message: 'repository details unavailable', + }) + + await expect( + createScanFromGithub({ + ...baseGithubScanOptions, + all: false, + interactive: true, + }), + ).resolves.toMatchObject({ + ok: false, + message: 'All repos failed to scan', + cause: expect.stringContaining('repo-b'), + }) + expect(mockSelect).toHaveBeenCalledWith({ + message: 'Please select the repo to process:', + choices: [ + { + name: 'repo-a', + value: 'repo-a', + description: 'Create scan for the repo-a repo through GitHub', + }, + { + name: 'repo-b', + value: 'repo-b', + description: 'Create scan for the repo-b repo through GitHub', + }, + { + name: '(Exit)', + value: '', + description: 'Cancel this action and exit', + }, + ], + }) + expect(mockGithubApiRequest).toHaveBeenCalledOnce() + }) +}) diff --git a/src/commands/scan/output-diff-scan.test.mts b/src/commands/scan/output-diff-scan.test.mts index 3b053cdab..bbfa3b7b0 100644 --- a/src/commands/scan/output-diff-scan.test.mts +++ b/src/commands/scan/output-diff-scan.test.mts @@ -1,7 +1,12 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' + import { afterEach, describe, expect, it, vi } from 'vitest' import { handlePrDiffScan } from './handle-diff-scan.mts' import { outputDiffScan } from './output-diff-scan.mts' +import { logger } from '../../utils/logger.mts' const fetchDiffScan = vi.hoisted(() => vi.fn()) @@ -11,12 +16,22 @@ vi.mock('../../utils/logger.mts', () => ({ logger: { error: vi.fn(), fail: vi.fn(), + group: vi.fn(), + groupEnd: vi.fn(), info: vi.fn(), log: vi.fn(), success: vi.fn(), }, })) +function createManyArtifacts() { + return Array.from({ length: 12 }, (_, i) => ({ + type: 'npm', + name: `package-${i}`, + version: '1.0.0', + })) +} + const diff = { diff_scan: { after_full_scan: { id: 'after' }, @@ -122,3 +137,182 @@ describe('outputDiffScan strict blocking', () => { expect(process.exitCode).toBe(0) }) }) + +describe('diff scan report formats', () => { + let temporaryDirectory: string | undefined + + afterEach(async () => { + process.exitCode = 0 + vi.clearAllMocks() + if (temporaryDirectory) { + await rm(temporaryDirectory, { force: true, recursive: true }) + temporaryDirectory = undefined + } + }) + + it('prints API failures as JSON while preserving the server exit code', async () => { + await outputDiffScan( + { ok: false, code: 7, message: 'scan diff unavailable' }, + { depth: 0, file: '', outputKind: 'json', strictBlocking: false }, + ) + + expect(logger.log).toHaveBeenCalledWith( + expect.stringContaining('scan diff unavailable'), + ) + expect(process.exitCode).toBe(7) + }) + + it('prints API failures with the Socket badge in text mode', async () => { + await outputDiffScan( + { ok: false, message: 'scan diff unavailable', cause: 'try again' }, + { depth: 0, file: '', outputKind: 'text', strictBlocking: false }, + ) + + expect(logger.fail).toHaveBeenCalledWith( + expect.stringContaining('scan diff unavailable'), + ) + }) + + it('renders changed packages and scan metadata in Markdown mode', async () => { + const markdownDiff = structuredClone(diff) + markdownDiff.diff_scan.html_url = 'https://socket.dev/diff/123' + markdownDiff.diff_scan.before_full_scan = { + id: 'before', + repository_slug: 'example/repo', + organization_slug: 'example', + pull_request: 0, + organization_id: 'org-id', + repository_id: 'repo-id', + } + markdownDiff.diff_scan.after_full_scan = { + id: 'after', + repository_slug: 'example/repo', + organization_slug: 'example', + pull_request: 42, + organization_id: 'org-id', + repository_id: 'repo-id', + } + markdownDiff.diff_scan.artifacts.added = [ + { + type: 'npm', + name: 'new-package', + version: '1.2.3', + }, + ] + markdownDiff.diff_scan.artifacts.removed = [ + { + type: 'npm', + name: 'old-package', + version: '1.0.0', + }, + ] + markdownDiff.diff_scan.artifacts.replaced = [ + { + type: 'npm', + name: 'replaced-package', + version: '3.0.0', + }, + ] + markdownDiff.diff_scan.artifacts.updated = [ + { + type: 'npm', + name: 'updated-package', + version: '2.0.0', + }, + ] + + await outputDiffScan({ ok: true, data: markdownDiff } as never, { + depth: 0, + file: '', + outputKind: 'markdown', + strictBlocking: false, + }) + + const rendered = vi.mocked(logger.log).mock.calls.flat().join('\n') + expect(rendered).toContain('- npm new-package@1.2.3') + expect(rendered).toContain('- npm old-package@1.0.0') + expect(rendered).toContain('- npm replaced-package@3.0.0') + expect(rendered).toContain('- npm updated-package@2.0.0') + expect(logger.group).toHaveBeenCalledWith('- repo: example/repo') + expect(logger.group).toHaveBeenCalledWith('- org: example') + expect(rendered).toContain('https://socket.dev/diff/123') + }) + + it('limits each Markdown package category to ten entries and reports the remainder', async () => { + const manyAdded = structuredClone(diff) + manyAdded.diff_scan.artifacts.added = createManyArtifacts() + manyAdded.diff_scan.artifacts.removed = createManyArtifacts() + manyAdded.diff_scan.artifacts.replaced = createManyArtifacts() + manyAdded.diff_scan.artifacts.updated = createManyArtifacts() + manyAdded.diff_scan.artifacts.unchanged = createManyArtifacts() + manyAdded.diff_scan.after_full_scan = { id: 'after', pull_request: 0 } + + await outputDiffScan({ ok: true, data: manyAdded } as never, { + depth: 0, + file: '', + outputKind: 'markdown', + strictBlocking: false, + }) + + const rendered = vi.mocked(logger.log).mock.calls.flat().join('\n') + expect(rendered).toContain('- npm package-9@1.0.0') + expect(rendered).not.toContain('- npm package-10@1.0.0') + expect(rendered.match(/\.\.\. and 2 more/gu)).toHaveLength(5) + expect(logger.group).not.toHaveBeenCalledWith('- pull_request: 0') + }) + + it('writes complete JSON reports to a file and reports successful completion', async () => { + temporaryDirectory = await mkdtemp( + path.join(os.tmpdir(), 'socket-diff-output-'), + ) + const filepath = path.join(temporaryDirectory, 'diff.json') + + await outputDiffScan({ ok: true, data: diff } as never, { + depth: 0, + file: filepath, + outputKind: 'json', + strictBlocking: false, + }) + await vi.waitFor(() => expect(logger.success).toHaveBeenCalledOnce()) + + const result = JSON.parse(await readFile(filepath, 'utf8')) + expect(result.data.diff_scan.before_full_scan.id).toBe('before') + expect(logger.log).toHaveBeenCalledWith(`Writing json to \`${filepath}\``) + }) + + it('reports file write errors instead of claiming the report was saved', async () => { + temporaryDirectory = await mkdtemp( + path.join(os.tmpdir(), 'socket-diff-output-error-'), + ) + const filepath = path.join(temporaryDirectory, 'missing', 'diff.json') + + await outputDiffScan({ ok: true, data: diff } as never, { + depth: 0, + file: filepath, + outputKind: 'json', + strictBlocking: false, + }) + await vi.waitFor(() => + expect(logger.fail).toHaveBeenCalledWith( + `Writing to \`${filepath}\` failed...`, + ), + ) + + expect(logger.success).not.toHaveBeenCalled() + expect(logger.error).toHaveBeenCalledWith(expect.any(Error)) + }) + + it('prints inspected results with the requested depth in terminal mode', async () => { + await outputDiffScan({ ok: true, data: diff } as never, { + depth: 2, + file: '', + outputKind: 'text', + strictBlocking: false, + }) + + expect(logger.log).toHaveBeenCalledWith('Diff scan result:') + expect(logger.info).toHaveBeenCalledWith( + expect.stringContaining('use the --json flag'), + ) + }) +}) diff --git a/src/utils/api.test.mts b/src/utils/api.test.mts index c4e7335bc..2d6d0060f 100644 --- a/src/utils/api.test.mts +++ b/src/utils/api.test.mts @@ -24,9 +24,10 @@ * - utils/sdk.mts (getExtraCaCerts, getDefaultProxyUrl) */ -import type { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EventEmitter } from 'node:events' + // Mock getExtraCaCerts from sdk.mts. const mockGetExtraCaCerts = vi.hoisted(() => vi.fn(() => undefined)) const mockGetDefaultApiToken = vi.hoisted(() => vi.fn(() => 'test-api-token')) @@ -119,6 +120,8 @@ vi.mock('./config.mts', () => ({ vi.mock('./errors.mts', () => ({ errorMessage: (error: unknown) => error instanceof Error ? error.message : 'Unknown error', + isErrnoException: (error: unknown) => + Boolean(error && typeof error === 'object' && 'code' in error), })) // Mock debug functions. @@ -178,7 +181,17 @@ describe('OAuth API error guidance', () => { }) }) -function stubHttpsResponse() { +function stubHttpsResponse({ + body = 'response body', + headers = { 'content-type': 'text/plain' }, + statusCode = 200, + statusMessage = 'OK', +}: { + body?: string + headers?: Record + statusCode?: number + statusMessage?: string +} = {}) { const mockReq = { end: vi.fn(), on: vi.fn(), @@ -188,10 +201,10 @@ function stubHttpsResponse() { (_url: string, _opts: unknown, callback: RequestCallback) => { setTimeout(() => { const mockRes = { - headers: { 'content-type': 'text/plain' }, + headers, on: vi.fn(), - statusCode: 200, - statusMessage: 'OK', + statusCode, + statusMessage, } const handlers: Record = {} mockRes.on.mockImplementation((event: string, handler: Function) => { @@ -199,7 +212,7 @@ function stubHttpsResponse() { return mockRes }) callback(mockRes) - handlers['data']?.(Buffer.from('response body')) + handlers['data']?.(Buffer.from(body)) handlers['end']?.() }, 0) return mockReq @@ -783,3 +796,241 @@ describe('apiFetch proxy support', () => { expect(MockHttpsAgent).toHaveBeenCalledTimes(1) }) }) + +describe('Socket API query and write results', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.resetModules() + mockGetConfigValueOrUndef.mockReturnValue(undefined) + mockIsConfigFromFlag.mockReturnValue(false) + mockGetExtraCaCerts.mockReturnValue(undefined) + mockGetDefaultProxyUrl.mockReturnValue(undefined) + mockResolveDefaultApiToken.mockResolvedValue('test-api-token') + }) + + it('retains an accepted HTTP status for callers that poll asynchronous results', async () => { + stubHttpsResponse({ + body: 'scan pending', + statusCode: 202, + statusMessage: 'Accepted', + }) + const { queryApiSafeTextWithStatus } = await import('./api.mts') + + const result = await queryApiSafeTextWithStatus('scan/status') + + expect(result).toEqual({ + ok: true, + data: { status: 202, text: 'scan pending' }, + }) + }) + + it('returns an authentication error when token resolution fails', async () => { + mockResolveDefaultApiToken.mockRejectedValue(new Error('token expired')) + const { queryApiSafeTextWithStatus } = await import('./api.mts') + + await expect(queryApiSafeTextWithStatus('scan/status')).resolves.toEqual({ + ok: false, + message: 'Authentication Error', + cause: 'token expired', + }) + expect(mockHttpsRequest).not.toHaveBeenCalled() + }) + + it('returns a user-facing failure when authentication resolves without a token', async () => { + mockResolveDefaultApiToken.mockResolvedValue(undefined) + const { queryApiSafeTextWithStatus } = await import('./api.mts') + + await expect( + queryApiSafeTextWithStatus('scan/status'), + ).resolves.toMatchObject({ + ok: false, + message: 'Authentication Error', + cause: expect.stringContaining('Run `socket login`'), + }) + expect(mockHttpsRequest).not.toHaveBeenCalled() + }) + + it('surfaces an HTTP error response with the requested endpoint', async () => { + stubHttpsResponse({ + body: JSON.stringify({ error: { message: 'scan not found' } }), + headers: { 'content-type': 'application/json' }, + statusCode: 404, + statusMessage: 'Not Found', + }) + const { queryApiSafeTextWithStatus } = await import('./api.mts') + + await expect( + queryApiSafeTextWithStatus('scans/missing'), + ).resolves.toMatchObject({ + ok: false, + message: 'Socket API error', + cause: expect.stringContaining('Not Found: scan not found'), + }) + }) + + it('reports malformed JSON with a bounded preview of the server response', async () => { + const responseText = 'x'.repeat(101) + stubHttpsResponse({ body: responseText }) + const { queryApiSafeJson } = await import('./api.mts') + + await expect(queryApiSafeJson('scan/result')).resolves.toMatchObject({ + ok: false, + message: 'Server returned invalid JSON', + cause: expect.stringContaining(`${'x'.repeat(100)}...`), + }) + }) + + it('sends JSON write bodies with Socket authentication and decodes the response', async () => { + stubHttpsResponse({ + body: '{"accepted":true}', + headers: { 'content-type': 'application/json' }, + }) + const { sendApiRequest } = await import('./api.mts') + + await expect( + sendApiRequest<{ accepted: boolean }>('scans', { + body: { reportId: 'report-1' }, + method: 'POST', + }), + ).resolves.toEqual({ ok: true, data: { accepted: true } }) + + const [url, options] = mockHttpsRequest.mock.calls[0]! + expect(url).toBe('https://api.socket.dev/v0/scans') + expect(options.method).toBe('POST') + expect(options.headers['Content-Type']).toBe('application/json') + expect(options.headers.Authorization).toBe( + `Basic ${btoa('test-api-token:')}`, + ) + expect(mockHttpsRequest.mock.results[0]?.value.write).toHaveBeenCalledWith( + '{"reportId":"report-1"}', + ) + }) + + it('includes the server error and endpoint when a write is rejected', async () => { + stubHttpsResponse({ + body: JSON.stringify({ error: { message: 'write permission required' } }), + headers: { 'content-type': 'application/json' }, + statusCode: 403, + statusMessage: 'Forbidden', + }) + const { sendApiRequest } = await import('./api.mts') + + await expect( + sendApiRequest('scans', { method: 'POST' }), + ).resolves.toMatchObject({ + ok: false, + message: 'Socket API error', + cause: expect.stringContaining( + 'Forbidden: write permission required (reason:', + ), + }) + }) + + it('reports invalid JSON from a successful write response with the endpoint path', async () => { + stubHttpsResponse({ body: 'not-json' }) + const { sendApiRequest } = await import('./api.mts') + + await expect( + sendApiRequest('scans/result', { method: 'PUT' }), + ).resolves.toEqual({ + ok: false, + message: 'API request failed', + cause: 'Unexpected error parsing response JSON (path: scans/result)', + }) + }) +}) + +describe('Socket SDK result handling', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.resetModules() + mockGetConfigValueOrUndef.mockReturnValue(undefined) + mockIsOAuthLoginActive.mockReturnValue(false) + }) + + it('stops the supplied spinner after a successful SDK request', async () => { + const { handleApiCall } = await import('./api.mts') + const spinner = { start: vi.fn(), stop: vi.fn() } + + await expect( + handleApiCall( + Promise.resolve({ success: true, status: 200, data: { id: 'org-1' } }), + { description: 'organization list', spinner }, + ), + ).resolves.toEqual({ ok: true, data: { id: 'org-1' } }) + expect(spinner.start).toHaveBeenCalledWith( + 'Requesting organization list from API...', + ) + expect(spinner.stop).toHaveBeenCalledOnce() + }) + + it('preserves SDK status and cause when a no-spinner request fails', async () => { + const { handleApiCallNoSpinner } = await import('./api.mts') + + await expect( + handleApiCallNoSpinner( + Promise.resolve({ + success: false, + status: 403, + error: 'missing_scope', + cause: 'write operation denied', + url: 'https://api.socket.dev/scans', + }), + 'scan creation', + ), + ).resolves.toEqual({ + ok: false, + message: 'Socket API error', + cause: + 'missing_scope (reason: write operation denied) (url: https://api.socket.dev/scans)', + data: { code: 403 }, + }) + }) + + it('returns a readable error when the SDK promise rejects', async () => { + const { handleApiCallNoSpinner } = await import('./api.mts') + + await expect( + handleApiCallNoSpinner( + Promise.reject(new Error('connection reset')), + 'scan status', + ), + ).resolves.toMatchObject({ + ok: false, + message: 'Socket API error', + cause: 'Error: connection reset', + }) + }) + + it('uses configured API URLs and falls back to the public endpoint', async () => { + const constants = await import('../constants.mts') + const { getDefaultApiBaseUrl } = await import('./api.mts') + + constants.default.ENV.SOCKET_CLI_API_BASE_URL = '' + mockGetConfigValueOrUndef.mockReturnValue('https://staging.socket.dev/v0') + expect(getDefaultApiBaseUrl()).toBe('https://staging.socket.dev/v0') + + mockGetConfigValueOrUndef.mockReturnValue('') + expect(getDefaultApiBaseUrl()).toBe('https://api.socket.dev/v0/') + }) + + it('explains common HTTP failures and preserves the generic fallback', async () => { + const { getErrorMessageForHttpStatusCode } = await import('./api.mts') + + await expect(getErrorMessageForHttpStatusCode(400)).resolves.toMatch( + /options passed.*incorrect/i, + ) + await expect(getErrorMessageForHttpStatusCode(401)).resolves.toMatch( + /token.*invalid.*expired.*revoked/i, + ) + await expect(getErrorMessageForHttpStatusCode(404)).resolves.toMatch( + /not found/i, + ) + await expect(getErrorMessageForHttpStatusCode(500)).resolves.toMatch( + /unknown server side problem/i, + ) + await expect(getErrorMessageForHttpStatusCode(418)).resolves.toMatch( + /status code 418/i, + ) + }) +}) diff --git a/src/utils/editable-json.test.mts b/src/utils/editable-json.test.mts new file mode 100644 index 000000000..6340496a0 --- /dev/null +++ b/src/utils/editable-json.test.mts @@ -0,0 +1,140 @@ +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, describe, expect, it } from 'vitest' + +import { EditableJson, getEditableJsonClass } from './editable-json.mts' + +describe('EditableJson file editing scenarios', () => { + let directory = '' + + afterEach(async () => { + if (directory) { + await fs.rm(directory, { force: true, recursive: true }) + directory = '' + } + }) + + async function createFile(content: string): Promise { + directory = await fs.mkdtemp( + path.join(os.tmpdir(), 'socket-editable-json-'), + ) + const filepath = path.join(directory, 'config.json') + await fs.writeFile(filepath, content) + return filepath + } + + it('loads JSON and retains its filename and parsed content', async () => { + const filepath = await createFile('{\n "enabled": true\n}\n') + const editable = await new EditableJson<{ enabled: boolean }>().load( + filepath, + ) + + expect(editable.path).toBe(filepath) + expect(editable.filename).toBe(filepath) + expect(editable.content).toMatchObject({ enabled: true }) + expect(editable.willSave()).toBe(false) + }) + + it('creates a missing file when load is explicitly allowed to initialize it', async () => { + directory = await fs.mkdtemp( + path.join(os.tmpdir(), 'socket-editable-json-'), + ) + const filepath = path.join(directory, 'new.json') + const editable = await new EditableJson<{ mode: string }>().load( + filepath, + true, + ) + + expect(editable.willSave()).toBe(true) + editable.update({ mode: 'safe' }) + expect(editable.willSave()).toBe(true) + await expect(editable.save()).resolves.toBe(true) + await expect(fs.readFile(filepath, 'utf8')).resolves.toBe( + '{\n "mode": "safe"\n}\n', + ) + }) + + it('preserves CRLF line endings and detected indentation when saving changes', async () => { + const filepath = await createFile('{\r\n\t"enabled": true\r\n}\r\n') + const editable = await new EditableJson<{ + enabled: boolean + mode?: string + }>().load(filepath) + editable.update({ mode: 'safe' }) + + await expect(editable.save()).resolves.toBe(true) + await expect(fs.readFile(filepath, 'utf8')).resolves.toBe( + '{\r\n\t"enabled": true,\r\n\t"mode": "safe"\r\n}\r\n', + ) + }) + + it('sorts keys only when requested and does not mutate the editable content', async () => { + const filepath = await createFile('{}\n') + const editable = await new EditableJson>().load( + filepath, + ) + editable.update({ zebra: 1, alpha: 2 }) + + await expect(editable.save({ sort: true })).resolves.toBe(true) + await expect(fs.readFile(filepath, 'utf8')).resolves.toBe( + '{\n "alpha": 2,\n "zebra": 1\n}\n', + ) + expect(Object.keys(editable.content)).toEqual(['zebra', 'alpha']) + }) + + it('ignores formatting differences when comparing parsed values', async () => { + const filepath = await createFile('{"enabled":true}\n') + const editable = await new EditableJson<{ enabled: boolean }>().load( + filepath, + ) + + expect(editable.willSave()).toBe(true) + expect(editable.willSave({ ignoreWhitespace: true })).toBe(false) + await expect(editable.save({ ignoreWhitespace: true })).resolves.toBe(false) + }) + + it('writes formatting-only changes when whitespace differences are significant', async () => { + const filepath = await createFile('{"enabled":true}\n') + const editable = await new EditableJson<{ enabled: boolean }>().load( + filepath, + ) + editable.fromJSON('{\n "enabled": true\n}\n') + + expect(editable.willSave()).toBe(true) + expect(editable.willSave({ ignoreWhitespace: true })).toBe(false) + await expect(editable.save()).resolves.toBe(true) + await expect(fs.readFile(filepath, 'utf8')).resolves.toBe( + '{\n "enabled": true\n}\n', + ) + }) + + it('does not persist content initialized from an object', async () => { + const editable = new EditableJson<{ enabled: boolean }>().fromContent({ + enabled: true, + }) + + expect(editable.filename).toBe('') + expect(editable.path).toBeUndefined() + expect(editable.willSave()).toBe(false) + await expect(editable.save()).rejects.toThrow('No file path to save to') + }) + + it('creates a new editable instance through the class factory', () => { + const EditableConfig = getEditableJsonClass<{ token: string }>() + const editable = new EditableConfig().create('/tmp/config.json') + + expect(editable.filename).toBe('/tmp/config.json') + expect(editable.content).toEqual({}) + expect(editable.willSave()).toBe(true) + }) + + it('initializes an empty editable file when malformed JSON is explicitly recoverable', async () => { + const filepath = await createFile('{broken json') + + const editable = await new EditableJson().load(filepath, true) + expect(editable.content).toEqual({}) + expect(editable.willSave()).toBe(true) + }) +}) diff --git a/src/utils/logger.test.mts b/src/utils/logger.test.mts new file mode 100644 index 000000000..dff7bdae2 --- /dev/null +++ b/src/utils/logger.test.mts @@ -0,0 +1,212 @@ +import { Writable } from 'node:stream' +import { stripVTControlCharacters } from 'node:util' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { Logger, LOG_SYMBOLS } from './logger.mts' + +function createCapture(): { stream: Writable; read(): string } { + let output = '' + const stream = new Writable({ + write(chunk, _encoding, callback) { + output += chunk.toString() + callback() + }, + }) + return { stream, read: () => stripVTControlCharacters(output) } +} + +describe('Logger output scenarios', () => { + it('prefixes every line inside nested output groups', () => { + const stdout = createCapture() + const stderr = createCapture() + const logger = new Logger(stdout.stream, stderr.stream) + + logger.group('section').log('first\nsecond').group('nested').log('third') + logger.groupEnd().log('fourth').groupEnd() + + expect(stdout.read()).toContain( + 'section\n first\n second\n nested\n third\n fourth\n', + ) + expect(logger.logCallCount).toBe(5) + }) + + it('supports collapsed groups with the same indentation behavior', () => { + const stdout = createCapture() + const logger = new Logger(stdout.stream, createCapture().stream) + + logger.groupCollapsed('details').log('nested').groupEnd() + + expect(stdout.read()).toContain('details\n nested\n') + }) + + it('adds a newline only when the last output was not blank', () => { + const stdout = createCapture() + const logger = new Logger(stdout.stream, createCapture().stream) + + logger.log('message').logNewline().logNewline() + + expect(stdout.read()).toBe('message\n\n') + expect(logger.logCallCount).toBe(2) + }) + + it('tracks error newlines independently from standard output', () => { + const stderr = createCapture() + const logger = new Logger(createCapture().stream, stderr.stream) + + logger.error('problem').errorNewline().errorNewline() + + expect(stderr.read()).toBe('problem\n\n') + expect(logger.logCallCount).toBe(2) + }) + + it('routes status symbols to stderr and counts each status message', () => { + const stdout = createCapture() + const stderr = createCapture() + const logger = new Logger(stdout.stream, stderr.stream) + + logger.info('details').warn('caution').fail('failure').success('complete') + + expect(stdout.read()).toBe('') + expect(stderr.read()).toContain( + `${stripVTControlCharacters(LOG_SYMBOLS.info)} details`, + ) + expect(stderr.read()).toContain( + `${stripVTControlCharacters(LOG_SYMBOLS.warn)} caution`, + ) + expect(stderr.read()).toContain( + `${stripVTControlCharacters(LOG_SYMBOLS.fail)} failure`, + ) + expect(stderr.read()).toContain( + `${stripVTControlCharacters(LOG_SYMBOLS.success)} complete`, + ) + expect(logger.logCallCount).toBe(4) + }) + + it('preserves non-string values passed to ordinary log methods', () => { + const stdout = createCapture() + const logger = new Logger(stdout.stream, createCapture().stream) + const details = { count: 2 } + + logger.log(details, 'items').error(7) + + expect(stdout.read()).toContain('{ count: 2 } items') + expect(logger.logCallCount).toBe(2) + }) + + it('prints a symbol without a message when the first argument is not text', () => { + const stderr = createCapture() + const logger = new Logger(createCapture().stream, stderr.stream) + logger.fail({ code: 'E_FAIL' }) + + expect(stderr.read()).toContain( + `${stripVTControlCharacters(LOG_SYMBOLS.fail)} { code: 'E_FAIL' }`, + ) + expect(logger.logCallCount).toBe(1) + }) + + it('runs task callbacks after printing their task name', () => { + const stdout = createCapture() + const logger = new Logger(stdout.stream, createCapture().stream) + const result = logger.createTask('refresh cache').run(() => 42) + + expect(result).toBe(42) + expect(stdout.read()).toContain('refresh cache') + expect(logger.logCallCount).toBe(1) + }) + + it('returns the logger from chaining and resets indentation explicitly', () => { + const stdout = createCapture() + const logger = new Logger(stdout.stream, createCapture().stream) + + expect(logger.indent(2)).toBe(logger) + expect(logger.dedent()).toBe(logger) + expect(logger.resetIndent()).toBe(logger) + logger.log('root') + expect(stdout.read()).toContain('root') + }) + + it('counts failed assertions but not successful assertions', () => { + const stderr = createCapture() + const logger = new Logger(createCapture().stream, stderr.stream) + + logger.assert(true, 'valid').assert(false, 'invalid') + + expect(logger.logCallCount).toBe(2) + expect(stderr.read()).toContain('Assertion failed: invalid') + }) + + it('counts console inspection and timing methods', () => { + const logger = new Logger(createCapture().stream, createCapture().stream) + + logger + .clear() + .count('requests') + .countReset('requests') + .debug('debug') + .dir({ enabled: true }) + .dirxml('node') + .table([{ id: 1 }]) + .time('work') + .timeLog('work') + .timeEnd('work') + .trace('trace') + + expect(logger.logCallCount).toBeGreaterThanOrEqual(10) + }) +}) + +describe('Windows terminal symbol detection', () => { + const originalPlatform = process.platform + const originalEnvironment = { ...process.env } + + afterEach(() => { + Object.defineProperty(process, 'platform', { + configurable: true, + value: originalPlatform, + }) + for (const key of Object.keys(process.env)) { + if (!(key in originalEnvironment)) delete process.env[key] + } + Object.assign(process.env, originalEnvironment) + vi.resetModules() + }) + + it.each([ + ['Windows Terminal', { WT_SESSION: '1' }], + ['Terminus Sublime marker', { TERMINUS_SUBLIME: '1' }], + ['Cmder task', { ConEmuTask: '{cmd::Cmder}' }], + ['Terminus Sublime program', { TERM_PROGRAM: 'Terminus-Sublime' }], + ['VS Code terminal', { TERM_PROGRAM: 'vscode' }], + ['256 color xterm', { TERM: 'xterm-256color' }], + ['Alacritty', { TERM: 'alacritty' }], + ['Unicode rxvt', { TERM: 'rxvt-unicode' }], + ['256 color Unicode rxvt', { TERM: 'rxvt-unicode-256color' }], + ['JetBrains terminal', { TERMINAL_EMULATOR: 'JetBrains-JediTerm' }], + ])('uses Unicode status symbols for %s', async (_terminal, environment) => { + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32', + }) + for (const key of Object.keys(process.env)) delete process.env[key] + Object.assign(process.env, environment) + vi.resetModules() + + const { LOG_SYMBOLS } = await import('./logger.mts') + + expect(stripVTControlCharacters(LOG_SYMBOLS.fail)).toBe('✖') + }) + + it('uses ASCII status symbols on Windows terminals without Unicode support', async () => { + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32', + }) + for (const key of Object.keys(process.env)) delete process.env[key] + vi.resetModules() + + const { LOG_SYMBOLS } = await import('./logger.mts') + + expect(stripVTControlCharacters(LOG_SYMBOLS.fail)).toBe('×') + }) +}) diff --git a/src/utils/meow-with-subcommands.test.mts b/src/utils/meow-with-subcommands.test.mts new file mode 100644 index 000000000..2eb89d207 --- /dev/null +++ b/src/utils/meow-with-subcommands.test.mts @@ -0,0 +1,691 @@ +import { stripVTControlCharacters } from 'node:util' + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mockMeow = vi.hoisted(() => vi.fn()) +const mockLogger = vi.hoisted(() => ({ + error: vi.fn(), + fail: vi.fn(), + info: vi.fn(), + log: vi.fn(), +})) +const mockGetConfigValueOrUndef = vi.hoisted(() => vi.fn()) +const mockIsConfigFromFlag = vi.hoisted(() => vi.fn(() => false)) +const mockOverrideCachedConfig = vi.hoisted(() => vi.fn(() => ({ ok: true }))) +const mockOverrideConfigApiToken = vi.hoisted(() => vi.fn()) +const mockGetVisibleTokenPrefix = vi.hoisted(() => vi.fn(() => 'sk-test')) + +vi.mock('meow', () => ({ default: mockMeow })) +vi.mock('../constants.mts', async importOriginal => { + const actual = await importOriginal() + return { + ...actual, + default: { + ...actual.default, + ENV: { ...actual.default.ENV }, + }, + } +}) +vi.mock('./config.mts', () => ({ + getConfigValueOrUndef: mockGetConfigValueOrUndef, + isConfigFromFlag: mockIsConfigFromFlag, + overrideCachedConfig: mockOverrideCachedConfig, + overrideConfigApiToken: mockOverrideConfigApiToken, +})) +vi.mock('./logger.mts', () => ({ logger: mockLogger })) +vi.mock('./debug.mts', () => ({ isDebug: vi.fn(() => false) })) +vi.mock('./sdk.mts', () => ({ + getVisibleTokenPrefix: mockGetVisibleTokenPrefix, +})) + +import constants from '../constants.mts' +import { + getLastSeenCommand, + meowOrExit, + meowWithSubcommands, +} from './meow-with-subcommands.mts' + +const importMeta = { url: 'file:///socket-cli-test.mts' } as ImportMeta + +function setParsedFlags(flags: Record = {}) { + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: false, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + ...flags, + }, + showHelp: vi.fn(), + }) +} + +beforeEach(() => { + vi.clearAllMocks() + mockOverrideCachedConfig.mockReset() + mockOverrideCachedConfig.mockReturnValue({ ok: true }) + process.exitCode = 0 + constants.ENV.SOCKET_CLI_CONFIG = '' + constants.ENV.SOCKET_CLI_NO_API_TOKEN = '' + constants.ENV.SOCKET_CLI_API_TOKEN = '' + constants.ENV.CI = false + constants.ENV.VITEST = true + setParsedFlags() +}) + +describe('subcommand dispatch', () => { + it('forwards aliases to their target command with trailing arguments', async () => { + const run = vi.fn() + const subcommands = { scan: { description: 'create scans', run } } + + await meowWithSubcommands( + { name: 'socket', argv: ['s', '--json'], importMeta, subcommands }, + { aliases: { s: { argv: ['scan'], description: 'scan alias' } } }, + ) + + expect(run).toHaveBeenCalledWith(['--json'], importMeta, { + parentName: 'socket', + }) + }) + + it('routes package URL shorthand to the deep package command', async () => { + const run = vi.fn() + const subcommands = { + package: { description: 'score packages', run }, + } + + await meowWithSubcommands({ + name: 'socket', + argv: ['npm/lodash', '--json'], + importMeta, + subcommands, + }) + + expect(run).toHaveBeenCalledWith( + ['deep', 'pkg:npm/lodash', '--json'], + importMeta, + { parentName: 'socket' }, + ) + expect(mockLogger.info).toHaveBeenCalledWith( + 'Invoking `socket package score`.', + ) + }) + + it('routes purl shorthand to the deep package command', async () => { + const run = vi.fn() + await meowWithSubcommands({ + name: 'socket', + argv: ['pkg:npm/lodash@4.17.21'], + importMeta, + subcommands: { package: { description: 'score packages', run } }, + }) + + expect(run).toHaveBeenCalledWith( + ['deep', 'pkg:npm/lodash@4.17.21'], + importMeta, + { parentName: 'socket' }, + ) + }) + + it('suggests a nearby command name for a typo', async () => { + await meowWithSubcommands({ + name: 'socket', + argv: ['scann'], + importMeta, + subcommands: { scan: { description: 'scan projects', run: vi.fn() } }, + }) + + expect(mockLogger.fail).toHaveBeenCalledWith( + 'Unknown command "scann". Did you mean "scan"?', + ) + expect(process.exitCode).toBe(2) + }) + + it('shows usage when the root command has no subcommand', async () => { + const showHelp = vi.fn() + setParsedFlags({ help: false }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: false, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + }, + showHelp, + }) + const publicNames = [ + 'analytics', + 'audit-log', + 'ci', + 'cdxgen', + 'config', + 'dependencies', + 'fix', + 'install', + 'license', + 'login', + 'logout', + 'manifest', + 'npm', + 'npx', + 'optimize', + 'organization', + 'package', + 'patch', + 'raw-npm', + 'raw-npx', + 'repository', + 'scan', + 'threat-feed', + 'uninstall', + 'wrapper', + ] + const subcommands = Object.fromEntries( + publicNames.map(name => [name, { description: name, run: vi.fn() }]), + ) + + await meowWithSubcommands({ + name: 'socket', + argv: [], + importMeta, + subcommands, + }) + + expect(showHelp).toHaveBeenCalledWith(2) + }) + + it('prints the configured version without rendering help', async () => { + const showHelp = vi.fn() + setParsedFlags({ version: true }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: false, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: true, + }, + showHelp, + }) + + await meowWithSubcommands({ + name: 'tool', + argv: ['--version'], + importMeta, + subcommands: {}, + }) + + expect(mockLogger.log).toHaveBeenCalledWith( + constants.ENV.INLINED_SOCKET_CLI_VERSION, + ) + expect(showHelp).not.toHaveBeenCalled() + expect(process.exitCode).toBe(0) + }) + + it('runs the configured default subcommand when no command is supplied', async () => { + const run = vi.fn() + await meowWithSubcommands( + { + name: 'tool', + argv: [], + importMeta, + subcommands: { status: { description: 'show status', run } }, + }, + { defaultSub: 'status' }, + ) + + expect(run).toHaveBeenCalledWith([], importMeta, { parentName: 'tool' }) + }) + + it('resolves aliases to hidden target commands while keeping hidden aliases private', async () => { + const showHelp = vi.fn() + setParsedFlags({ help: true }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: false, + help: true, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + }, + showHelp, + }) + + await meowWithSubcommands( + { + name: 'tool', + argv: ['--help'], + importMeta, + subcommands: { + visible: { description: 'public operation', run: vi.fn() }, + hidden: { + description: 'internal operation', + hidden: true, + run: vi.fn(), + }, + }, + }, + { + aliases: { + v: { argv: ['visible'], description: 'short name' }, + x: { argv: ['hidden'], description: 'internal alias', hidden: true }, + }, + }, + ) + + const help = mockMeow.mock.calls.at(-1)?.[0].help as string + expect(help).toContain('visible') + expect(help).toContain('short name') + expect(help).not.toContain('internal operation') + expect(help).not.toContain('internal alias') + expect(showHelp).toHaveBeenCalledWith(0) + }) + + it('documents environment variables on the full root help screen', async () => { + const showHelp = vi.fn() + setParsedFlags({ help: true }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: false, + help: true, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + }, + showHelp, + }) + const publicNames = [ + 'analytics', + 'audit-log', + 'ci', + 'cdxgen', + 'config', + 'dependencies', + 'fix', + 'install', + 'license', + 'login', + 'logout', + 'manifest', + 'npm', + 'npx', + 'optimize', + 'organization', + 'package', + 'patch', + 'raw-npm', + 'raw-npx', + 'repository', + 'scan', + 'threat-feed', + 'uninstall', + 'wrapper', + ] + const subcommands = Object.fromEntries( + publicNames.map(name => [name, { description: name, run: vi.fn() }]), + ) + + await meowWithSubcommands({ + name: 'socket', + argv: ['--help-full'], + importMeta, + subcommands, + }) + + const help = mockMeow.mock.calls.at(-1)?.[0].help as string + expect(help).toContain('Environment variables for development') + expect(help).toContain('SOCKET_CLI_GITHUB_TOKEN') + expect(showHelp).toHaveBeenCalledWith(0) + }) + + it('prints a successful no-op for a subcommand group in dry-run mode', async () => { + const showHelp = vi.fn() + setParsedFlags({ dryRun: true }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: true, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + }, + showHelp, + }) + + await meowWithSubcommands({ + name: 'tool', + argv: [], + importMeta, + subcommands: {}, + }) + + expect(mockLogger.log).toHaveBeenCalledWith( + expect.stringContaining('No-op, call a sub-command'), + ) + expect(process.exitCode).toBe(0) + expect(showHelp).not.toHaveBeenCalled() + }) + + it('prints a compact diagnostic header with an environment token and configured organization', async () => { + constants.ENV.VITEST = false + constants.ENV.SOCKET_CLI_API_TOKEN = 'environment-token' + mockGetConfigValueOrUndef.mockImplementation(key => + key === 'defaultOrg' ? 'configured-org' : undefined, + ) + setParsedFlags({ compactHeader: true }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: true, + config: undefined, + dryRun: false, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + }, + showHelp: vi.fn(), + }) + + await meowWithSubcommands({ + name: 'tool', + argv: [], + importMeta, + subcommands: {}, + }) + + expect(mockLogger.error).toHaveBeenCalledWith( + expect.stringContaining('token: sk-test*** (env)'), + ) + expect(mockLogger.error).toHaveBeenCalledWith( + expect.stringContaining('org: configured-org'), + ) + }) + + it('shows the disabled-token state and marks config-sourced credentials', async () => { + constants.ENV.VITEST = false + mockGetConfigValueOrUndef.mockImplementation(key => + key === 'apiToken' ? 'saved-token' : undefined, + ) + mockIsConfigFromFlag.mockReturnValue(true) + setParsedFlags({ compactHeader: true }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: true, + config: undefined, + dryRun: false, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: true, + version: false, + }, + showHelp: vi.fn(), + }) + + await meowWithSubcommands({ + name: 'tool', + argv: [], + importMeta, + subcommands: {}, + }) + + expect(mockLogger.error).toHaveBeenCalledWith( + expect.stringContaining('token: sk-test*** (--config flag)'), + ) + + constants.ENV.SOCKET_CLI_NO_API_TOKEN = '1' + await meowWithSubcommands({ + name: 'tool', + argv: [], + importMeta, + subcommands: {}, + }) + expect(mockOverrideConfigApiToken).toHaveBeenCalledWith(undefined) + expect(mockLogger.error).toHaveBeenCalledWith( + expect.stringContaining('token: (disabled)'), + ) + }) + + it('applies a config flag and selects the CI spinner when spinner output is disabled', async () => { + setParsedFlags({ config: '{"defaultOrg":"flag-org"}', spinner: false }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: '{"defaultOrg":"flag-org"}', + dryRun: false, + help: false, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: false, + version: false, + }, + showHelp: vi.fn(), + }) + + await meowWithSubcommands({ + name: 'tool', + argv: [], + importMeta, + subcommands: {}, + }) + + expect(mockOverrideCachedConfig).toHaveBeenCalledWith( + '{"defaultOrg":"flag-org"}', + ) + }) + + it('reports missing public root commands when the command registry is incomplete', async () => { + await meowWithSubcommands({ + name: 'socket', + argv: [], + importMeta, + subcommands: { scan: { description: 'scan projects', run: vi.fn() } }, + }) + + expect(mockLogger.fail).toHaveBeenCalledWith( + 'Found commands in the list that were not marked as public or not defined at all:', + expect.stringContaining("'analytics'"), + ) + }) + + it('shows help for a parsed subcommand and records its diagnostic name', () => { + const showHelp = vi.fn() + setParsedFlags({ help: true, spinner: false }) + mockMeow.mockReturnValue({ + flags: { + compactHeader: false, + config: undefined, + dryRun: false, + help: true, + json: false, + markdown: false, + org: undefined, + silence: false, + spinner: false, + version: false, + }, + showHelp, + }) + + meowOrExit({ + argv: ['--help'], + config: { + commandName: 'list', + description: 'list items', + hidden: false, + flags: { help: { type: 'boolean' } }, + help: () => 'List help', + }, + parentName: 'socket items', + importMeta, + }) + + expect(showHelp).toHaveBeenCalledWith(0) + expect(getLastSeenCommand()).toBe('socket items list') + }) + + it('reports unregistered root commands instead of hiding them from help output', async () => { + await meowWithSubcommands({ + name: 'socket', + argv: [], + importMeta, + subcommands: { + unexpected: { description: 'unregistered command', run: vi.fn() }, + }, + }) + + expect(mockLogger.fail).toHaveBeenCalledWith( + 'Received an unknown command:', + 'unexpected', + ) + }) + + it('handles the legacy version flag explicitly when a command does not define it', () => { + const exitSpy = vi + .spyOn(process, 'exit') + .mockImplementation((() => undefined) as never) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + setParsedFlags({ version: true }) + + try { + expect(() => + meowOrExit({ + argv: ['--version'], + config: { + commandName: 'list', + description: 'list items', + hidden: false, + flags: {}, + help: () => 'List help', + }, + parentName: 'socket items', + importMeta, + }), + ).toThrow('process.exit called') + expect(exitSpy).toHaveBeenCalledWith(2) + expect(consoleError).toHaveBeenCalledWith('Unknown flag\n--version') + } finally { + exitSpy.mockRestore() + consoleError.mockRestore() + } + }) + + it('renders the header without token origin when no token source is configured', async () => { + constants.ENV.VITEST = false + constants.ENV.SOCKET_CLI_API_TOKEN = '' + mockGetConfigValueOrUndef.mockReturnValue(undefined) + + await meowWithSubcommands({ + name: 'tool', + argv: [], + importMeta, + subcommands: {}, + }) + + const header = mockLogger.error.mock.calls + .map(([message]) => stripVTControlCharacters(String(message))) + .find(message => message.includes('token: sk-test***')) + const token = header?.split('token: ')[1]?.split(', org:')[0] + expect(token).toBe('sk-test***') + }) + + it('applies the explicit API token to configuration before command dispatch', async () => { + constants.ENV.SOCKET_CLI_API_TOKEN = 'environment-token' + const run = vi.fn() + + await meowWithSubcommands({ + name: 'tool', + argv: ['run'], + importMeta, + subcommands: { run: { description: 'run task', run } }, + }) + + expect(mockOverrideConfigApiToken).toHaveBeenCalledWith('environment-token') + expect(run).toHaveBeenCalledOnce() + }) + + it('reports invalid configuration and exits before dispatch', async () => { + constants.ENV.SOCKET_CLI_CONFIG = '{invalid' + mockOverrideCachedConfig.mockReturnValue({ + ok: false, + message: 'configuration must be valid JSON', + }) + const run = vi.fn() + + await meowWithSubcommands( + { + name: 'tool', + argv: ['run'], + importMeta, + subcommands: { run: { description: 'run task', run } }, + }, + { flags: { config: { type: 'string' } } }, + ) + + expect(mockLogger.fail).toHaveBeenCalledWith( + 'configuration must be valid JSON', + ) + expect(run).not.toHaveBeenCalled() + expect(process.exitCode).toBe(2) + }) +}) + +describe('meow command parsing', () => { + it('records the latest parsed command for diagnostics', () => { + meowOrExit({ + argv: ['--json'], + config: { + commandName: 'list', + description: 'list items', + hidden: false, + flags: { help: { type: 'boolean' } }, + help: () => 'List help', + }, + parentName: 'socket items', + importMeta, + }) + + expect(getLastSeenCommand()).toBe('socket items list') + }) +}) diff --git a/src/utils/package-manager-paths.test.mts b/src/utils/package-manager-paths.test.mts new file mode 100644 index 000000000..b27565590 --- /dev/null +++ b/src/utils/package-manager-paths.test.mts @@ -0,0 +1,95 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mockFindBinPathDetails = vi.hoisted(() => vi.fn()) +const mockLogger = vi.hoisted(() => ({ fail: vi.fn() })) + +vi.mock('./path-resolve.mts', () => ({ + findBinPathDetailsSync: mockFindBinPathDetails, +})) +vi.mock('./logger.mts', () => ({ logger: mockLogger })) + +beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + process.exitCode = 0 +}) + +describe('PNPM executable path resolution', () => { + it('caches the resolved executable details across path queries', async () => { + mockFindBinPathDetails.mockReturnValue({ + name: 'pnpm', + path: '/tools/pnpm', + shadowed: false, + }) + const paths = await import('./pnpm-paths.mts') + + expect(paths.getPnpmBinPathDetails()).toEqual({ + name: 'pnpm', + path: '/tools/pnpm', + shadowed: false, + }) + expect(paths.getPnpmBinPath()).toBe('/tools/pnpm') + expect(paths.isPnpmBinPathShadowed()).toBe(false) + expect(mockFindBinPathDetails).toHaveBeenCalledOnce() + }) + + it('exits with a clear message when pnpm cannot be located', async () => { + mockFindBinPathDetails.mockReturnValue({ + name: 'pnpm', + path: '', + shadowed: false, + }) + const paths = await import('./pnpm-paths.mts') + const exit = vi + .spyOn(process, 'exit') + .mockImplementation((() => undefined) as never) + + try { + expect(() => paths.getPnpmBinPath()).toThrow('process.exit called') + expect(exit).toHaveBeenCalledWith(127) + expect(mockLogger.fail).toHaveBeenCalledWith( + expect.stringContaining('unable to locate pnpm'), + ) + } finally { + exit.mockRestore() + } + }) +}) + +describe('Yarn executable path resolution', () => { + it('reports a shadowed Yarn executable using cached path details', async () => { + mockFindBinPathDetails.mockReturnValue({ + name: 'yarn', + path: '/tools/yarn', + shadowed: true, + }) + const paths = await import('./yarn-paths.mts') + + expect(paths.getYarnBinPath()).toBe('/tools/yarn') + expect(paths.isYarnBinPathShadowed()).toBe(true) + expect(mockFindBinPathDetails).toHaveBeenCalledWith('yarn') + expect(mockFindBinPathDetails).toHaveBeenCalledOnce() + }) + + it('exits with a clear message when yarn cannot be located', async () => { + mockFindBinPathDetails.mockReturnValue({ + name: 'yarn', + path: '', + shadowed: false, + }) + const paths = await import('./yarn-paths.mts') + const exit = vi + .spyOn(process, 'exit') + .mockImplementation((() => undefined) as never) + + try { + expect(() => paths.getYarnBinPath()).toThrow('process.exit called') + expect(exit).toHaveBeenCalledWith(127) + expect(mockLogger.fail).toHaveBeenCalledWith( + expect.stringContaining('unable to locate yarn'), + ) + } finally { + exit.mockRestore() + } + }) +}) diff --git a/src/utils/temporary-execution-shadowing.test.mts b/src/utils/temporary-execution-shadowing.test.mts new file mode 100644 index 000000000..1b395c6f3 --- /dev/null +++ b/src/utils/temporary-execution-shadowing.test.mts @@ -0,0 +1,58 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const runtimeEnv = vi.hoisted(() => ({ + npm_config_cache: undefined as string | undefined, + npm_config_user_agent: undefined as string | undefined, +})) + +vi.mock('../constants.mts', () => ({ default: { ENV: runtimeEnv } })) +vi.mock('./path.mts', () => ({ + normalizePath: (value: string) => value.replaceAll('\\', '/'), +})) + +import { + isRunningInTemporaryExecutor, + shouldSkipShadow, +} from './dlx-detection.mts' + +describe('temporary package execution shadowing', () => { + beforeEach(() => { + runtimeEnv.npm_config_cache = undefined + runtimeEnv.npm_config_user_agent = undefined + }) + + it('detects npm exec from the package manager user agent', () => { + runtimeEnv.npm_config_user_agent = 'npm/10.0.0 node/v20.0.0 exec' + + expect(isRunningInTemporaryExecutor()).toBe(true) + expect(shouldSkipShadow('', { cwd: '/repo' })).toBe(true) + }) + + it('detects execution from inside the configured npm cache', () => { + runtimeEnv.npm_config_cache = `${process.cwd()}/src` + + expect(isRunningInTemporaryExecutor()).toBe(true) + }) + + it('detects pnpm dlx and Yarn virtual-package working directories', () => { + runtimeEnv.npm_config_user_agent = 'pnpm/9.0.0 dlx' + expect(isRunningInTemporaryExecutor()).toBe(true) + + runtimeEnv.npm_config_user_agent = undefined + expect(shouldSkipShadow('', { cwd: '/repo/.yarn/$$virtual/app' })).toBe( + true, + ) + }) + + it('skips an existing Windows executable shadow without relying on package-manager state', () => { + expect( + shouldSkipShadow('C:\\tools\\npm.cmd', { cwd: '/repo', win32: true }), + ).toBe(true) + expect(shouldSkipShadow('', { cwd: '/repo', win32: true })).toBe(false) + }) + + it('allows persistent shadows from ordinary project directories', () => { + expect(isRunningInTemporaryExecutor()).toBe(false) + expect(shouldSkipShadow('', { cwd: '/repo/project' })).toBe(false) + }) +}) diff --git a/src/utils/yarn-version.test.mts b/src/utils/yarn-version.test.mts new file mode 100644 index 000000000..cb4bbc9d7 --- /dev/null +++ b/src/utils/yarn-version.test.mts @@ -0,0 +1,58 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { getYarnBinPath, spawnSync } = vi.hoisted(() => ({ + getYarnBinPath: vi.fn(() => '/test/bin/yarn'), + spawnSync: vi.fn(), +})) + +vi.mock('./yarn-paths.mts', () => ({ getYarnBinPath })) +vi.mock('./spawn-sync.mts', () => ({ spawnSync })) +vi.mock('../constants.mts', () => ({ + default: { WIN32: false }, + FLAG_VERSION: '--version', + UTF8: 'utf8', +})) + +describe('Yarn generation detection', () => { + beforeEach(() => { + vi.resetModules() + getYarnBinPath.mockReset().mockReturnValue('/test/bin/yarn') + spawnSync.mockReset() + }) + + it('recognizes Yarn Berry from a successful major version 2 response', async () => { + spawnSync.mockReturnValue({ status: 0, stdout: Buffer.from('4.2.0\n') }) + const { isYarnBerry } = await import('./yarn-version.mts') + + expect(isYarnBerry()).toBe(true) + expect(isYarnBerry()).toBe(true) + expect(spawnSync).toHaveBeenCalledTimes(1) + expect(spawnSync).toHaveBeenCalledWith('/test/bin/yarn', ['--version'], { + encoding: 'utf8', + shell: false, + }) + }) + + it('treats a successful Yarn 1 version as Classic', async () => { + spawnSync.mockReturnValue({ status: 0, stdout: Buffer.from('1.22.22') }) + const { isYarnBerry } = await import('./yarn-version.mts') + + expect(isYarnBerry()).toBe(false) + }) + + it('treats a failed version command as Classic', async () => { + spawnSync.mockReturnValue({ status: 1, stdout: Buffer.from('') }) + const { isYarnBerry } = await import('./yarn-version.mts') + + expect(isYarnBerry()).toBe(false) + }) + + it('falls back to Classic when Yarn cannot be located', async () => { + getYarnBinPath.mockImplementation(() => { + throw new Error('yarn not found') + }) + const { isYarnBerry } = await import('./yarn-version.mts') + + expect(isYarnBerry()).toBe(false) + }) +}) diff --git a/test/unit/scripts/coverage-badge.test.mts b/test/unit/scripts/coverage-badge.test.mts new file mode 100644 index 000000000..8863d6219 --- /dev/null +++ b/test/unit/scripts/coverage-badge.test.mts @@ -0,0 +1,67 @@ +import { mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { afterEach, describe, expect, it } from 'vitest' + +import { + formatCoverageBadge, + isCoverageBadgeEntrypoint, + updateCoverageBadge, +} from '../../../scripts/coverage-badge.mts' + +describe('coverage badge generation', () => { + let temporaryDirectory: string | undefined + + afterEach(async () => { + if (temporaryDirectory) { + await rm(temporaryDirectory, { recursive: true, force: true }) + temporaryDirectory = undefined + } + }) + + it('uses the coverage band matching the measured line percentage', () => { + expect(formatCoverageBadge(79.4)).toContain('coverage-79%25-red') + expect(formatCoverageBadge(79.5)).toContain('coverage-80%25-yellow') + expect(formatCoverageBadge(90)).toContain('coverage-90%25-brightgreen') + }) + + it('recognizes the script when launched through a symlinked path', async () => { + temporaryDirectory = await mkdtemp( + path.join(os.tmpdir(), 'socket-coverage-link-'), + ) + const scriptPath = fileURLToPath( + new URL('../../../scripts/coverage-badge.mts', import.meta.url), + ) + const symlinkPath = path.join(temporaryDirectory, 'coverage-badge.mts') + await symlink(scriptPath, symlinkPath) + + expect(isCoverageBadgeEntrypoint(symlinkPath)).toBe(true) + expect( + isCoverageBadgeEntrypoint(path.join(temporaryDirectory, 'other.mts')), + ).toBe(false) + }) + + it('replaces only the generated badge between README markers', async () => { + temporaryDirectory = await mkdtemp( + path.join(os.tmpdir(), 'socket-coverage-'), + ) + const readmePath = path.join(temporaryDirectory, 'README.md') + const summaryPath = path.join(temporaryDirectory, 'coverage-summary.json') + await writeFile( + readmePath, + 'intro\n\nold badge\n\noutro\n', + ) + await writeFile( + summaryPath, + JSON.stringify({ total: { lines: { pct: 91.4 } } }), + ) + + await updateCoverageBadge({ readmePath, summaryPath }) + + expect(await readFile(readmePath, 'utf8')).toBe( + 'intro\n\n[![Coverage](https://img.shields.io/badge/coverage-91%25-brightgreen)](https://github.com/SocketDev/socket-cli/actions)\n\noutro\n', + ) + }) +}) diff --git a/test/unit/utils/home-path-display.test.mts b/test/unit/utils/home-path-display.test.mts new file mode 100644 index 000000000..d8164b579 --- /dev/null +++ b/test/unit/utils/home-path-display.test.mts @@ -0,0 +1,24 @@ +import path from 'node:path' + +import { describe, expect, it } from 'vitest' + +import constants from '../../../src/constants.mts' +import { tildify } from '../../../src/utils/tildify.mts' + +describe('home path display', () => { + it('abbreviates the home directory while preserving child paths', () => { + expect( + tildify(path.join(constants.homePath, 'projects', 'socket-cli')), + ).toBe('~/projects/socket-cli') + }) + + it('keeps sibling paths that only share the home directory prefix', () => { + expect(tildify(`${constants.homePath}-archive/project`)).toBe( + `${constants.homePath}-archive/project`, + ) + }) + + it('abbreviates the home directory itself with a trailing separator', () => { + expect(tildify(constants.homePath)).toBe('~/') + }) +}) diff --git a/test/unit/utils/organization-plans.test.mts b/test/unit/utils/organization-plans.test.mts new file mode 100644 index 000000000..499ea0559 --- /dev/null +++ b/test/unit/utils/organization-plans.test.mts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' + +import { + getEnterpriseOrgs, + getOrgSlugs, + hasEnterpriseOrgPlan, +} from '../../../src/utils/organization.mts' + +import type { Organizations } from '../../../src/commands/organization/fetch-organization-list.mts' + +describe('organization plan selection', () => { + const organizations = [ + { slug: 'starter-team', plan: 'starter' }, + { slug: 'enterprise-team', plan: 'enterprise' }, + { slug: 'enterprise-plus-team', plan: 'enterprise-plus' }, + ] as Organizations + + it('selects enterprise organizations without changing their order', () => { + expect(getEnterpriseOrgs(organizations).map(org => org.slug)).toEqual([ + 'enterprise-team', + 'enterprise-plus-team', + ]) + }) + + it('returns organization slugs in API order', () => { + expect(getOrgSlugs(organizations)).toEqual([ + 'starter-team', + 'enterprise-team', + 'enterprise-plus-team', + ]) + }) + + it('reports no enterprise plan when every organization is on a standard plan', () => { + expect( + hasEnterpriseOrgPlan([ + { slug: 'starter-team', plan: 'starter' }, + ] as Organizations), + ).toBe(false) + }) +}) diff --git a/test/unit/utils/relative-activity-time.test.mts b/test/unit/utils/relative-activity-time.test.mts new file mode 100644 index 000000000..7ae57282b --- /dev/null +++ b/test/unit/utils/relative-activity-time.test.mts @@ -0,0 +1,23 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { msAtHome } from '../../../src/utils/ms-at-home.mts' + +afterEach(() => { + vi.useRealTimers() +}) + +describe('relative activity time display', () => { + it('rounds recent activity to the nearest minute', () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-01-01T12:00:00.000Z')) + + expect(msAtHome('2026-01-01T11:58:30.000Z')).toBe('2 min. ago') + }) + + it('uses a dated display after activity is at least one week old', () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-01-10T12:00:00.000Z')) + + expect(msAtHome('2026-01-01T11:00:00.000Z')).toBe('2026-01-01') + }) +})