-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcli.mts
More file actions
executable file
·171 lines (144 loc) · 5.2 KB
/
cli.mts
File metadata and controls
executable file
·171 lines (144 loc) · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env node
import { fileURLToPath, pathToFileURL } from 'node:url'
import meow from 'meow'
import { messageWithCauses, stackWithCauses } from 'pony-cause'
import lookupRegistryAuthToken from 'registry-auth-token'
import lookupRegistryUrl from 'registry-url'
import updateNotifier from 'tiny-updater'
import colors from 'yoctocolors-cjs'
import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug'
import { logger } from '@socketsecurity/registry/lib/logger'
import { rootAliases, rootCommands } from './commands.mts'
import constants from './constants.mts'
import { AuthError, InputError, captureException } from './utils/errors.mts'
import { failMsgWithBadge } from './utils/fail-msg-with-badge.mts'
import { meowWithSubcommands } from './utils/meow-with-subcommands.mts'
import { serializeResultJson } from './utils/serialize-result-json.mts'
import {
finalizeTelemetry,
setupTelemetryExitHandlers,
trackCliComplete,
trackCliError,
trackCliStart,
} from './utils/telemetry/integration.mts'
import { socketPackageLink } from './utils/terminal-link.mts'
const __filename = fileURLToPath(import.meta.url)
// Capture CLI start time at module level for global error handlers.
const cliStartTime = Date.now()
// Set up telemetry exit handlers early to catch all exit scenarios.
setupTelemetryExitHandlers()
void (async () => {
// Track CLI start for telemetry.
await trackCliStart(process.argv)
const registryUrl = lookupRegistryUrl()
await updateNotifier({
authInfo: lookupRegistryAuthToken(registryUrl, { recursive: true }),
name: constants.SOCKET_CLI_BIN_NAME,
registryUrl,
ttl: 86_400_000 /* 24 hours in milliseconds */,
version: constants.ENV.INLINED_SOCKET_CLI_VERSION,
logCallback: (name: string, version: string, latest: string) => {
logger.log(
`\n\n📦 Update available for ${colors.cyan(name)}: ${colors.gray(version)} → ${colors.green(latest)}`,
)
logger.log(
`📝 ${socketPackageLink('npm', name, `files/${latest}/CHANGELOG.md`, 'View changelog')}`,
)
},
})
try {
await meowWithSubcommands(
{
name: constants.SOCKET_CLI_BIN_NAME,
argv: process.argv.slice(2),
importMeta: { url: `${pathToFileURL(__filename)}` } as ImportMeta,
subcommands: rootCommands,
},
{ aliases: rootAliases },
)
// Track successful CLI completion.
await trackCliComplete(process.argv, cliStartTime, process.exitCode)
} catch (e) {
process.exitCode = 1
// Track CLI error for telemetry.
await trackCliError(process.argv, cliStartTime, e, process.exitCode)
debugFn('error', 'CLI uncaught error')
debugDir('error', e)
let errorBody: string | undefined
let errorTitle: string
let errorMessage = ''
if (e instanceof AuthError) {
errorTitle = 'Authentication error'
errorMessage = e.message
} else if (e instanceof InputError) {
errorTitle = 'Invalid input'
errorMessage = e.message
errorBody = e.body
} else if (e instanceof Error) {
errorTitle = 'Unexpected error'
errorMessage = messageWithCauses(e)
errorBody = stackWithCauses(e)
} else {
errorTitle = 'Unexpected error with no details'
}
// Try to parse the flags, find out if --json is set.
const isJson = (() => {
const cli = meow({
argv: process.argv.slice(2),
// Prevent meow from potentially exiting early.
autoHelp: false,
autoVersion: false,
flags: {},
importMeta: { url: `${pathToFileURL(__filename)}` } as ImportMeta,
})
return !!cli.flags['json']
})()
if (isJson) {
logger.log(
serializeResultJson({
ok: false,
message: errorTitle,
cause: errorMessage,
}),
)
} else {
// Add 2 newlines in stderr to bump below any spinner.
logger.error('\n')
logger.fail(failMsgWithBadge(errorTitle, errorMessage))
if (errorBody) {
debugDir('inspect', { errorBody })
}
}
await captureException(e)
}
})().catch(async err => {
// Fatal error in main async function.
console.error('Fatal error:', err)
// Track CLI error for fatal exceptions.
await trackCliError(process.argv, cliStartTime, err, 1)
// Finalize telemetry before fatal exit.
await finalizeTelemetry()
// eslint-disable-next-line n/no-process-exit
process.exit(1)
})
// Handle uncaught exceptions.
process.on('uncaughtException', async err => {
console.error('Uncaught exception:', err)
// Track CLI error for uncaught exception.
await trackCliError(process.argv, cliStartTime, err, 1)
// Finalize telemetry before exit.
await finalizeTelemetry()
// eslint-disable-next-line n/no-process-exit
process.exit(1)
})
// Handle unhandled promise rejections.
process.on('unhandledRejection', async (reason, promise) => {
console.error('Unhandled rejection at:', promise, 'reason:', reason)
// Track CLI error for unhandled rejection.
const error = reason instanceof Error ? reason : new Error(String(reason))
await trackCliError(process.argv, cliStartTime, error, 1)
// Finalize telemetry before exit.
await finalizeTelemetry()
// eslint-disable-next-line n/no-process-exit
process.exit(1)
})