-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathbinary-update.ts
More file actions
461 lines (415 loc) · 15.3 KB
/
Copy pathbinary-update.ts
File metadata and controls
461 lines (415 loc) · 15.3 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import {
chmod,
copyFile,
lstat,
mkdir,
readdir,
readlink,
rename,
rm,
unlink,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { homedir } from "node:os";
import { createHash } from "node:crypto";
import {
BINARY_PRODUCT_CLIENT_NAME,
binaryAssetFileName,
binaryInnerFileName,
channelManifestUrl,
detectBinaryPlatform,
extractZipEntryToFile,
getConfigDir,
releaseAssetUrl,
writeInstallMethodSync,
} from "bailian-cli-core";
export interface ChannelManifest {
version: string;
assets?: Record<string, { file?: string; sha256?: string; url?: string; inner?: string }>;
}
/** Product share root: versions/, current, and (on Windows) bin/. */
export function getBinaryShareRoot(): string {
if (process.env.BAILIAN_SHARE_DIR) return process.env.BAILIAN_SHARE_DIR;
if (process.platform === "win32") {
return join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "bailian-cli");
}
return join(homedir(), ".local", "share", "bailian-cli");
}
/** PATH directory that should expose `bl` / `bailian`. */
export function getBinaryBinRoot(): string {
if (process.env.BAILIAN_BIN_DIR) return process.env.BAILIAN_BIN_DIR;
if (process.platform === "win32") {
return join(getBinaryShareRoot(), "bin");
}
return join(homedir(), ".local", "bin");
}
export function getBinaryVersionsDir(): string {
return join(getBinaryShareRoot(), "versions");
}
export function getBinaryCurrentPath(): string {
return join(getBinaryShareRoot(), "current");
}
export async function fetchBinaryChannelVersion(
channel = "latest",
timeoutMs = 5000,
): Promise<string | null> {
try {
const response = await fetch(channelManifestUrl(channel), {
signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) return null;
const data = (await response.json()) as ChannelManifest;
return data.version ?? null;
} catch {
return null;
}
}
export async function fetchBinaryChannelManifest(
channel = "latest",
timeoutMs = 8000,
): Promise<ChannelManifest | null> {
try {
const response = await fetch(channelManifestUrl(channel), {
signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) return null;
return (await response.json()) as ChannelManifest;
} catch {
return null;
}
}
/** Strip a leading `v` from release-style tags (`v1.2.3` → `1.2.3`). */
export function normalizeBinaryVersion(raw: string): string {
const trimmed = raw.trim();
if (/^v\d/i.test(trimmed)) return trimmed.slice(1);
return trimmed;
}
/**
* Semver core + optional pre-release / build metadata.
* Accepts this repo's channel betas (`0.0.0-beta-<sha7>-<YYYYMMDDHHMM>`) and
* ordinary releases (`1.13.0`, `1.4.2-beta.1`). Optional leading `v` is allowed.
*/
const UPDATE_TARGET_VERSION_RE =
/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
/** True if `raw` is a usable `--to` target after trim (optional `v` prefix). */
export function isValidUpdateTargetVersion(raw: string): boolean {
const trimmed = raw.trim();
if (!trimmed) return false;
return UPDATE_TARGET_VERSION_RE.test(trimmed);
}
async function fetchSha256FromVersionSums(
version: string,
fileName: string,
timeoutMs = 8000,
): Promise<string | undefined> {
try {
const response = await fetch(releaseAssetUrl(version, "SHA256SUMS"), {
signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) return undefined;
const text = await response.text();
for (const line of text.split("\n")) {
const match = line.trim().match(/^([a-fA-F0-9]{64})\s+(\S+)$/);
if (match?.[2] === fileName) return match[1].toLowerCase();
}
} catch {
/* optional checksum source */
}
return undefined;
}
export interface BinaryDownloadSpec {
zipName: string;
innerName: string;
url: string;
expectedSha?: string;
}
/**
* Resolve download URL / names for an exact binary version.
* Always targets `v{version}/` assets; never reuses another version's rolling
* manifest `url` / `file`. Checksum prefers per-version SHA256SUMS, then the
* latest rolling manifest only when it points at the same version.
*/
export async function resolveBinaryDownloadSpec(
targetVersion: string,
): Promise<BinaryDownloadSpec> {
const version = normalizeBinaryVersion(targetVersion);
const { os, arch, fileSuffix } = detectBinaryPlatform();
const exe = fileSuffix === ".exe";
const zipName = binaryAssetFileName(version, os, arch, exe);
const innerName = binaryInnerFileName(version, os, arch, exe);
const url = releaseAssetUrl(version, zipName);
let expectedSha = await fetchSha256FromVersionSums(version, zipName);
if (!expectedSha) {
const manifest = await fetchBinaryChannelManifest("latest");
if (manifest?.version === version) {
expectedSha = manifest.assets?.[`${os}-${arch}`]?.sha256;
}
}
return { zipName, innerName, url, expectedSha };
}
async function downloadToFile(url: string, dest: string): Promise<Buffer> {
const response = await fetch(url, { signal: AbortSignal.timeout(120_000) });
if (!response.ok || !response.body) {
throw new Error(`Download failed (${response.status}): ${url}`);
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
await mkdir(dirname(dest), { recursive: true });
await writeFile(dest, buffer);
return buffer;
}
function sha256(buffer: Buffer): string {
return createHash("sha256").update(buffer).digest("hex");
}
function binaryFileName(): string {
return process.platform === "win32" ? "bl.exe" : "bl";
}
function aliasFileName(): string {
return process.platform === "win32" ? "bailian.exe" : "bailian";
}
/** Resolve which version directory `current` points at, if any. */
export async function readCurrentVersionDir(): Promise<string | null> {
const currentPath = getBinaryCurrentPath();
try {
const target = await readlink(currentPath);
return target.startsWith("/") || /^[A-Za-z]:[\\/]/.test(target)
? target
: join(dirname(currentPath), target);
} catch {
return null;
}
}
function versionNameFromDir(versionDir: string): string | null {
const versionsRoot = getBinaryVersionsDir();
const normalizedDir = versionDir.replaceAll("\\", "/");
const normalizedRoot = versionsRoot.replaceAll("\\", "/").replace(/\/$/, "");
if (!normalizedDir.startsWith(`${normalizedRoot}/`) && normalizedDir !== normalizedRoot) {
// Also accept basename match when paths differ by symlink resolution
const base = versionDir.replaceAll("\\", "/").split("/").pop();
return base && base !== "versions" ? base : null;
}
return normalizedDir.slice(normalizedRoot.length + 1).split("/")[0] ?? null;
}
/**
* Point `shareRoot/current` at `versions/<version>/`.
* Unix: directory symlink. Windows: directory junction.
* Retargets in place so PATH entries that go through `current` keep working.
*/
export async function switchCurrentToVersion(version: string): Promise<string> {
const versionDir = join(getBinaryVersionsDir(), version);
const currentPath = getBinaryCurrentPath();
await mkdir(getBinaryShareRoot(), { recursive: true });
try {
await unlink(currentPath);
} catch {
try {
await rm(currentPath, { recursive: true, force: true });
} catch {
/* missing */
}
}
const { symlink } = await import("node:fs/promises");
if (process.platform === "win32") {
await symlink(versionDir, currentPath, "junction");
} else {
await symlink(versionDir, currentPath);
}
return versionDir;
}
/**
* Ensure PATH bin entries resolve through `current` (Codex-style).
* - Unix: `~/.local/bin/{bl,bailian}` → `current/bl`
* - Windows: `shareRoot/bin` is a junction → `current` (contains bl.exe + bailian.exe)
*/
export async function ensureBinaryPathEntries(version: string): Promise<void> {
const versionDir = join(getBinaryVersionsDir(), version);
const binaryName = binaryFileName();
const currentBinary = join(getBinaryCurrentPath(), binaryName);
const binDir = getBinaryBinRoot();
if (process.platform === "win32") {
await ensureWindowsBinJunction(binDir);
// Version dir must expose both aliases for the bin junction to work.
const primary = join(versionDir, binaryName);
const aliasPath = join(versionDir, aliasFileName());
try {
await lstat(aliasPath);
} catch {
try {
const { link } = await import("node:fs/promises");
await link(primary, aliasPath);
} catch {
await copyFile(primary, aliasPath);
}
}
return;
}
await mkdir(binDir, { recursive: true });
const { symlink } = await import("node:fs/promises");
for (const name of ["bl", "bailian"] as const) {
const linkPath = join(binDir, name);
try {
await unlink(linkPath);
} catch {
/* missing */
}
await symlink(currentBinary, linkPath);
}
}
function errnoCode(error: unknown): string {
if (error && typeof error === "object" && "code" in error) {
return String((error as { code?: unknown }).code ?? "");
}
return "";
}
/**
* Ensure `shareRoot/bin` is a junction → `current`.
*
* Install scripts / older layouts may leave a real `bin/` directory with
* `bl.exe` inside. Deleting that directory fails with EACCES while this
* process is the running image — rename-away first (Windows allows that),
* then create the junction. Stale `bin.migrating-*` dirs are best-effort GC.
*/
export async function ensureWindowsBinJunction(binDir: string): Promise<void> {
const currentPath = getBinaryCurrentPath();
const { symlink, rename } = await import("node:fs/promises");
let migratedAside: string | null = null;
try {
const stats = await lstat(binDir);
if (stats.isSymbolicLink()) {
const target = await readlink(binDir);
const resolved =
target.startsWith("/") || /^[A-Za-z]:[\\/]/.test(target)
? target
: join(dirname(binDir), target);
if (
resolved.replaceAll("\\", "/").toLowerCase() ===
currentPath.replaceAll("\\", "/").toLowerCase()
) {
return;
}
await unlink(binDir);
} else if (stats.isDirectory()) {
// Prefer rename over rm: a running bl.exe inside bin locks delete/rm,
// but rename of the directory usually succeeds on Windows.
migratedAside = `${binDir}.migrating.${process.pid}`;
try {
await rename(binDir, migratedAside);
} catch (renameError) {
// Fallback: empty / unlocked real dirs can still be removed.
try {
await rm(binDir, { recursive: true, force: true });
migratedAside = null;
} catch (rmError) {
const code = errnoCode(renameError) || errnoCode(rmError) || "EACCES";
throw new Error(
`Failed to migrate ${binDir} to a junction pointing at current (${code}). ` +
`Close other bl sessions and re-run update, or re-run the install script once.`,
{ cause: rmError },
);
}
}
} else {
await unlink(binDir).catch(() => rm(binDir, { recursive: true, force: true }));
}
} catch (error) {
const code = errnoCode(error);
if (code && code !== "ENOENT") {
if (error instanceof Error && error.message.includes("Failed to migrate")) throw error;
throw new Error(
`Failed to migrate ${binDir} to a junction pointing at current (${code}). ` +
`Close other bl sessions and re-run update, or re-run the install script once.`,
{ cause: error },
);
}
}
await mkdir(dirname(binDir), { recursive: true });
await symlink(currentPath, binDir, "junction");
if (migratedAside) {
// Best-effort: locked exes may keep the aside dir until process exit.
await rm(migratedAside, { recursive: true, force: true }).catch(() => {});
}
}
/**
* Keep only the listed version directory names under `versions/`.
* Always preserves directories that are still the live `current` target.
*/
export async function pruneBinaryVersions(keepVersions: string[]): Promise<void> {
const versionsDir = getBinaryVersionsDir();
const keep = new Set(keepVersions.filter(Boolean));
const currentDir = await readCurrentVersionDir();
const currentName = currentDir ? versionNameFromDir(currentDir) : null;
if (currentName) keep.add(currentName);
let entries: string[];
try {
entries = await readdir(versionsDir);
} catch {
return;
}
for (const entry of entries) {
if (entry.startsWith(".")) {
await rm(join(versionsDir, entry), { recursive: true, force: true }).catch(() => {});
continue;
}
if (keep.has(entry)) continue;
await rm(join(versionsDir, entry), { recursive: true, force: true }).catch(() => {});
}
}
/**
* Download and install a newer standalone binary using Codex-style layout:
* `versions/<ver>/` + retarget `current` + path entries through `current`.
* After a successful switch, prune so only current + previous version remain.
*
* Does not overwrite a running executable image: old version files stay locked
* by the current process; the next invocation follows the updated pointer.
*/
export async function performBinaryUpdate(targetVersion: string): Promise<string> {
const version = normalizeBinaryVersion(targetVersion);
const { zipName, innerName, url, expectedSha } = await resolveBinaryDownloadSpec(version);
const share = getBinaryShareRoot();
const versionsDir = getBinaryVersionsDir();
await mkdir(join(share, ".tmp"), { recursive: true });
await mkdir(versionsDir, { recursive: true });
const previousVersionDir = await readCurrentVersionDir();
const previousVersion = previousVersionDir ? versionNameFromDir(previousVersionDir) : null;
const tmpZip = join(share, ".tmp", zipName);
const buffer = await downloadToFile(url, tmpZip);
const actualSha = sha256(buffer);
if (expectedSha && expectedSha !== actualSha) {
await unlink(tmpZip).catch(() => {});
throw new Error(`Checksum mismatch for ${zipName}`);
}
const stagingDir = join(versionsDir, `.staging.${version}.${process.pid}`);
await rm(stagingDir, { recursive: true, force: true }).catch(() => {});
await mkdir(stagingDir, { recursive: true });
const binaryName = binaryFileName();
const stagingBinary = join(stagingDir, binaryName);
const tmpBinary = join(share, ".tmp", `${binaryName}.${process.pid}`);
await extractZipEntryToFile(tmpZip, tmpBinary, innerName);
await unlink(tmpZip).catch(() => {});
await rename(tmpBinary, stagingBinary);
if (process.platform !== "win32") {
await chmod(stagingBinary, 0o755);
} else {
const aliasPath = join(stagingDir, aliasFileName());
try {
const { link } = await import("node:fs/promises");
await link(stagingBinary, aliasPath);
} catch {
await copyFile(stagingBinary, aliasPath);
}
}
const versionDir = join(versionsDir, version);
await rm(versionDir, { recursive: true, force: true }).catch(() => {});
await rename(stagingDir, versionDir);
await switchCurrentToVersion(version);
await ensureBinaryPathEntries(version);
const keep = [version];
if (previousVersion && previousVersion !== version) {
keep.push(previousVersion);
}
await pruneBinaryVersions(keep);
writeInstallMethodSync("binary", { clientName: BINARY_PRODUCT_CLIENT_NAME });
await mkdir(getConfigDir(), { recursive: true });
return version;
}