codebuff 1.0.683 → 1.0.685
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/http.js +275 -12
- package/index.js +23 -936
- package/launcher.js +1217 -0
- package/package.json +4 -4
- package/postinstall.js +0 -34
package/launcher.js
ADDED
|
@@ -0,0 +1,1217 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const { spawn, execFileSync } = require('child_process')
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const http = require('http')
|
|
6
|
+
const https = require('https')
|
|
7
|
+
const os = require('os')
|
|
8
|
+
const path = require('path')
|
|
9
|
+
const { pipeline } = require('stream/promises')
|
|
10
|
+
const zlib = require('zlib')
|
|
11
|
+
|
|
12
|
+
const tar = require('tar')
|
|
13
|
+
const { createReleaseHttpClient } = require('./http')
|
|
14
|
+
|
|
15
|
+
function createLauncher(productConfig) {
|
|
16
|
+
const {
|
|
17
|
+
packageName,
|
|
18
|
+
displayName,
|
|
19
|
+
includeTreeSitterWasm = true,
|
|
20
|
+
startupBanner = [],
|
|
21
|
+
telemetryEvent = 'cli.update_codebuff_failed',
|
|
22
|
+
telemetryProperties = {},
|
|
23
|
+
tempDownloadDirName = `.${packageName}-download-temp`,
|
|
24
|
+
} = productConfig
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Terminal escape sequences to reset terminal state after the child process exits.
|
|
28
|
+
* When the binary is SIGKILL'd, it can't clean up its own terminal state.
|
|
29
|
+
* The wrapper (this process) survives and must reset these modes.
|
|
30
|
+
*/
|
|
31
|
+
const EXIT_ALTERNATE_SCREEN_SEQUENCE = '\x1b[?1049l'
|
|
32
|
+
const SAFE_TERMINAL_RESET_SEQUENCES =
|
|
33
|
+
'\x1b[?1000l' + // Disable X10 mouse mode
|
|
34
|
+
'\x1b[?1002l' + // Disable button event mouse mode
|
|
35
|
+
'\x1b[?1003l' + // Disable any-event mouse mode (all motion)
|
|
36
|
+
'\x1b[?1006l' + // Disable SGR extended mouse mode
|
|
37
|
+
'\x1b[?1004l' + // Disable focus reporting
|
|
38
|
+
'\x1b[?2004l' + // Disable bracketed paste mode
|
|
39
|
+
'\x1b[<u' + // Pop kitty keyboard protocol flags
|
|
40
|
+
'\x1b[>4;0m' + // Reset modifyOtherKeys
|
|
41
|
+
'\x1b[?25h' // Show cursor
|
|
42
|
+
|
|
43
|
+
const FULL_TERMINAL_RESET_SEQUENCES =
|
|
44
|
+
EXIT_ALTERNATE_SCREEN_SEQUENCE + SAFE_TERMINAL_RESET_SEQUENCES
|
|
45
|
+
|
|
46
|
+
function resetTerminal(options = {}) {
|
|
47
|
+
const { exitAlternateScreen = false } = options
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
if (process.stdin.isTTY && process.stdin.setRawMode) {
|
|
51
|
+
process.stdin.setRawMode(false)
|
|
52
|
+
}
|
|
53
|
+
} catch {
|
|
54
|
+
// stdin may be closed
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
if (process.stdout.isTTY) {
|
|
58
|
+
// Exiting the alternate screen is only safe after an interactive child.
|
|
59
|
+
// Plain CLI paths like --help never enter it, and ?1049l can erase output.
|
|
60
|
+
process.stdout.write(
|
|
61
|
+
exitAlternateScreen
|
|
62
|
+
? FULL_TERMINAL_RESET_SEQUENCES
|
|
63
|
+
: SAFE_TERMINAL_RESET_SEQUENCES,
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
// stdout may be closed
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function getUnsignedExitCode(code) {
|
|
72
|
+
return code != null && code < 0 ? code >>> 0 : code
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isWindowsNativeCrashCode(code) {
|
|
76
|
+
const unsignedCode = getUnsignedExitCode(code)
|
|
77
|
+
return (
|
|
78
|
+
process.platform === 'win32' &&
|
|
79
|
+
(unsignedCode === 0xc000001d ||
|
|
80
|
+
unsignedCode === 0xc0000005 ||
|
|
81
|
+
unsignedCode === 0xc0000409)
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function shouldExitAlternateScreen(code, signal) {
|
|
86
|
+
return Boolean(signal) || isWindowsNativeCrashCode(code)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isIllegalInstructionExit(code, signal) {
|
|
90
|
+
const unsignedCode = getUnsignedExitCode(code)
|
|
91
|
+
return (
|
|
92
|
+
signal === 'SIGILL' ||
|
|
93
|
+
(process.platform === 'win32' && unsignedCode === 0xc000001d)
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function createConfig(packageName) {
|
|
98
|
+
const homeDir = os.homedir()
|
|
99
|
+
const configDir = path.join(homeDir, '.config', 'manicode')
|
|
100
|
+
const binaryName =
|
|
101
|
+
process.platform === 'win32' ? `${packageName}.exe` : packageName
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
homeDir,
|
|
105
|
+
configDir,
|
|
106
|
+
binaryName,
|
|
107
|
+
binaryPath: path.join(configDir, binaryName),
|
|
108
|
+
metadataPath: path.join(configDir, `${packageName}-metadata.json`),
|
|
109
|
+
tempDownloadDir: path.join(configDir, tempDownloadDirName),
|
|
110
|
+
userAgent: `${packageName}-cli`,
|
|
111
|
+
requestTimeout: 20000,
|
|
112
|
+
downloadRequestTimeout: 120000,
|
|
113
|
+
downloadMaxAttempts: 3,
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const CONFIG = createConfig(packageName)
|
|
118
|
+
const { downloadFile, httpGet, withRetries } = createReleaseHttpClient({
|
|
119
|
+
env: process.env,
|
|
120
|
+
userAgent: CONFIG.userAgent,
|
|
121
|
+
requestTimeout: CONFIG.requestTimeout,
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
function getPostHogConfig() {
|
|
125
|
+
const apiKey =
|
|
126
|
+
process.env.CODEBUFF_POSTHOG_API_KEY ||
|
|
127
|
+
process.env.NEXT_PUBLIC_POSTHOG_API_KEY
|
|
128
|
+
const host =
|
|
129
|
+
process.env.CODEBUFF_POSTHOG_HOST ||
|
|
130
|
+
process.env.NEXT_PUBLIC_POSTHOG_HOST_URL
|
|
131
|
+
|
|
132
|
+
if (!apiKey || !host) {
|
|
133
|
+
return null
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { apiKey, host }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Track update failure event to PostHog.
|
|
141
|
+
* Fire-and-forget - errors are silently ignored.
|
|
142
|
+
*/
|
|
143
|
+
function trackUpdateFailed(errorMessage, version, context = {}) {
|
|
144
|
+
try {
|
|
145
|
+
const posthogConfig = getPostHogConfig()
|
|
146
|
+
if (!posthogConfig) {
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const payload = JSON.stringify({
|
|
151
|
+
api_key: posthogConfig.apiKey,
|
|
152
|
+
event: telemetryEvent,
|
|
153
|
+
properties: {
|
|
154
|
+
distinct_id: `anonymous-${CONFIG.homeDir}`,
|
|
155
|
+
error: errorMessage,
|
|
156
|
+
version: version || 'unknown',
|
|
157
|
+
platform: process.platform,
|
|
158
|
+
arch: process.arch,
|
|
159
|
+
...telemetryProperties,
|
|
160
|
+
...context,
|
|
161
|
+
},
|
|
162
|
+
timestamp: new Date().toISOString(),
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
const parsedUrl = new URL(`${posthogConfig.host}/capture/`)
|
|
166
|
+
const isHttps = parsedUrl.protocol === 'https:'
|
|
167
|
+
const options = {
|
|
168
|
+
hostname: parsedUrl.hostname,
|
|
169
|
+
port: parsedUrl.port || (isHttps ? 443 : 80),
|
|
170
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
171
|
+
method: 'POST',
|
|
172
|
+
headers: {
|
|
173
|
+
'Content-Type': 'application/json',
|
|
174
|
+
'Content-Length': Buffer.byteLength(payload),
|
|
175
|
+
},
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const transport = isHttps ? https : http
|
|
179
|
+
const req = transport.request(options)
|
|
180
|
+
req.on('error', () => {}) // Silently ignore errors
|
|
181
|
+
req.write(payload)
|
|
182
|
+
req.end()
|
|
183
|
+
} catch (e) {
|
|
184
|
+
// Silently ignore any tracking errors
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const PLATFORM_TARGETS = {
|
|
189
|
+
'linux-x64': `${packageName}-linux-x64.tar.gz`,
|
|
190
|
+
'linux-x64-baseline': `${packageName}-linux-x64-baseline.tar.gz`,
|
|
191
|
+
'linux-arm64': `${packageName}-linux-arm64.tar.gz`,
|
|
192
|
+
'darwin-x64': `${packageName}-darwin-x64.tar.gz`,
|
|
193
|
+
'darwin-arm64': `${packageName}-darwin-arm64.tar.gz`,
|
|
194
|
+
'win32-x64': `${packageName}-win32-x64.tar.gz`,
|
|
195
|
+
'win32-x64-baseline': `${packageName}-win32-x64-baseline.tar.gz`,
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const BASELINE_FALLBACK_TARGETS = {
|
|
199
|
+
'linux-x64': 'linux-x64-baseline',
|
|
200
|
+
'win32-x64': 'win32-x64-baseline',
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const term = {
|
|
204
|
+
clearLine: () => {
|
|
205
|
+
if (process.stderr.isTTY) {
|
|
206
|
+
process.stderr.write('\r\x1b[K')
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
write: (text) => {
|
|
210
|
+
term.clearLine()
|
|
211
|
+
process.stderr.write(text)
|
|
212
|
+
},
|
|
213
|
+
writeLine: (text) => {
|
|
214
|
+
term.clearLine()
|
|
215
|
+
process.stderr.write(text + '\n')
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function getPlatformKey() {
|
|
220
|
+
return `${process.platform}-${process.arch}`
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function getTargetOverride() {
|
|
224
|
+
const envNames = [
|
|
225
|
+
`${packageName.toUpperCase()}_BINARY_TARGET`,
|
|
226
|
+
'CODEBUFF_BINARY_TARGET',
|
|
227
|
+
'CLI_BINARY_TARGET',
|
|
228
|
+
]
|
|
229
|
+
|
|
230
|
+
for (const envName of envNames) {
|
|
231
|
+
const target = process.env[envName]
|
|
232
|
+
if (target && PLATFORM_TARGETS[target]) {
|
|
233
|
+
return target
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
return null
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function linuxCpuHasAvx2() {
|
|
241
|
+
try {
|
|
242
|
+
return /\bavx2\b/i.test(fs.readFileSync('/proc/cpuinfo', 'utf8'))
|
|
243
|
+
} catch {
|
|
244
|
+
return true
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Returns true (AVX2 present), false (absent), or null (couldn't determine).
|
|
249
|
+
// Ask the OS directly via IsProcessorFeaturePresent (kernel32), which is
|
|
250
|
+
// backed by CPUID — far more reliable than matching CPU model names, and it
|
|
251
|
+
// works on the stock Windows PowerShell that ships with every supported
|
|
252
|
+
// Windows version. Feature 40 = PF_AVX2_INSTRUCTIONS_AVAILABLE.
|
|
253
|
+
function probeWindowsAvx2() {
|
|
254
|
+
const script =
|
|
255
|
+
'$f = Add-Type -MemberDefinition \'[DllImport("kernel32.dll")] ' +
|
|
256
|
+
"public static extern bool IsProcessorFeaturePresent(uint feature);' " +
|
|
257
|
+
'-Name Cpu -Namespace Win32 -PassThru; $f::IsProcessorFeaturePresent(40)'
|
|
258
|
+
try {
|
|
259
|
+
const out = execFileSync(
|
|
260
|
+
'powershell.exe',
|
|
261
|
+
['-NoProfile', '-NonInteractive', '-Command', script],
|
|
262
|
+
{
|
|
263
|
+
encoding: 'utf8',
|
|
264
|
+
timeout: 5000,
|
|
265
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
266
|
+
},
|
|
267
|
+
).trim()
|
|
268
|
+
if (out === 'True') return true
|
|
269
|
+
if (out === 'False') return false
|
|
270
|
+
return null
|
|
271
|
+
} catch {
|
|
272
|
+
// No PowerShell, locked-down policy, timeout, etc. — inconclusive.
|
|
273
|
+
return null
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
let _hasAvx2Cache
|
|
278
|
+
|
|
279
|
+
function machineHasAvx2() {
|
|
280
|
+
if (_hasAvx2Cache === undefined) {
|
|
281
|
+
_hasAvx2Cache = detectMachineHasAvx2()
|
|
282
|
+
}
|
|
283
|
+
return _hasAvx2Cache
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function detectMachineHasAvx2() {
|
|
287
|
+
if (process.arch !== 'x64') {
|
|
288
|
+
return true
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Linux detection is a cheap file read, so we don't bother persisting it.
|
|
292
|
+
if (process.platform === 'linux') {
|
|
293
|
+
return linuxCpuHasAvx2()
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (process.platform !== 'win32') {
|
|
297
|
+
return true
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Windows detection shells out to PowerShell. getDefaultTargetKey runs on
|
|
301
|
+
// every launch (via the version check), so cache the result on disk to keep
|
|
302
|
+
// startup fast after the first probe.
|
|
303
|
+
const cached = readCachedAvx2()
|
|
304
|
+
if (cached !== null) {
|
|
305
|
+
return cached
|
|
306
|
+
}
|
|
307
|
+
const detected = probeWindowsAvx2()
|
|
308
|
+
if (detected === null) {
|
|
309
|
+
// Inconclusive probe: assume AVX2 for this launch and rely on the SIGILL
|
|
310
|
+
// fallback, but don't persist it — a transient failure must not lock in a
|
|
311
|
+
// wrong answer for the lifetime of the install. We'll re-probe next launch.
|
|
312
|
+
return true
|
|
313
|
+
}
|
|
314
|
+
writeCachedAvx2(detected)
|
|
315
|
+
return detected
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function getCpuFeatureCachePath() {
|
|
319
|
+
return path.join(CONFIG.configDir, 'cpu-features.json')
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function readCachedAvx2() {
|
|
323
|
+
try {
|
|
324
|
+
const cache = JSON.parse(
|
|
325
|
+
fs.readFileSync(getCpuFeatureCachePath(), 'utf8'),
|
|
326
|
+
)
|
|
327
|
+
return typeof cache.avx2 === 'boolean' ? cache.avx2 : null
|
|
328
|
+
} catch {
|
|
329
|
+
return null
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function writeCachedAvx2(value) {
|
|
334
|
+
try {
|
|
335
|
+
fs.mkdirSync(CONFIG.configDir, { recursive: true })
|
|
336
|
+
fs.writeFileSync(
|
|
337
|
+
getCpuFeatureCachePath(),
|
|
338
|
+
JSON.stringify({ avx2: value }),
|
|
339
|
+
)
|
|
340
|
+
} catch {
|
|
341
|
+
// Best effort; we'll just re-probe next launch.
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function getDefaultTargetKey() {
|
|
346
|
+
const override = getTargetOverride()
|
|
347
|
+
if (override) {
|
|
348
|
+
return override
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const platformKey = getPlatformKey()
|
|
352
|
+
// Select the binary up front from explicit CPU feature detection rather than
|
|
353
|
+
// optimistically launching the AVX2 build and waiting for it to crash with
|
|
354
|
+
// an illegal instruction. The crash isn't always a clean immediate failure —
|
|
355
|
+
// it can surface later from a deeper code path — so older CPUs (e.g. an
|
|
356
|
+
// Intel Xeon with AVX but no AVX2) are safer on baseline from the start.
|
|
357
|
+
//
|
|
358
|
+
// This assumes every baseline target is gated on AVX2 specifically, which
|
|
359
|
+
// holds today (only linux-x64 and win32-x64 have baseline builds, both
|
|
360
|
+
// AVX2-gated). If a baseline build is ever added for a different reason, give
|
|
361
|
+
// BASELINE_FALLBACK_TARGETS a per-target capability and check that instead.
|
|
362
|
+
if (BASELINE_FALLBACK_TARGETS[platformKey] && !machineHasAvx2()) {
|
|
363
|
+
return BASELINE_FALLBACK_TARGETS[platformKey]
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return platformKey
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function getBaselineFallbackTargetKey() {
|
|
370
|
+
// Runtime safety net: if proactive detection was unavailable or wrong and the
|
|
371
|
+
// optimized binary still dies with SIGILL, fall back to baseline.
|
|
372
|
+
return BASELINE_FALLBACK_TARGETS[getPlatformKey()] || null
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function isTargetAllowedForThisMachine(target) {
|
|
376
|
+
const override = getTargetOverride()
|
|
377
|
+
if (override) {
|
|
378
|
+
return target === override
|
|
379
|
+
}
|
|
380
|
+
// Check the baseline fallback first: it's always safe on its platform and
|
|
381
|
+
// avoids running CPU detection when a baseline binary is already installed.
|
|
382
|
+
return (
|
|
383
|
+
target === getBaselineFallbackTargetKey() ||
|
|
384
|
+
target === getDefaultTargetKey()
|
|
385
|
+
)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function getDownloadTargetKey() {
|
|
389
|
+
const override = getTargetOverride()
|
|
390
|
+
if (override) {
|
|
391
|
+
return override
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const metadata = getCurrentMetadata()
|
|
395
|
+
if (metadata?.target && isTargetAllowedForThisMachine(metadata.target)) {
|
|
396
|
+
return metadata.target
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return getDefaultTargetKey()
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async function getLatestVersion() {
|
|
403
|
+
try {
|
|
404
|
+
const res = await httpGet(
|
|
405
|
+
`https://registry.npmjs.org/${packageName}/latest`,
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
if (res.statusCode !== 200) return null
|
|
409
|
+
|
|
410
|
+
const body = await streamToString(res)
|
|
411
|
+
const packageData = JSON.parse(body)
|
|
412
|
+
|
|
413
|
+
return packageData.version || null
|
|
414
|
+
} catch (error) {
|
|
415
|
+
return null
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function streamToString(stream) {
|
|
420
|
+
return new Promise((resolve, reject) => {
|
|
421
|
+
let data = ''
|
|
422
|
+
stream.on('data', (chunk) => (data += chunk))
|
|
423
|
+
stream.on('end', () => resolve(data))
|
|
424
|
+
stream.on('error', reject)
|
|
425
|
+
})
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function getCurrentVersion() {
|
|
429
|
+
try {
|
|
430
|
+
const metadata = getCurrentMetadata()
|
|
431
|
+
if (!metadata) {
|
|
432
|
+
return null
|
|
433
|
+
}
|
|
434
|
+
// Also verify the binary still exists
|
|
435
|
+
if (!fs.existsSync(CONFIG.binaryPath)) {
|
|
436
|
+
return null
|
|
437
|
+
}
|
|
438
|
+
const metadataTarget = metadata.target || getPlatformKey()
|
|
439
|
+
if (!isTargetAllowedForThisMachine(metadataTarget)) {
|
|
440
|
+
return null
|
|
441
|
+
}
|
|
442
|
+
return metadata.version || null
|
|
443
|
+
} catch (error) {
|
|
444
|
+
return null
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function getCurrentMetadata() {
|
|
449
|
+
try {
|
|
450
|
+
if (!fs.existsSync(CONFIG.metadataPath)) {
|
|
451
|
+
return null
|
|
452
|
+
}
|
|
453
|
+
return JSON.parse(fs.readFileSync(CONFIG.metadataPath, 'utf8'))
|
|
454
|
+
} catch {
|
|
455
|
+
return null
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function compareVersions(v1, v2) {
|
|
460
|
+
if (!v1 || !v2) return 0
|
|
461
|
+
|
|
462
|
+
// Always update if the current version is not a valid semver
|
|
463
|
+
// e.g. 1.0.420-beta.1
|
|
464
|
+
if (!v1.match(/^\d+(\.\d+)*$/)) {
|
|
465
|
+
return -1
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const parseVersion = (version) => {
|
|
469
|
+
const parts = version.split('-')
|
|
470
|
+
const mainParts = parts[0].split('.').map(Number)
|
|
471
|
+
const prereleaseParts = parts[1] ? parts[1].split('.') : []
|
|
472
|
+
return { main: mainParts, prerelease: prereleaseParts }
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const p1 = parseVersion(v1)
|
|
476
|
+
const p2 = parseVersion(v2)
|
|
477
|
+
|
|
478
|
+
for (let i = 0; i < Math.max(p1.main.length, p2.main.length); i++) {
|
|
479
|
+
const n1 = p1.main[i] || 0
|
|
480
|
+
const n2 = p2.main[i] || 0
|
|
481
|
+
|
|
482
|
+
if (n1 < n2) return -1
|
|
483
|
+
if (n1 > n2) return 1
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
if (p1.prerelease.length === 0 && p2.prerelease.length === 0) {
|
|
487
|
+
return 0
|
|
488
|
+
} else if (p1.prerelease.length === 0) {
|
|
489
|
+
return 1
|
|
490
|
+
} else if (p2.prerelease.length === 0) {
|
|
491
|
+
return -1
|
|
492
|
+
} else {
|
|
493
|
+
for (
|
|
494
|
+
let i = 0;
|
|
495
|
+
i < Math.max(p1.prerelease.length, p2.prerelease.length);
|
|
496
|
+
i++
|
|
497
|
+
) {
|
|
498
|
+
const pr1 = p1.prerelease[i] || ''
|
|
499
|
+
const pr2 = p2.prerelease[i] || ''
|
|
500
|
+
|
|
501
|
+
const isNum1 = !isNaN(parseInt(pr1))
|
|
502
|
+
const isNum2 = !isNaN(parseInt(pr2))
|
|
503
|
+
|
|
504
|
+
if (isNum1 && isNum2) {
|
|
505
|
+
const num1 = parseInt(pr1)
|
|
506
|
+
const num2 = parseInt(pr2)
|
|
507
|
+
if (num1 < num2) return -1
|
|
508
|
+
if (num1 > num2) return 1
|
|
509
|
+
} else if (isNum1 && !isNum2) {
|
|
510
|
+
return 1
|
|
511
|
+
} else if (!isNum1 && isNum2) {
|
|
512
|
+
return -1
|
|
513
|
+
} else if (pr1 < pr2) {
|
|
514
|
+
return -1
|
|
515
|
+
} else if (pr1 > pr2) {
|
|
516
|
+
return 1
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return 0
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function formatBytes(bytes) {
|
|
524
|
+
if (bytes === 0) return '0 B'
|
|
525
|
+
const k = 1024
|
|
526
|
+
const sizes = ['B', 'KB', 'MB', 'GB']
|
|
527
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
|
528
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function createProgressBar(percentage, width = 30) {
|
|
532
|
+
const filled = Math.round((width * percentage) / 100)
|
|
533
|
+
const empty = width - filled
|
|
534
|
+
return '[' + '█'.repeat(filled) + '░'.repeat(empty) + ']'
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function isRetryableDownloadError(error) {
|
|
538
|
+
if (error && typeof error.retryable === 'boolean') return error.retryable
|
|
539
|
+
return !['EACCES', 'ENOSPC', 'EPERM', 'EROFS'].includes(error?.code)
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function getPartialArchivePath(version, targetKey) {
|
|
543
|
+
return path.join(
|
|
544
|
+
CONFIG.configDir,
|
|
545
|
+
`.${packageName}-${version}-${targetKey}.tar.gz.part`,
|
|
546
|
+
)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function getFileSize(filePath) {
|
|
550
|
+
try {
|
|
551
|
+
return fs.statSync(filePath).size
|
|
552
|
+
} catch (error) {
|
|
553
|
+
if (error.code === 'ENOENT') return 0
|
|
554
|
+
throw error
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function removeFileIfPresent(filePath) {
|
|
559
|
+
try {
|
|
560
|
+
fs.unlinkSync(filePath)
|
|
561
|
+
} catch (error) {
|
|
562
|
+
if (error.code !== 'ENOENT') throw error
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function formatDownloadSource(downloadUrl) {
|
|
567
|
+
try {
|
|
568
|
+
const parsedUrl = new URL(downloadUrl)
|
|
569
|
+
return `${parsedUrl.origin}${parsedUrl.pathname}`
|
|
570
|
+
} catch {
|
|
571
|
+
return downloadUrl
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function printDownloadFailure(error) {
|
|
576
|
+
const code = error.code ? ` (${error.code})` : ''
|
|
577
|
+
console.error(
|
|
578
|
+
`❌ Failed to download ${packageName}: ${error.message}${code}`,
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
if (error.requestUrl) {
|
|
582
|
+
console.error(
|
|
583
|
+
`Download source: ${formatDownloadSource(error.requestUrl)}`,
|
|
584
|
+
)
|
|
585
|
+
}
|
|
586
|
+
if (error.downloadedBytes > 0) {
|
|
587
|
+
const total = error.totalBytes
|
|
588
|
+
? ` of ${formatBytes(error.totalBytes)}`
|
|
589
|
+
: ''
|
|
590
|
+
console.error(
|
|
591
|
+
`Saved ${formatBytes(error.downloadedBytes)}${total}; the next run will resume this download.`,
|
|
592
|
+
)
|
|
593
|
+
} else if (error.requestUrl) {
|
|
594
|
+
console.error(
|
|
595
|
+
'Please retry. The release host may be temporarily unavailable.',
|
|
596
|
+
)
|
|
597
|
+
} else {
|
|
598
|
+
console.error(
|
|
599
|
+
'The downloaded update could not be installed; the existing binary was preserved when possible.',
|
|
600
|
+
)
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function prepareTempDownloadDir() {
|
|
605
|
+
if (fs.existsSync(CONFIG.tempDownloadDir)) {
|
|
606
|
+
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
|
|
607
|
+
}
|
|
608
|
+
fs.mkdirSync(CONFIG.tempDownloadDir, { recursive: true })
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async function downloadAndExtract(
|
|
612
|
+
downloadUrl,
|
|
613
|
+
version,
|
|
614
|
+
targetKey,
|
|
615
|
+
{ quiet = false } = {},
|
|
616
|
+
) {
|
|
617
|
+
let attempts = 0
|
|
618
|
+
const partialArchivePath = getPartialArchivePath(version, targetKey)
|
|
619
|
+
let totalBytes = null
|
|
620
|
+
|
|
621
|
+
try {
|
|
622
|
+
return await withRetries(
|
|
623
|
+
async (attempt) => {
|
|
624
|
+
attempts = attempt
|
|
625
|
+
prepareTempDownloadDir()
|
|
626
|
+
if (!quiet) term.write('Downloading...')
|
|
627
|
+
|
|
628
|
+
let lastProgressTime = Date.now()
|
|
629
|
+
const result = await downloadFile(downloadUrl, partialArchivePath, {
|
|
630
|
+
timeout: CONFIG.downloadRequestTimeout,
|
|
631
|
+
onProgress: ({ downloadedBytes, totalBytes: progressTotal }) => {
|
|
632
|
+
totalBytes = progressTotal
|
|
633
|
+
if (quiet) return
|
|
634
|
+
const now = Date.now()
|
|
635
|
+
if (
|
|
636
|
+
now - lastProgressTime < 100 &&
|
|
637
|
+
downloadedBytes !== progressTotal
|
|
638
|
+
) {
|
|
639
|
+
return
|
|
640
|
+
}
|
|
641
|
+
lastProgressTime = now
|
|
642
|
+
if (progressTotal) {
|
|
643
|
+
const pct = Math.round((downloadedBytes / progressTotal) * 100)
|
|
644
|
+
term.write(
|
|
645
|
+
`Downloading... ${createProgressBar(pct)} ${pct}% of ${formatBytes(progressTotal)}`,
|
|
646
|
+
)
|
|
647
|
+
} else {
|
|
648
|
+
term.write(`Downloading... ${formatBytes(downloadedBytes)}`)
|
|
649
|
+
}
|
|
650
|
+
},
|
|
651
|
+
})
|
|
652
|
+
totalBytes = result.totalBytes
|
|
653
|
+
|
|
654
|
+
try {
|
|
655
|
+
await pipeline(
|
|
656
|
+
fs.createReadStream(partialArchivePath),
|
|
657
|
+
zlib.createGunzip(),
|
|
658
|
+
tar.x({ cwd: CONFIG.tempDownloadDir }),
|
|
659
|
+
)
|
|
660
|
+
} catch (error) {
|
|
661
|
+
// A complete archive that cannot be extracted is corrupt. Do not
|
|
662
|
+
// resume it on the next attempt.
|
|
663
|
+
removeFileIfPresent(partialArchivePath)
|
|
664
|
+
throw error
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const tempBinaryPath = path.join(
|
|
668
|
+
CONFIG.tempDownloadDir,
|
|
669
|
+
CONFIG.binaryName,
|
|
670
|
+
)
|
|
671
|
+
if (!fs.existsSync(tempBinaryPath)) {
|
|
672
|
+
const files = fs.readdirSync(CONFIG.tempDownloadDir)
|
|
673
|
+
removeFileIfPresent(partialArchivePath)
|
|
674
|
+
const error = new Error(
|
|
675
|
+
`Binary not found after extraction. Expected: ${CONFIG.binaryName}, Available files: ${files.join(', ')}`,
|
|
676
|
+
)
|
|
677
|
+
error.retryable = false
|
|
678
|
+
throw error
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
removeFileIfPresent(partialArchivePath)
|
|
682
|
+
return tempBinaryPath
|
|
683
|
+
},
|
|
684
|
+
{
|
|
685
|
+
maxAttempts: CONFIG.downloadMaxAttempts,
|
|
686
|
+
shouldRetry: isRetryableDownloadError,
|
|
687
|
+
onRetry: ({ nextAttempt, delayMs }) => {
|
|
688
|
+
if (quiet) return
|
|
689
|
+
term.writeLine(
|
|
690
|
+
`Download interrupted. Retrying in ${delayMs / 1000}s (${nextAttempt}/${CONFIG.downloadMaxAttempts})...`,
|
|
691
|
+
)
|
|
692
|
+
},
|
|
693
|
+
},
|
|
694
|
+
)
|
|
695
|
+
} catch (error) {
|
|
696
|
+
try {
|
|
697
|
+
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true, force: true })
|
|
698
|
+
} catch {
|
|
699
|
+
// Best effort after a failed download.
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
trackUpdateFailed(error.message, version, {
|
|
703
|
+
stage: 'download',
|
|
704
|
+
errorCode: error.code,
|
|
705
|
+
statusCode: error.statusCode,
|
|
706
|
+
target: targetKey,
|
|
707
|
+
attempts,
|
|
708
|
+
bytesDownloaded: getFileSize(partialArchivePath),
|
|
709
|
+
totalBytes: error.totalBytes || totalBytes,
|
|
710
|
+
})
|
|
711
|
+
error.downloadedBytes = getFileSize(partialArchivePath)
|
|
712
|
+
error.totalBytes ||= totalBytes
|
|
713
|
+
error.requestUrl ||= downloadUrl
|
|
714
|
+
throw error
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
async function stageBinary(
|
|
719
|
+
version,
|
|
720
|
+
targetKey = getDownloadTargetKey(),
|
|
721
|
+
options = {},
|
|
722
|
+
) {
|
|
723
|
+
const fileName = PLATFORM_TARGETS[targetKey]
|
|
724
|
+
|
|
725
|
+
if (!fileName) {
|
|
726
|
+
const error = new Error(
|
|
727
|
+
`Unsupported platform: ${process.platform} ${process.arch}`,
|
|
728
|
+
)
|
|
729
|
+
trackUpdateFailed(error.message, version, {
|
|
730
|
+
stage: 'platform_check',
|
|
731
|
+
target: targetKey,
|
|
732
|
+
})
|
|
733
|
+
throw error
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const downloadUrl = `${
|
|
737
|
+
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL || 'https://codebuff.com'
|
|
738
|
+
}/api/releases/download/${version}/${fileName}`
|
|
739
|
+
|
|
740
|
+
fs.mkdirSync(CONFIG.configDir, { recursive: true })
|
|
741
|
+
const tempBinaryPath = await downloadAndExtract(
|
|
742
|
+
downloadUrl,
|
|
743
|
+
version,
|
|
744
|
+
targetKey,
|
|
745
|
+
options,
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
try {
|
|
749
|
+
if (process.platform !== 'win32') {
|
|
750
|
+
fs.chmodSync(tempBinaryPath, 0o755)
|
|
751
|
+
}
|
|
752
|
+
} catch (error) {
|
|
753
|
+
try {
|
|
754
|
+
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true, force: true })
|
|
755
|
+
} catch {
|
|
756
|
+
// Preserve the original chmod error.
|
|
757
|
+
}
|
|
758
|
+
throw error
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
return { tempBinaryPath, version, targetKey }
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function replaceFileWithRollback(sourcePath, targetPath, replacements) {
|
|
765
|
+
const backupPath = fs.existsSync(targetPath)
|
|
766
|
+
? `${targetPath}.old.${Date.now()}.${replacements.length}`
|
|
767
|
+
: null
|
|
768
|
+
|
|
769
|
+
if (backupPath) {
|
|
770
|
+
fs.renameSync(targetPath, backupPath)
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
try {
|
|
774
|
+
fs.renameSync(sourcePath, targetPath)
|
|
775
|
+
} catch (error) {
|
|
776
|
+
if (backupPath && fs.existsSync(backupPath)) {
|
|
777
|
+
fs.renameSync(backupPath, targetPath)
|
|
778
|
+
}
|
|
779
|
+
throw error
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
replacements.push({ backupPath, targetPath })
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
function rollbackReplacements(replacements) {
|
|
786
|
+
for (const { backupPath, targetPath } of replacements.reverse()) {
|
|
787
|
+
removeFileIfPresent(targetPath)
|
|
788
|
+
if (backupPath && fs.existsSync(backupPath)) {
|
|
789
|
+
fs.renameSync(backupPath, targetPath)
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function commitReplacements(replacements) {
|
|
795
|
+
for (const { backupPath } of replacements) {
|
|
796
|
+
if (!backupPath) continue
|
|
797
|
+
try {
|
|
798
|
+
removeFileIfPresent(backupPath)
|
|
799
|
+
} catch {
|
|
800
|
+
// The replacement is already committed. A stale backup is safer than
|
|
801
|
+
// rolling back a working install because cleanup failed.
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
function installStagedBinary({ tempBinaryPath, version, targetKey }) {
|
|
807
|
+
const replacements = []
|
|
808
|
+
const metadataTempPath = `${CONFIG.metadataPath}.new.${process.pid}`
|
|
809
|
+
|
|
810
|
+
try {
|
|
811
|
+
fs.writeFileSync(
|
|
812
|
+
metadataTempPath,
|
|
813
|
+
JSON.stringify({ version, target: targetKey }, null, 2),
|
|
814
|
+
)
|
|
815
|
+
replaceFileWithRollback(tempBinaryPath, CONFIG.binaryPath, replacements)
|
|
816
|
+
|
|
817
|
+
// Move tree-sitter.wasm next to the binary if the tarball included
|
|
818
|
+
// it. The CLI binary loads this at startup; embedding it inside the
|
|
819
|
+
// binary itself was unreliable on Windows (bun --compile asset
|
|
820
|
+
// bundling silently dropped or unbound it across several attempts),
|
|
821
|
+
// so we ship it as a sibling file instead. Older artifacts that
|
|
822
|
+
// pre-date this change won't have the wasm and will still install —
|
|
823
|
+
// they'll just hit the same crash they had before, which is fine.
|
|
824
|
+
if (includeTreeSitterWasm) {
|
|
825
|
+
const tempWasmPath = path.join(
|
|
826
|
+
CONFIG.tempDownloadDir,
|
|
827
|
+
'tree-sitter.wasm',
|
|
828
|
+
)
|
|
829
|
+
if (fs.existsSync(tempWasmPath)) {
|
|
830
|
+
const targetWasmPath = path.join(
|
|
831
|
+
path.dirname(CONFIG.binaryPath),
|
|
832
|
+
'tree-sitter.wasm',
|
|
833
|
+
)
|
|
834
|
+
replaceFileWithRollback(tempWasmPath, targetWasmPath, replacements)
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
replaceFileWithRollback(
|
|
839
|
+
metadataTempPath,
|
|
840
|
+
CONFIG.metadataPath,
|
|
841
|
+
replacements,
|
|
842
|
+
)
|
|
843
|
+
commitReplacements(replacements)
|
|
844
|
+
} catch (error) {
|
|
845
|
+
rollbackReplacements(replacements)
|
|
846
|
+
throw error
|
|
847
|
+
} finally {
|
|
848
|
+
removeFileIfPresent(metadataTempPath)
|
|
849
|
+
if (fs.existsSync(CONFIG.tempDownloadDir)) {
|
|
850
|
+
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
term.clearLine()
|
|
855
|
+
console.log(`Download complete! Starting ${displayName}...`)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async function downloadBinary(version, targetKey = getDownloadTargetKey()) {
|
|
859
|
+
const stagedBinary = await stageBinary(version, targetKey)
|
|
860
|
+
installStagedBinary(stagedBinary)
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
async function ensureBinaryExists() {
|
|
864
|
+
const currentVersion = getCurrentVersion()
|
|
865
|
+
if (currentVersion !== null) {
|
|
866
|
+
return
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
const version = await getLatestVersion()
|
|
870
|
+
if (!version) {
|
|
871
|
+
console.error('❌ Failed to determine latest version')
|
|
872
|
+
console.error('Please check your internet connection and try again')
|
|
873
|
+
process.exit(1)
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
try {
|
|
877
|
+
await downloadBinary(version)
|
|
878
|
+
} catch (error) {
|
|
879
|
+
term.clearLine()
|
|
880
|
+
printDownloadFailure(error)
|
|
881
|
+
process.exit(1)
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function stopRunningProcess(runningProcess) {
|
|
886
|
+
return new Promise((resolve, reject) => {
|
|
887
|
+
let forceKillTimer
|
|
888
|
+
let forceKillTimeout
|
|
889
|
+
|
|
890
|
+
const cleanup = () => {
|
|
891
|
+
clearTimeout(forceKillTimer)
|
|
892
|
+
clearTimeout(forceKillTimeout)
|
|
893
|
+
runningProcess.removeListener('exit', handleExit)
|
|
894
|
+
}
|
|
895
|
+
const handleExit = () => {
|
|
896
|
+
cleanup()
|
|
897
|
+
resolve()
|
|
898
|
+
}
|
|
899
|
+
const fail = (error) => {
|
|
900
|
+
cleanup()
|
|
901
|
+
reject(error)
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
runningProcess.once('exit', handleExit)
|
|
905
|
+
forceKillTimer = setTimeout(() => {
|
|
906
|
+
forceKillTimeout = setTimeout(() => {
|
|
907
|
+
fail(new Error(`${packageName} did not exit after SIGKILL`))
|
|
908
|
+
}, 1000)
|
|
909
|
+
try {
|
|
910
|
+
runningProcess.kill('SIGKILL')
|
|
911
|
+
} catch (error) {
|
|
912
|
+
fail(error)
|
|
913
|
+
}
|
|
914
|
+
}, 5000)
|
|
915
|
+
try {
|
|
916
|
+
runningProcess.kill('SIGTERM')
|
|
917
|
+
} catch (error) {
|
|
918
|
+
fail(error)
|
|
919
|
+
}
|
|
920
|
+
})
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
async function checkForUpdates(runningProcess, exitListener) {
|
|
924
|
+
let stoppedForUpdate = false
|
|
925
|
+
|
|
926
|
+
try {
|
|
927
|
+
const currentVersion = getCurrentVersion()
|
|
928
|
+
|
|
929
|
+
const latestVersion = await getLatestVersion()
|
|
930
|
+
if (!latestVersion) return
|
|
931
|
+
|
|
932
|
+
if (
|
|
933
|
+
// Download new version if current version is unknown or outdated.
|
|
934
|
+
currentVersion === null ||
|
|
935
|
+
compareVersions(currentVersion, latestVersion) < 0
|
|
936
|
+
) {
|
|
937
|
+
const stagedBinary = await stageBinary(
|
|
938
|
+
latestVersion,
|
|
939
|
+
getDownloadTargetKey(),
|
|
940
|
+
{ quiet: true },
|
|
941
|
+
)
|
|
942
|
+
|
|
943
|
+
term.clearLine()
|
|
944
|
+
|
|
945
|
+
runningProcess.removeListener('exit', exitListener)
|
|
946
|
+
try {
|
|
947
|
+
await stopRunningProcess(runningProcess)
|
|
948
|
+
} catch (error) {
|
|
949
|
+
runningProcess.on('exit', exitListener)
|
|
950
|
+
throw error
|
|
951
|
+
}
|
|
952
|
+
stoppedForUpdate = true
|
|
953
|
+
|
|
954
|
+
resetTerminal({ exitAlternateScreen: true })
|
|
955
|
+
console.log(`Update available: ${currentVersion} → ${latestVersion}`)
|
|
956
|
+
|
|
957
|
+
installStagedBinary(stagedBinary)
|
|
958
|
+
|
|
959
|
+
const newChild = spawnInstalledBinary({ detached: false })
|
|
960
|
+
attachExitHandler(newChild)
|
|
961
|
+
|
|
962
|
+
return new Promise(() => {})
|
|
963
|
+
}
|
|
964
|
+
} catch (error) {
|
|
965
|
+
if (stoppedForUpdate && fs.existsSync(CONFIG.binaryPath)) {
|
|
966
|
+
console.error(
|
|
967
|
+
`Update failed; restarting ${packageName} ${getCurrentVersion()}.`,
|
|
968
|
+
)
|
|
969
|
+
const child = spawnInstalledBinary({ detached: false })
|
|
970
|
+
attachExitHandler(child)
|
|
971
|
+
return new Promise(() => {})
|
|
972
|
+
}
|
|
973
|
+
try {
|
|
974
|
+
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true, force: true })
|
|
975
|
+
} catch {
|
|
976
|
+
// Best effort after a failed background update.
|
|
977
|
+
}
|
|
978
|
+
// A staging failure leaves the current process and binary untouched.
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
function printCrashDiagnostics(code, signal) {
|
|
983
|
+
// Windows NTSTATUS codes (unsigned DWORD)
|
|
984
|
+
const unsignedCode = getUnsignedExitCode(code)
|
|
985
|
+
const isIllegalInstruction = isIllegalInstructionExit(code, signal)
|
|
986
|
+
const isAccessViolation =
|
|
987
|
+
signal === 'SIGSEGV' ||
|
|
988
|
+
(process.platform === 'win32' && unsignedCode === 0xc0000005)
|
|
989
|
+
const isBusError = signal === 'SIGBUS'
|
|
990
|
+
const isAbort =
|
|
991
|
+
signal === 'SIGABRT' ||
|
|
992
|
+
(process.platform === 'win32' && unsignedCode === 0xc0000409)
|
|
993
|
+
|
|
994
|
+
if (!isIllegalInstruction && !isAccessViolation && !isBusError && !isAbort)
|
|
995
|
+
return
|
|
996
|
+
|
|
997
|
+
const exitInfo = signal ? `signal ${signal}` : `code ${code}`
|
|
998
|
+
console.error('')
|
|
999
|
+
console.error(`❌ ${packageName} exited immediately (${exitInfo})`)
|
|
1000
|
+
console.error('')
|
|
1001
|
+
|
|
1002
|
+
if (isIllegalInstruction) {
|
|
1003
|
+
console.error(
|
|
1004
|
+
'Your CPU may not support the required instruction set (AVX2).',
|
|
1005
|
+
)
|
|
1006
|
+
console.error('This typically affects CPUs from before 2013.')
|
|
1007
|
+
console.error('')
|
|
1008
|
+
printBaselineOverrideHint()
|
|
1009
|
+
} else if (isAccessViolation) {
|
|
1010
|
+
console.error('The binary crashed with an access violation.')
|
|
1011
|
+
console.error('')
|
|
1012
|
+
} else if (isBusError) {
|
|
1013
|
+
console.error('The binary crashed with a bus error.')
|
|
1014
|
+
console.error('This may indicate a platform compatibility issue.')
|
|
1015
|
+
console.error('')
|
|
1016
|
+
} else if (isAbort) {
|
|
1017
|
+
console.error('The binary crashed with an abort signal.')
|
|
1018
|
+
console.error('')
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
printSystemInfo()
|
|
1022
|
+
console.error('')
|
|
1023
|
+
console.error('Please report this issue at:')
|
|
1024
|
+
console.error(' https://github.com/CodebuffAI/codebuff/issues')
|
|
1025
|
+
console.error('')
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function printBaselineOverrideHint() {
|
|
1029
|
+
const fallbackTarget = getBaselineFallbackTargetKey()
|
|
1030
|
+
if (!fallbackTarget) return
|
|
1031
|
+
console.error('To force the baseline (non-AVX2) build, set:')
|
|
1032
|
+
console.error(
|
|
1033
|
+
` ${packageName.toUpperCase()}_BINARY_TARGET=${fallbackTarget}`,
|
|
1034
|
+
)
|
|
1035
|
+
console.error('')
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
function printSystemInfo() {
|
|
1039
|
+
const metadata = getCurrentMetadata()
|
|
1040
|
+
console.error('System info:')
|
|
1041
|
+
console.error(` Platform: ${process.platform} ${process.arch}`)
|
|
1042
|
+
console.error(` Node: ${process.version}`)
|
|
1043
|
+
if (process.arch === 'x64') {
|
|
1044
|
+
console.error(` AVX2: ${machineHasAvx2() ? 'yes' : 'no'}`)
|
|
1045
|
+
}
|
|
1046
|
+
console.error(` Target: ${metadata?.target || getDefaultTargetKey()}`)
|
|
1047
|
+
console.error(` Binary: ${CONFIG.binaryPath}`)
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
function getInstalledBinaryStatus() {
|
|
1051
|
+
try {
|
|
1052
|
+
const stats = fs.statSync(CONFIG.binaryPath)
|
|
1053
|
+
return stats.isFile() ? `yes (${formatBytes(stats.size)})` : 'no'
|
|
1054
|
+
} catch {
|
|
1055
|
+
return 'no'
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
function printSpawnFailure(err) {
|
|
1060
|
+
resetTerminal()
|
|
1061
|
+
const code = err && err.code ? ` (${err.code})` : ''
|
|
1062
|
+
|
|
1063
|
+
console.error(`Failed to start ${packageName}: ${err.message}${code}`)
|
|
1064
|
+
console.error('')
|
|
1065
|
+
printSystemInfo()
|
|
1066
|
+
console.error(` Exists: ${getInstalledBinaryStatus()}`)
|
|
1067
|
+
|
|
1068
|
+
if (process.platform === 'win32') {
|
|
1069
|
+
console.error('')
|
|
1070
|
+
console.error(
|
|
1071
|
+
'On Windows, this can happen when Windows Security or antivirus blocks',
|
|
1072
|
+
)
|
|
1073
|
+
console.error(
|
|
1074
|
+
'or quarantines the downloaded executable, or when the binary requires',
|
|
1075
|
+
)
|
|
1076
|
+
console.error('CPU instructions that are not available on this machine.')
|
|
1077
|
+
console.error('')
|
|
1078
|
+
printBaselineOverrideHint()
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
console.error('')
|
|
1082
|
+
console.error('Try deleting the downloaded files and running again:')
|
|
1083
|
+
console.error(` ${CONFIG.configDir}`)
|
|
1084
|
+
console.error('')
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
function exitOnSpawnFailure(err) {
|
|
1088
|
+
printSpawnFailure(err)
|
|
1089
|
+
process.exit(1)
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
function spawnInstalledBinary(options = {}) {
|
|
1093
|
+
if (!fs.existsSync(CONFIG.binaryPath)) {
|
|
1094
|
+
try {
|
|
1095
|
+
if (fs.existsSync(CONFIG.metadataPath))
|
|
1096
|
+
fs.unlinkSync(CONFIG.metadataPath)
|
|
1097
|
+
} catch {
|
|
1098
|
+
// best effort
|
|
1099
|
+
}
|
|
1100
|
+
const error = new Error(
|
|
1101
|
+
`downloaded binary is missing at ${CONFIG.binaryPath}`,
|
|
1102
|
+
)
|
|
1103
|
+
error.code = 'BINARY_MISSING'
|
|
1104
|
+
exitOnSpawnFailure(error)
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// spawn() only emits 'error' asynchronously for a few errno values
|
|
1108
|
+
// (EACCES, EAGAIN, EMFILE, ENFILE, ENOENT); everything else — notably
|
|
1109
|
+
// UNKNOWN on Windows when antivirus or Smart App Control blocks the
|
|
1110
|
+
// exe or the download is corrupt — is thrown synchronously.
|
|
1111
|
+
let child
|
|
1112
|
+
try {
|
|
1113
|
+
const { env: optionEnv, ...spawnOptions } = options
|
|
1114
|
+
child = spawn(CONFIG.binaryPath, process.argv.slice(2), {
|
|
1115
|
+
stdio: 'inherit',
|
|
1116
|
+
...spawnOptions,
|
|
1117
|
+
env: {
|
|
1118
|
+
...process.env,
|
|
1119
|
+
...optionEnv,
|
|
1120
|
+
CODEBUFF_LAUNCHER_PID: String(process.pid),
|
|
1121
|
+
},
|
|
1122
|
+
})
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
exitOnSpawnFailure(err)
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
child.on('error', exitOnSpawnFailure)
|
|
1128
|
+
|
|
1129
|
+
return child
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
async function tryFallbackToBaseline(code, signal) {
|
|
1133
|
+
if (!isIllegalInstructionExit(code, signal)) {
|
|
1134
|
+
return false
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
const fallbackTarget = getBaselineFallbackTargetKey()
|
|
1138
|
+
if (!fallbackTarget) {
|
|
1139
|
+
return false
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
const metadata = getCurrentMetadata()
|
|
1143
|
+
const currentTarget = metadata?.target || getDefaultTargetKey()
|
|
1144
|
+
if (currentTarget === fallbackTarget) {
|
|
1145
|
+
return false
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
const version = metadata?.version || (await getLatestVersion())
|
|
1149
|
+
if (!version) {
|
|
1150
|
+
return false
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
resetTerminal({
|
|
1154
|
+
exitAlternateScreen: shouldExitAlternateScreen(code, signal),
|
|
1155
|
+
})
|
|
1156
|
+
console.error('')
|
|
1157
|
+
console.error(
|
|
1158
|
+
`${packageName} is switching to the older-CPU binary for this machine.`,
|
|
1159
|
+
)
|
|
1160
|
+
|
|
1161
|
+
try {
|
|
1162
|
+
await downloadBinary(version, fallbackTarget)
|
|
1163
|
+
} catch (error) {
|
|
1164
|
+
term.clearLine()
|
|
1165
|
+
console.error(`Failed to download ${fallbackTarget}: ${error.message}`)
|
|
1166
|
+
return false
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
const child = spawnInstalledBinary({ detached: false })
|
|
1170
|
+
attachExitHandler(child, false)
|
|
1171
|
+
return true
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function attachExitHandler(child, allowBaselineFallback = true) {
|
|
1175
|
+
const exitListener = async (code, signal) => {
|
|
1176
|
+
if (
|
|
1177
|
+
allowBaselineFallback &&
|
|
1178
|
+
(await tryFallbackToBaseline(code, signal))
|
|
1179
|
+
) {
|
|
1180
|
+
return
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
resetTerminal({
|
|
1184
|
+
exitAlternateScreen: shouldExitAlternateScreen(code, signal),
|
|
1185
|
+
})
|
|
1186
|
+
printCrashDiagnostics(code, signal)
|
|
1187
|
+
process.exit(signal ? 1 : code || 0)
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
child.on('exit', exitListener)
|
|
1191
|
+
return exitListener
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
async function main() {
|
|
1195
|
+
for (const line of startupBanner) {
|
|
1196
|
+
console.log(line)
|
|
1197
|
+
}
|
|
1198
|
+
if (startupBanner.length > 0) console.log('')
|
|
1199
|
+
|
|
1200
|
+
await ensureBinaryExists()
|
|
1201
|
+
|
|
1202
|
+
const child = spawnInstalledBinary()
|
|
1203
|
+
const exitListener = attachExitHandler(child)
|
|
1204
|
+
|
|
1205
|
+
setTimeout(() => {
|
|
1206
|
+
checkForUpdates(child, exitListener)
|
|
1207
|
+
}, 100)
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
return {
|
|
1211
|
+
config: productConfig,
|
|
1212
|
+
main,
|
|
1213
|
+
stopRunningProcess,
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
module.exports = { createLauncher }
|