Skip to content

Commit e085e37

Browse files
committed
Rename issue to alert
1 parent 5bc6e34 commit e085e37

File tree

10 files changed

+99
-85
lines changed

10 files changed

+99
-85
lines changed

.config/rollup.test.config.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ const {
1818

1919
export default () =>
2020
baseConfig({
21-
input: ['alert-rules', 'errors', 'path-resolve'].reduce((o, k) => {
22-
o[k] = `${rootSrcPath}/utils/${k}.ts`
21+
input: ['alert/rules', 'errors', 'path-resolve'].reduce((o, k) => {
22+
o[k.replaceAll('/', '-')] = `${rootSrcPath}/utils/${k}.ts`
2323
return o
2424
}, {}),
2525
output: [

src/commands/info.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,20 @@ import constants from '@socketsecurity/registry/lib/constants'
77
import { Spinner } from '@socketsecurity/registry/lib/spinner'
88

99
import { commonFlags, outputFlags, validationFlags } from '../flags'
10+
import { formatSeverityCount, getSeverityCount } from '../utils/alert/severity'
1011
import { handleApiCall, handleUnsuccessfulApiResponse } from '../utils/api'
1112
import { ColorOrMarkdown } from '../utils/color-or-markdown'
1213
import { InputError } from '../utils/errors'
1314
import { objectSome } from '../utils/objects'
1415
import { getFlagListOutput } from '../utils/output-formatting'
1516
import { getPublicToken, setupSdk } from '../utils/sdk'
16-
import { formatSeverityCount, getSeverityCount } from '../utils/sdk-issues'
1717
import {
1818
getSocketDevAlertUrl,
1919
getSocketDevPackageOverviewUrl
2020
} from '../utils/socket-url'
2121

22+
import type { SocketAlert } from '../utils/alert/severity'
2223
import type { CliSubcommand } from '../utils/meow-with-subcommands'
23-
import type { SocketIssue } from '../utils/sdk-issues'
2424
import type { SocketSdkReturnType } from '@socketsecurity/sdk'
2525

2626
const { NPM } = constants
@@ -129,7 +129,7 @@ function setupCommand(
129129

130130
interface PackageData {
131131
data: SocketSdkReturnType<'getIssuesByNPMPackage'>['data']
132-
severityCount: Record<SocketIssue['severity'], number>
132+
severityCount: Record<SocketAlert['severity'], number>
133133
score: SocketSdkReturnType<'getScoreByNPMPackage'>['data']
134134
}
135135

src/commands/optimize.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import fs from 'node:fs/promises'
21
import path from 'node:path'
32
import process from 'node:process'
43

@@ -28,7 +27,7 @@ import { pluralize } from '@socketsecurity/registry/lib/words'
2827

2928
import constants from '../constants'
3029
import { commonFlags } from '../flags'
31-
import { existsSync } from '../utils/fs'
30+
import { safeReadFile } from '../utils/fs'
3231
import { getFlagListOutput } from '../utils/output-formatting'
3332
import { detect } from '../utils/package-manager-detector'
3433
import { shadowNpmInstall } from '../utils/shadow-npm'
@@ -541,12 +540,11 @@ async function getWorkspaceGlobs(
541540
path.join(pkgPath!, `${PNPM_WORKSPACE}.yaml`),
542541
path.join(pkgPath!, `${PNPM_WORKSPACE}.yml`)
543542
]) {
544-
if (existsSync(workspacePath)) {
543+
// eslint-disable-next-line no-await-in-loop
544+
const yml = <string | undefined>await safeReadFile(workspacePath, 'utf8')
545+
if (yml) {
545546
try {
546-
workspacePatterns = yamlParse(
547-
// eslint-disable-next-line no-await-in-loop
548-
await fs.readFile(workspacePath, 'utf8')
549-
)?.packages
547+
workspacePatterns = yamlParse(yml)?.packages
550548
} catch {}
551549
if (workspacePatterns) {
552550
break

src/commands/report/view.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,15 @@ import colors from 'yoctocolors-cjs'
77
import { Spinner } from '@socketsecurity/registry/lib/spinner'
88

99
import { commonFlags, outputFlags, validationFlags } from '../../flags'
10+
import {
11+
formatSeverityCount,
12+
getSeverityCount
13+
} from '../../utils/alert/severity'
1014
import { handleApiCall, handleUnsuccessfulApiResponse } from '../../utils/api'
1115
import { ColorOrMarkdown } from '../../utils/color-or-markdown'
1216
import { InputError } from '../../utils/errors'
1317
import { getFlagListOutput } from '../../utils/output-formatting'
1418
import { setupSdk } from '../../utils/sdk'
15-
import { formatSeverityCount, getSeverityCount } from '../../utils/sdk-issues'
1619

1720
import type { CliSubcommand } from '../../utils/meow-with-subcommands'
1821
import type {

src/shadow/arborist/lib/arborist/reify.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { Spinner } from '@socketsecurity/registry/lib/spinner'
1515
import { batchScan, isAlertFixable, isAlertFixableCve, walk } from './alerts'
1616
import { kCtorArgs, kRiskyReify } from './index'
1717
import constants from '../../../../constants'
18-
import { uxLookup } from '../../../../utils/alert-rules'
18+
import { uxLookup } from '../../../../utils/alert/rules'
1919
import { ColorOrMarkdown } from '../../../../utils/color-or-markdown'
2020
import { debugLog } from '../../../../utils/debug'
2121
import { getSocketDevPackageOverviewUrl } from '../../../../utils/socket-url'
@@ -400,9 +400,7 @@ export async function reify(
400400
)
401401
})())
402402
if (proceed) {
403-
const fix =
404-
!!alerts?.length &&
405-
bypassConfirms /*||
403+
const fix = !!alerts?.length && bypassConfirms /*||
406404
(await confirm(
407405
{
408406
message: 'Try to fix alerts?',

src/utils/alert-rules.ts renamed to src/utils/alert/rules.ts

Lines changed: 4 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
1-
import { readFileSync } from 'node:fs'
2-
import path from 'node:path'
3-
import process from 'node:process'
41
import { setTimeout as wait } from 'node:timers/promises'
52

6-
import config from '@socketsecurity/config'
73
import { isObject } from '@socketsecurity/registry/lib/objects'
84

9-
import { isErrnoException } from './errors'
10-
import { getPublicToken, setupSdk } from './sdk'
11-
import { getSetting } from './settings'
12-
import constants from '../constants'
5+
import constants from '../../constants'
6+
import { isErrnoException } from '../errors'
7+
import { getPublicToken, setupSdk } from '../sdk'
8+
import { findSocketYmlSync, getSetting } from '../settings'
139

1410
import type { SocketSdkResultType } from '@socketsecurity/sdk'
1511

@@ -60,39 +56,6 @@ const WARN_UX: RuleActionUX = {
6056
display: true
6157
}
6258

63-
function findSocketYmlSync() {
64-
let prevDir = null
65-
let dir = process.cwd()
66-
while (dir !== prevDir) {
67-
let ymlPath = path.join(dir, 'socket.yml')
68-
let yml = maybeReadfileSync(ymlPath)
69-
if (yml === undefined) {
70-
ymlPath = path.join(dir, 'socket.yaml')
71-
yml = maybeReadfileSync(ymlPath)
72-
}
73-
if (typeof yml === 'string') {
74-
try {
75-
return {
76-
path: ymlPath,
77-
parsed: config.parseSocketConfig(yml)
78-
}
79-
} catch {
80-
throw new Error(`Found file but was unable to parse ${ymlPath}`)
81-
}
82-
}
83-
prevDir = dir
84-
dir = path.join(dir, '..')
85-
}
86-
return null
87-
}
88-
89-
function maybeReadfileSync(filepath: string): string | undefined {
90-
try {
91-
return readFileSync(filepath, 'utf8')
92-
} catch {}
93-
return undefined
94-
}
95-
9659
// Iterates over all entries with ordered issue rule for deferral. Iterates over
9760
// all issue rules and finds the first defined value that does not defer otherwise
9861
// uses the defaultValue. Takes the value and converts into a UX workflow.

src/utils/sdk-issues.ts renamed to src/utils/alert/severity.ts

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
1-
import { pick } from './objects'
2-
import { stringJoinWithSeparateFinalSeparator } from './strings'
1+
import { pick } from '../objects'
2+
import { stringJoinWithSeparateFinalSeparator } from '../strings'
33

44
import type { SocketSdkReturnType } from '@socketsecurity/sdk'
55

6-
type SocketIssueList = SocketSdkReturnType<'getIssuesByNPMPackage'>['data']
6+
type SocketAlertList = SocketSdkReturnType<'getIssuesByNPMPackage'>['data']
77

8-
export type SocketIssue = SocketIssueList[number]['value'] extends
8+
export type SocketAlert = SocketAlertList[number]['value'] extends
99
| infer U
1010
| undefined
1111
? U
1212
: never
1313

14-
const SEVERITIES_BY_ORDER: SocketIssue['severity'][] = [
14+
// Ordered from most severe to least.
15+
const SEVERITIES_BY_ORDER: SocketAlert['severity'][] = [
1516
'critical',
1617
'high',
1718
'middle',
1819
'low'
1920
]
2021

2122
function getDesiredSeverities(
22-
lowestToInclude: SocketIssue['severity'] | undefined
23-
): SocketIssue['severity'][] {
24-
const result: SocketIssue['severity'][] = []
23+
lowestToInclude: SocketAlert['severity'] | undefined
24+
): SocketAlert['severity'][] {
25+
const result: SocketAlert['severity'][] = []
2526
for (const severity of SEVERITIES_BY_ORDER) {
2627
result.push(severity)
2728
if (severity === lowestToInclude) {
@@ -32,7 +33,7 @@ function getDesiredSeverities(
3233
}
3334

3435
export function formatSeverityCount(
35-
severityCount: Record<SocketIssue['severity'], number>
36+
severityCount: Record<SocketAlert['severity'], number>
3637
): string {
3738
const summary: string[] = []
3839
for (const severity of SEVERITIES_BY_ORDER) {
@@ -44,13 +45,13 @@ export function formatSeverityCount(
4445
}
4546

4647
export function getSeverityCount(
47-
issues: SocketIssueList,
48-
lowestToInclude: SocketIssue['severity'] | undefined
49-
): Record<SocketIssue['severity'], number> {
48+
issues: SocketAlertList,
49+
lowestToInclude: SocketAlert['severity'] | undefined
50+
): Record<SocketAlert['severity'], number> {
5051
const severityCount = pick(
5152
{ low: 0, middle: 0, high: 0, critical: 0 },
5253
getDesiredSeverities(lowestToInclude)
53-
) as Record<SocketIssue['severity'], number>
54+
) as Record<SocketAlert['severity'], number>
5455

5556
for (const issue of issues) {
5657
const { value } = issue

src/utils/fs.ts

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
1-
import { existsSync as existsSync_, promises as fs } from 'node:fs'
1+
import {
2+
promises as fs,
3+
existsSync as fsExistsSync,
4+
readFileSync as fsReadFileSync
5+
} from 'node:fs'
26
import path from 'node:path'
37
import process from 'node:process'
48

59
import type { Abortable } from 'node:events'
610
import type { ObjectEncodingOptions, OpenMode, PathLike } from 'node:fs'
711
import type { FileHandle } from 'node:fs/promises'
812

9-
export function existsSync(filepath: any): filepath is PathLike {
10-
try {
11-
return filepath ? existsSync_(filepath) : false
12-
} catch {}
13-
return false
14-
}
15-
1613
export async function findUp(
1714
name: string | string[],
1815
{ cwd = process.cwd() }: { cwd: string | undefined }
@@ -60,3 +57,28 @@ export async function readFileUtf8(
6057
encoding: 'utf8'
6158
})
6259
}
60+
61+
export function safeExistsSync(filepath: PathLike | undefined): boolean {
62+
try {
63+
return filepath ? fsExistsSync(filepath) : false
64+
} catch {}
65+
return false
66+
}
67+
68+
export function safeReadFile(
69+
...args: Parameters<typeof fs.readFile>
70+
): ReturnType<typeof fs.readFile> | undefined {
71+
try {
72+
return fs.readFile(...args)
73+
} catch {}
74+
return undefined
75+
}
76+
77+
export function safeReadFileSync(
78+
...args: Parameters<typeof fsReadFileSync>
79+
): ReturnType<typeof fsReadFileSync> | undefined {
80+
try {
81+
return fsReadFileSync(...args)
82+
} catch {}
83+
return undefined
84+
}

src/utils/package-manager-detector.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { isObjectObject } from '@socketsecurity/registry/lib/objects'
1111
import { readPackageJson } from '@socketsecurity/registry/lib/packages'
1212
import { isNonEmptyString } from '@socketsecurity/registry/lib/strings'
1313

14-
import { existsSync, findUp, readFileBinary, readFileUtf8 } from './fs'
14+
import { findUp, readFileBinary, readFileUtf8, safeExistsSync } from './fs'
1515
import constants from '../constants'
1616

1717
import type { EditablePackageJson } from '@socketsecurity/registry/lib/packages'
@@ -173,8 +173,8 @@ export async function detect({
173173
const pkgJsonPath = lockPath
174174
? path.resolve(lockPath, `${isHiddenLockFile ? '../' : ''}../package.json`)
175175
: await findUp('package.json', { cwd })
176-
const pkgPath = existsSync(pkgJsonPath)
177-
? path.dirname(pkgJsonPath)
176+
const pkgPath = safeExistsSync(pkgJsonPath)
177+
? path.dirname(pkgJsonPath!)
178178
: undefined
179179
const editablePkgJson = pkgPath
180180
? await readPackageJson(pkgPath, { editable: true })

src/utils/settings.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
1+
import { mkdirSync, writeFileSync } from 'node:fs'
22
import os from 'node:os'
33
import path from 'node:path'
44
import process from 'node:process'
55

6+
import config from '@socketsecurity/config'
7+
8+
import { safeReadFileSync } from './fs'
69
import { logger } from './logging'
710
import constants from '../constants'
811

@@ -21,8 +24,8 @@ function getSettings(): Settings {
2124
_settings = <Settings>{}
2225
const settingsPath = getSettingsPath()
2326
if (settingsPath) {
24-
if (existsSync(settingsPath)) {
25-
const raw = readFileSync(settingsPath, 'utf8')
27+
const raw = <string | undefined>safeReadFileSync(settingsPath, 'utf8')
28+
if (raw) {
2629
try {
2730
Object.assign(
2831
_settings,
@@ -70,6 +73,32 @@ function getSettingsPath(): string | undefined {
7073
return _settingsPath
7174
}
7275

76+
export function findSocketYmlSync() {
77+
let prevDir = null
78+
let dir = process.cwd()
79+
while (dir !== prevDir) {
80+
let ymlPath = path.join(dir, 'socket.yml')
81+
let yml = <string | undefined>safeReadFileSync(ymlPath, 'utf8')
82+
if (yml === undefined) {
83+
ymlPath = path.join(dir, 'socket.yaml')
84+
yml = <string | undefined>safeReadFileSync(ymlPath, 'utf8')
85+
}
86+
if (typeof yml === 'string') {
87+
try {
88+
return {
89+
path: ymlPath,
90+
parsed: config.parseSocketConfig(yml)
91+
}
92+
} catch {
93+
throw new Error(`Found file but was unable to parse ${ymlPath}`)
94+
}
95+
}
96+
prevDir = dir
97+
dir = path.join(dir, '..')
98+
}
99+
return null
100+
}
101+
73102
export function getSetting<Key extends keyof Settings>(
74103
key: Key
75104
): Settings[Key] {

0 commit comments

Comments
 (0)