Repository navigation
Expand file tree
/
Copy pathinstall-sfw.ts
More file actions
245 lines (223 loc) · 7.98 KB
/
Copy pathinstall-sfw.ts
File metadata and controls
245 lines (223 loc) · 7.98 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
import { createWriteStream, existsSync } from "node:fs";
import { chmod, mkdir, mkdtemp, rename, rm, stat } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import type { get as httpGet } from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import { isWindows } from "./platform.js";
import { commandPath } from "./process.js";
import { resolveSfwEnabled } from "./sfw.js";
import type { ExportVariable, InstallCommand, LogFn, RunInstallEntry } from "./types.js";
// All integrations use this version pin. Renovate updates it through
// .github/renovate.json so reruns of the same commit download the same release.
export const SFW_VERSION = "v1.15.4";
export const SFW_RELEASE_BASE = `https://github.com/SocketDev/sfw-free/releases/download/${SFW_VERSION}`;
const DOWNLOAD_TIMEOUT_MS = 60_000;
type DownloadClient = typeof httpGet;
export function isMuslLinux(): boolean {
if (process.platform !== "linux") return false;
try {
const report = process.report?.getReport() as
| { header?: { glibcVersionRuntime?: string } }
| undefined;
if (report?.header && !report.header.glibcVersionRuntime) {
return true;
}
} catch {
// Fall through to filesystem fallback.
}
return existsSync("/etc/alpine-release");
}
export function getSfwAssetName(platform: NodeJS.Platform, arch: string, isMusl: boolean): string {
if (platform === "darwin") {
if (arch === "arm64") return "sfw-free-macos-arm64";
if (arch === "x64") return "sfw-free-macos-x86_64";
} else if (platform === "linux") {
if (arch === "arm64") {
return isMusl ? "sfw-free-musl-linux-arm64" : "sfw-free-linux-arm64";
}
if (arch === "x64") {
return isMusl ? "sfw-free-musl-linux-x86_64" : "sfw-free-linux-x86_64";
}
} else if (isWindows(platform)) {
if (arch === "arm64") return "sfw-free-windows-arm64.exe";
if (arch === "x64") return "sfw-free-windows-x86_64.exe";
}
const libcSuffix = platform === "linux" ? ` (${isMusl ? "musl" : "glibc"})` : "";
throw new Error(`Unsupported platform/arch for sfw: ${platform}/${arch}${libcSuffix}`);
}
function downloadFileWithShell(url: string, outputPath: string, timeoutMs: number): void {
const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
const curl = commandPath("curl");
if (curl) {
const result = spawnSync(
curl,
[
"-fsSL",
"--connect-timeout",
"5",
"--max-time",
String(timeoutSeconds),
url,
"-o",
outputPath,
],
{ stdio: "ignore" },
);
if (result.status === 0) return;
throw result.error || new Error(`curl failed while downloading ${url}`);
}
const wget = commandPath("wget");
if (wget) {
const result = spawnSync(
wget,
["-q", "-T", String(timeoutSeconds), "-t", "2", "-O", outputPath, url],
{ stdio: "ignore" },
);
if (result.status === 0) return;
throw result.error || new Error(`wget failed while downloading ${url}`);
}
throw new Error("curl or wget is required to download sfw");
}
export function downloadFile(
url: string,
outputPath: string,
redirects = 0,
timeoutMs = DOWNLOAD_TIMEOUT_MS,
clientOverride?: DownloadClient,
): Promise<void> {
if (redirects > 5) {
return Promise.reject(new Error(`too many redirects while downloading ${url}`));
}
if (!clientOverride) {
downloadFileWithShell(url, outputPath, timeoutMs);
return Promise.resolve();
}
return new Promise((resolve, reject) => {
let settled = false;
const finish = (error?: Error): void => {
if (settled) return;
settled = true;
clearTimeout(timeout);
if (error) {
reject(error);
} else {
resolve();
}
};
const request = clientOverride(url, (response) => {
const statusCode = response.statusCode ?? 0;
const location = response.headers.location;
if (statusCode >= 300 && statusCode < 400 && location) {
response.resume();
const nextUrl = new URL(location, url).toString();
downloadFile(nextUrl, outputPath, redirects + 1, timeoutMs, clientOverride).then(
() => finish(),
finish,
);
return;
}
if (statusCode !== 200) {
response.resume();
finish(new Error(`download failed with HTTP ${statusCode}: ${url}`));
return;
}
const file = createWriteStream(outputPath);
response.pipe(file);
file.on("finish", () => file.close(() => finish()));
file.on("error", finish);
});
const timeout = setTimeout(() => {
request.destroy(new Error(`download timed out after ${timeoutMs}ms: ${url}`));
}, timeoutMs);
request.on("error", finish);
});
}
export async function setupSfw(
runInstallEntries: RunInstallEntry[],
options: {
env?: NodeJS.ProcessEnv;
sfwEnabled?: boolean;
vitePlusVersion?: string;
logWarning?: LogFn;
exportVariable?: ExportVariable;
platform?: NodeJS.Platform;
arch?: string;
isMusl?: boolean;
download?: typeof downloadFile;
cacheDirectory?: string;
} = {},
): Promise<InstallCommand> {
const env = options.env ?? process.env;
const sfwEnabled = options.sfwEnabled ?? env.SETUP_VP_SFW === "true";
const platform = options.platform ?? process.platform;
const arch = options.arch ?? process.arch;
const isMusl = options.isMusl ?? isMuslLinux();
const download = options.download ?? downloadFile;
const effectiveSfw = resolveSfwEnabled(
sfwEnabled,
options.vitePlusVersion ?? "",
options.logWarning ?? console.warn,
);
if (!effectiveSfw) return { executable: "vp", sfw: false };
if (runInstallEntries.length === 0) {
console.log(
"setup-vp: sfw was requested but run-install is disabled; sfw will not be invoked.",
);
return { executable: "vp", sfw: false };
}
const existing = commandPath("sfw", env);
if (existing) {
console.log(`setup-vp: using existing sfw on PATH: ${existing}`);
return { executable: existing, sfw: true };
}
let asset: string;
try {
asset = getSfwAssetName(platform, arch, isMusl);
} catch {
console.error(
`setup-vp: sfw has no published binary for this runner's platform/architecture (process.platform=${platform}, process.arch=${arch}, musl=${isMusl}) and none was found on PATH; falling back to plain vp install.`,
);
return { executable: "vp", sfw: false };
}
const cacheDirectory = options.cacheDirectory || env.SETUP_VP_SFW_CACHE_DIR;
const sfwDir = cacheDirectory
? path.resolve(cacheDirectory, SFW_VERSION, asset)
: await mkdtemp(path.resolve(tmpdir(), "setup-vp-sfw-"));
await mkdir(sfwDir, { recursive: true });
const sfwBin = path.join(sfwDir, isWindows(platform) ? "sfw.exe" : "sfw");
const sfwUrl = `${SFW_RELEASE_BASE}/${asset}`;
function activate(): InstallCommand {
const pathSeparator = isWindows(platform) ? ";" : ":";
env.PATH = `${sfwDir}${pathSeparator}${env.PATH || ""}`;
options.exportVariable?.("PATH", env.PATH);
return { executable: sfwBin, sfw: true };
}
if (
await stat(sfwBin).then(
(file) => file.isFile() && file.size > 0,
() => false,
)
) {
console.log(`setup-vp: using cached sfw ${SFW_VERSION}: ${sfwBin}`);
return activate();
}
for (let round = 1; round <= 2; round += 1) {
const downloadDir = await mkdtemp(path.join(sfwDir, ".download-"));
const downloadPath = path.join(downloadDir, "sfw");
try {
console.log(`setup-vp: installing sfw ${SFW_VERSION} from ${sfwUrl}`);
await download(sfwUrl, downloadPath);
if ((await stat(downloadPath)).size === 0) throw new Error("Downloaded sfw binary is empty");
await chmod(downloadPath, 0o755);
await rename(downloadPath, sfwBin);
return activate();
} catch (error) {
if (round === 2) throw error;
await new Promise((resolve) => setTimeout(resolve, 2000));
} finally {
await rm(downloadDir, { recursive: true, force: true });
}
}
throw new Error("failed to install sfw after retrying");
}