@online-tools/agent-runner 0.0.0-stage → 0.0.1-alpha-2

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/lib/lock.mjs ADDED
@@ -0,0 +1,66 @@
1
+ // One running instance per user: run.lock holds the owner's pid. A lock
2
+ // whose pid is gone (or now belongs to some other program) is taken over.
3
+
4
+ import { spawnSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+
7
+ export class LockedError extends Error {
8
+ constructor(pid) {
9
+ super(`已有实例在运行(pid ${pid},可能是后台服务,见 gitcode-agent-runner service status)`);
10
+ this.pid = pid;
11
+ }
12
+ }
13
+
14
+ /** True when `pid` is a live gitcode-agent-runner process (unknown commands count as live). */
15
+ export function isRunnerAlive(pid) {
16
+ if (!Number.isInteger(pid) || pid <= 0) return false;
17
+ try {
18
+ process.kill(pid, 0);
19
+ } catch (error) {
20
+ if (error.code !== 'EPERM') return false;
21
+ }
22
+ let command = '';
23
+ if (process.platform === 'linux') {
24
+ try {
25
+ command = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
26
+ } catch {
27
+ return true;
28
+ }
29
+ } else {
30
+ const result = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5000 });
31
+ if (result.status !== 0) return true;
32
+ command = result.stdout;
33
+ }
34
+ // A reused pid that runs something else is not our instance.
35
+ return command.includes('gitcode-agent-runner');
36
+ }
37
+
38
+ function owner(file) {
39
+ try {
40
+ return Number(fs.readFileSync(file, 'utf8').trim());
41
+ } catch {
42
+ return Number.NaN;
43
+ }
44
+ }
45
+
46
+ /** Takes the lock or throws LockedError. Returns { release() }. */
47
+ export function acquireLock(file, { pid = process.pid, isAlive = isRunnerAlive } = {}) {
48
+ const release = () => {
49
+ if (owner(file) === pid) fs.rmSync(file, { force: true });
50
+ };
51
+ for (let attempt = 0; attempt < 5; attempt += 1) {
52
+ try {
53
+ const fd = fs.openSync(file, 'wx', 0o600);
54
+ fs.writeSync(fd, String(pid));
55
+ fs.closeSync(fd);
56
+ return { release };
57
+ } catch (error) {
58
+ if (error.code !== 'EEXIST') throw error;
59
+ }
60
+ const holder = owner(file);
61
+ if (holder === pid) return { release };
62
+ if (Number.isInteger(holder) && holder > 0 && isAlive(holder)) throw new LockedError(holder);
63
+ fs.rmSync(file, { force: true }); // left behind by a dead instance
64
+ }
65
+ throw new Error(`无法获取运行锁 ${file}`);
66
+ }
package/lib/log.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // Timestamped Chinese log lines on stdout / stderr (systemd puts them in the
2
+ // journal, launchd in ~/Library/Logs). Never log a token, an API key,
3
+ // GITCODE_CRED or a proxy password: use redactUrl() for anything URL-like.
4
+
5
+ function stamp(date = new Date()) {
6
+ const pad = (value) => String(value).padStart(2, '0');
7
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
8
+ }
9
+
10
+ export function createLogger({ out = process.stdout, err = process.stderr } = {}) {
11
+ const write = (stream, prefix, message) => stream.write(`${stamp()} ${prefix}${message}\n`);
12
+ return {
13
+ info: (message) => write(out, '', message),
14
+ warn: (message) => write(err, '警告:', message),
15
+ error: (message) => write(err, '错误:', message),
16
+ };
17
+ }
18
+
19
+ /** Masks the account part of URLs (proxy addresses may carry user:password). */
20
+ export function redactUrl(value) {
21
+ return String(value ?? '').replace(/(\/\/)[^/@\s]*@/g, '$1***@');
22
+ }
@@ -0,0 +1,594 @@
1
+ 'use strict';
2
+ // A supported Node for the program when the machine's own is too old (Linux
3
+ // distributions ship old ones: Ubuntu 20.04 has 10, 22.04 has 12, 24.04 has
4
+ // 18): download the latest official Node.js LTS build (nodejs.org, or the
5
+ // npmmirror copy when nodejs.org is unreachable), check its SHA-256 against
6
+ // SHASUMS256.txt, and keep only bin/node under
7
+ // ${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/. The system
8
+ // Node and PATH are never touched.
9
+ //
10
+ // This file runs on that old Node (from bin/gitcode-agent-runner.cjs), so it
11
+ // is CommonJS and must work on Node 10: bare built-in names (no `node:`), no
12
+ // `?.` / `??`, no fetch, fs.rmSync, Array#at or other newer APIs.
13
+ // tests/agent-runner-node.test.js checks the syntax. Requiring it has no
14
+ // side effects.
15
+
16
+ const childProcess = require('child_process');
17
+ const crypto = require('crypto');
18
+ const fs = require('fs');
19
+ const http = require('http');
20
+ const https = require('https');
21
+ const os = require('os');
22
+ const path = require('path');
23
+ const tls = require('tls');
24
+ const zlib = require('zlib');
25
+
26
+ const NODE_REQUIREMENT = '22.21+、24.5+ 或 25+';
27
+ const OFFICIAL_SOURCE = 'https://nodejs.org/dist';
28
+ const MIRROR_SOURCE = 'https://npmmirror.com/mirrors/node';
29
+ const REQUEST_TIMEOUT_MS = 30000;
30
+ const TEXT_LIMIT = 4 * 1024 * 1024;
31
+ const MAX_REDIRECTS = 5;
32
+
33
+ /** The program's requirement: 22.x ≥ 22.21, 24.x ≥ 24.5, or 25+. */
34
+ function nodeSupported(version) {
35
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(version || ''));
36
+ if (!match) return false;
37
+ const major = Number(match[1]);
38
+ const minor = Number(match[2]);
39
+ if (major === 22) return minor >= 21;
40
+ if (major === 24) return minor >= 5;
41
+ return major >= 25;
42
+ }
43
+
44
+ function versionKey(version) {
45
+ return String(version).replace(/^v/, '').split('.').map(Number);
46
+ }
47
+
48
+ function compareVersionsDesc(a, b) {
49
+ const x = versionKey(a);
50
+ const y = versionKey(b);
51
+ for (let index = 0; index < 3; index += 1) {
52
+ if (x[index] !== y[index]) return y[index] - x[index];
53
+ }
54
+ return 0;
55
+ }
56
+
57
+ function nodeDataDir(env, home) {
58
+ const vars = env || process.env;
59
+ return path.join(vars.XDG_DATA_HOME || path.join(home || os.homedir(), '.local', 'share'), 'gitcode-agent-runner', 'node');
60
+ }
61
+
62
+ /** fs.rmSync(target, { recursive: true, force: true }), which Node < 14.14 lacks. */
63
+ function removeTree(target) {
64
+ if (typeof fs.rmSync === 'function') {
65
+ fs.rmSync(target, { recursive: true, force: true });
66
+ return;
67
+ }
68
+ let stat;
69
+ try {
70
+ stat = fs.lstatSync(target);
71
+ } catch (error) {
72
+ return;
73
+ }
74
+ if (stat.isDirectory()) {
75
+ for (const name of fs.readdirSync(target)) removeTree(path.join(target, name));
76
+ fs.rmdirSync(target);
77
+ } else fs.unlinkSync(target);
78
+ }
79
+
80
+ function isMusl(platform) {
81
+ if (platform !== 'linux') return false;
82
+ try {
83
+ if (process.report && typeof process.report.getReport === 'function') {
84
+ return !process.report.getReport().header.glibcVersionRuntime;
85
+ }
86
+ } catch (error) {
87
+ // Fall through to the loader check.
88
+ }
89
+ try {
90
+ return fs.readdirSync('/lib').some((name) => name.indexOf('ld-musl-') === 0);
91
+ } catch (error) {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Which official build fits: { indexKey (index.json "files"), suffix (file
98
+ * name) }, or null when there is none for this system.
99
+ */
100
+ function distTarget(platform, arch, musl) {
101
+ const system = platform || process.platform;
102
+ const cpu = arch || process.arch;
103
+ if (system === 'darwin') {
104
+ if (cpu === 'x64' || cpu === 'arm64') return { indexKey: 'osx-' + cpu + '-tar', suffix: 'darwin-' + cpu };
105
+ return null;
106
+ }
107
+ if (system !== 'linux') return null;
108
+ if (musl === undefined ? isMusl(system) : musl) {
109
+ return cpu === 'x64' ? { indexKey: 'linux-x64-musl', suffix: 'linux-x64-musl' } : null;
110
+ }
111
+ const names = { x64: 'linux-x64', arm64: 'linux-arm64', ppc64: 'linux-ppc64le', s390x: 'linux-s390x' };
112
+ return names[cpu] ? { indexKey: names[cpu], suffix: names[cpu] } : null;
113
+ }
114
+
115
+ /** The newest LTS release in index.json that has a build for `target` and meets the requirement. */
116
+ function pickRelease(index, target) {
117
+ if (!Array.isArray(index)) return null;
118
+ for (const release of index) {
119
+ if (!release || !release.lts || typeof release.version !== 'string') continue;
120
+ if (!/^v\d+\.\d+\.\d+$/.test(release.version)) continue;
121
+ if (!nodeSupported(release.version)) continue;
122
+ if (!Array.isArray(release.files) || release.files.indexOf(target.indexKey) === -1) continue;
123
+ return { version: release.version.slice(1), lts: String(release.lts) };
124
+ }
125
+ return null;
126
+ }
127
+
128
+ // ---- HTTPS (with HTTPS_PROXY via CONNECT) ---------------------------------------
129
+
130
+ function bareHost(hostname) {
131
+ return hostname.replace(/^\[(.*)\]$/, '$1');
132
+ }
133
+
134
+ function isLoopback(hostname) {
135
+ const host = bareHost(hostname);
136
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1';
137
+ }
138
+
139
+ /** The proxy for an https URL (HTTPS_PROXY, then HTTP_PROXY), honouring NO_PROXY; null for none. */
140
+ function proxyFor(target, env) {
141
+ const vars = env || process.env;
142
+ if (isLoopback(target.hostname)) return null;
143
+ const raw = vars.HTTPS_PROXY || vars.https_proxy || vars.HTTP_PROXY || vars.http_proxy || '';
144
+ if (!raw) return null;
145
+ const skip = String(vars.NO_PROXY || vars.no_proxy || '')
146
+ .split(',')
147
+ .map((item) => item.trim().toLowerCase())
148
+ .filter(Boolean);
149
+ const host = target.hostname.toLowerCase();
150
+ for (const entry of skip) {
151
+ if (entry === '*') return null;
152
+ const bare = entry.replace(/^\*?\./, '').replace(/:\d+$/, '');
153
+ if (host === bare || host.endsWith('.' + bare)) return null;
154
+ }
155
+ let proxy;
156
+ try {
157
+ proxy = new URL(raw.indexOf('://') === -1 ? 'http://' + raw : raw);
158
+ } catch (error) {
159
+ return null;
160
+ }
161
+ return proxy.protocol === 'http:' ? proxy : null; // only plain-HTTP proxies (CONNECT)
162
+ }
163
+
164
+ /**
165
+ * GET `url` (https; http only to 127.0.0.1 / localhost) and resolve with the
166
+ * 200 response, following redirects. `timeoutMs` is an idle timeout. The
167
+ * response is guarded so that it always ends in 'end' or 'error' (old Node
168
+ * only emits 'close' when a response is cut off).
169
+ */
170
+ function httpGet(url, options, redirects) {
171
+ const opts = options || {};
172
+ const timeoutMs = opts.timeoutMs || REQUEST_TIMEOUT_MS;
173
+ const env = opts.env || process.env;
174
+ const tlsOptions = opts.tlsOptions || {};
175
+ const hops = redirects || 0;
176
+ return new Promise((resolve, reject) => {
177
+ let target;
178
+ try {
179
+ target = new URL(url);
180
+ } catch (error) {
181
+ reject(new Error('地址不正确:' + url));
182
+ return;
183
+ }
184
+ const secure = target.protocol === 'https:';
185
+ if (!secure && !(target.protocol === 'http:' && isLoopback(target.hostname))) {
186
+ reject(new Error('只允许 https 下载:' + url));
187
+ return;
188
+ }
189
+ const port = target.port || (secure ? '443' : '80');
190
+ const send = (socket) => {
191
+ const requestOptions = Object.assign({}, socket ? {} : tlsOptions, {
192
+ hostname: bareHost(target.hostname),
193
+ port,
194
+ path: target.pathname + target.search,
195
+ method: 'GET',
196
+ headers: { 'User-Agent': 'gitcode-agent-runner', Accept: '*/*' },
197
+ });
198
+ if (socket) requestOptions.createConnection = () => socket;
199
+ const request = (secure ? https : http).request(requestOptions, (response) => {
200
+ const statusCode = response.statusCode;
201
+ const location = response.headers.location;
202
+ if ([301, 302, 303, 307, 308].indexOf(statusCode) !== -1 && location) {
203
+ response.resume();
204
+ if (hops >= MAX_REDIRECTS) {
205
+ reject(new Error('重定向过多:' + url));
206
+ return;
207
+ }
208
+ resolve(httpGet(new URL(location, target).toString(), opts, hops + 1));
209
+ return;
210
+ }
211
+ if (statusCode !== 200) {
212
+ response.resume();
213
+ reject(new Error('HTTP ' + statusCode + ':' + url));
214
+ return;
215
+ }
216
+ response.setTimeout(timeoutMs, () => response.destroy(new Error('下载超时:' + url)));
217
+ response.on('close', () => {
218
+ if (!response.complete) response.emit('error', new Error('连接中断:' + url));
219
+ });
220
+ resolve(response);
221
+ });
222
+ request.setTimeout(timeoutMs, () => request.destroy(new Error('连接超时:' + target.host)));
223
+ request.on('error', reject);
224
+ request.end();
225
+ };
226
+ const proxy = secure ? proxyFor(target, env) : null;
227
+ if (!proxy) {
228
+ send(null);
229
+ return;
230
+ }
231
+ const headers = { Host: target.hostname + ':' + port };
232
+ if (proxy.username) {
233
+ const credentials = decodeURIComponent(proxy.username) + ':' + decodeURIComponent(proxy.password);
234
+ headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(credentials).toString('base64');
235
+ }
236
+ const connect = http.request({
237
+ hostname: bareHost(proxy.hostname),
238
+ port: proxy.port || 80,
239
+ method: 'CONNECT',
240
+ path: target.hostname + ':' + port,
241
+ headers,
242
+ });
243
+ connect.setTimeout(timeoutMs, () => connect.destroy(new Error('代理连接超时')));
244
+ connect.on('connect', (response, socket) => {
245
+ if (response.statusCode !== 200) {
246
+ socket.destroy();
247
+ reject(new Error('代理拒绝连接(HTTP ' + response.statusCode + ')'));
248
+ return;
249
+ }
250
+ // The tunnel's own request keeps the idle timeout from here on.
251
+ socket.setTimeout(0);
252
+ socket.removeAllListeners('timeout');
253
+ const tunnel = tls.connect(Object.assign({ socket, servername: bareHost(target.hostname) }, tlsOptions));
254
+ tunnel.once('secureConnect', () => send(tunnel));
255
+ tunnel.once('error', reject);
256
+ });
257
+ connect.on('error', reject);
258
+ connect.end();
259
+ });
260
+ }
261
+
262
+ function httpText(url, options) {
263
+ return httpGet(url, options).then(
264
+ (response) =>
265
+ new Promise((resolve, reject) => {
266
+ const chunks = [];
267
+ let size = 0;
268
+ response.on('data', (chunk) => {
269
+ size += chunk.length;
270
+ if (size > TEXT_LIMIT) {
271
+ response.destroy();
272
+ reject(new Error('响应过大:' + url));
273
+ return;
274
+ }
275
+ chunks.push(chunk);
276
+ });
277
+ response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
278
+ response.on('error', reject);
279
+ }),
280
+ );
281
+ }
282
+
283
+ /** Streams `url` into `file`; resolves with { sha256, size }. `options.onProgress(received, total)`. */
284
+ function downloadFile(url, file, options) {
285
+ const opts = options || {};
286
+ return httpGet(url, opts).then(
287
+ (response) =>
288
+ new Promise((resolve, reject) => {
289
+ const total = Number(response.headers['content-length']) || 0;
290
+ const hash = crypto.createHash('sha256');
291
+ let received = 0;
292
+ const out = fs.createWriteStream(file, { mode: 0o600 });
293
+ response.on('data', (chunk) => {
294
+ hash.update(chunk);
295
+ received += chunk.length;
296
+ if (opts.onProgress) opts.onProgress(received, total);
297
+ });
298
+ response.on('error', (error) => {
299
+ out.destroy();
300
+ reject(error);
301
+ });
302
+ out.on('error', reject);
303
+ out.on('finish', () => {
304
+ if (total && received !== total) reject(new Error('下载不完整'));
305
+ else resolve({ sha256: hash.digest('hex'), size: received });
306
+ });
307
+ response.pipe(out);
308
+ }),
309
+ );
310
+ }
311
+
312
+ /** The SHA-256 of `fileName` in a SHASUMS256.txt, or ''. */
313
+ function checksumFor(sums, fileName) {
314
+ for (const line of String(sums).split('\n')) {
315
+ const match = /^([0-9a-f]{64})\s+\*?(\S+)$/.exec(line.trim());
316
+ if (match && match[2] === fileName) return match[1];
317
+ }
318
+ return '';
319
+ }
320
+
321
+ // ---- tar.gz: take bin/node only -----------------------------------------------
322
+
323
+ function field(header, start, length) {
324
+ const raw = header.subarray(start, start + length);
325
+ const end = raw.indexOf(0);
326
+ return raw.subarray(0, end === -1 ? length : end).toString('utf8');
327
+ }
328
+
329
+ function entrySize(header) {
330
+ if (header[124] & 0x80) {
331
+ // GNU base-256 for large sizes.
332
+ let size = 0;
333
+ for (let index = 125; index < 136; index += 1) size = size * 256 + header[index];
334
+ return size;
335
+ }
336
+ const text = field(header, 124, 12).trim();
337
+ return text ? parseInt(text, 8) : 0;
338
+ }
339
+
340
+ /**
341
+ * Extracts the one regular file `wanted` (e.g. node-v26.13.1-linux-x64/bin/node)
342
+ * from a .tar.gz into `dest` (mode 0755). Nothing else is ever written, so
343
+ * archive paths cannot escape. Understands ustar names, GNU long names and
344
+ * pax `path` records. Resolves false when the entry is missing.
345
+ */
346
+ function extractTarEntry(archive, wanted, dest) {
347
+ return new Promise((resolve, reject) => {
348
+ const input = fs.createReadStream(archive);
349
+ const gunzip = zlib.createGunzip();
350
+ let header = Buffer.alloc(0);
351
+ let dataLeft = 0; // bytes of the current entry still to read
352
+ let padLeft = 0; // padding after it
353
+ let fd = null; // open while writing `wanted`
354
+ let collect = null; // { kind: 'L' | 'x', chunks } for long names / pax data
355
+ let nextName = '';
356
+ let found = false;
357
+ let ended = false;
358
+ let failed = false;
359
+ const fail = (error) => {
360
+ if (failed) return;
361
+ failed = true;
362
+ if (fd !== null) {
363
+ try {
364
+ fs.closeSync(fd);
365
+ } catch (closeError) {
366
+ // Ignore.
367
+ }
368
+ fd = null;
369
+ }
370
+ input.destroy();
371
+ gunzip.destroy();
372
+ reject(error);
373
+ };
374
+ const finishEntry = () => {
375
+ if (fd !== null) {
376
+ fs.closeSync(fd);
377
+ fd = null;
378
+ found = true;
379
+ }
380
+ if (collect) {
381
+ const text = Buffer.concat(collect.chunks).toString('utf8');
382
+ if (collect.kind === 'L') nextName = text.replace(/\0+$/, '');
383
+ else {
384
+ const match = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(text);
385
+ if (match) nextName = match[1];
386
+ }
387
+ collect = null;
388
+ }
389
+ };
390
+ const startEntry = (block) => {
391
+ const name = field(block, 0, 100);
392
+ const prefix = block.subarray(257, 262).toString('latin1') === 'ustar' ? field(block, 345, 155) : '';
393
+ const type = String.fromCharCode(block[156] || 48);
394
+ const size = entrySize(block);
395
+ dataLeft = size;
396
+ padLeft = (512 - (size % 512)) % 512;
397
+ if (type === 'L' || type === 'x') {
398
+ collect = { kind: type, chunks: [] };
399
+ return;
400
+ }
401
+ const full = (nextName || (prefix ? prefix + '/' + name : name)).replace(/^\.\//, '');
402
+ nextName = '';
403
+ if (full === wanted && (type === '0' || type === '7')) {
404
+ fd = fs.openSync(dest, 'w', 0o755);
405
+ }
406
+ if (dataLeft === 0) finishEntry();
407
+ };
408
+ gunzip.on('data', (chunk) => {
409
+ if (failed) return;
410
+ try {
411
+ let offset = 0;
412
+ while (offset < chunk.length && !ended) {
413
+ if (dataLeft > 0) {
414
+ const count = Math.min(dataLeft, chunk.length - offset);
415
+ const slice = chunk.subarray(offset, offset + count);
416
+ if (fd !== null) fs.writeSync(fd, slice);
417
+ else if (collect) collect.chunks.push(Buffer.from(slice));
418
+ offset += count;
419
+ dataLeft -= count;
420
+ if (dataLeft === 0) finishEntry();
421
+ continue;
422
+ }
423
+ if (padLeft > 0) {
424
+ const count = Math.min(padLeft, chunk.length - offset);
425
+ offset += count;
426
+ padLeft -= count;
427
+ continue;
428
+ }
429
+ const take = chunk.subarray(offset, offset + 512 - header.length);
430
+ header = Buffer.concat([header, take]);
431
+ offset += take.length;
432
+ if (header.length < 512) continue;
433
+ const block = header;
434
+ header = Buffer.alloc(0);
435
+ if (block.every((byte) => byte === 0)) {
436
+ ended = true; // end-of-archive marker
437
+ break;
438
+ }
439
+ startEntry(block);
440
+ }
441
+ } catch (error) {
442
+ fail(error);
443
+ }
444
+ });
445
+ gunzip.on('end', () => {
446
+ if (failed) return;
447
+ if (fd !== null) {
448
+ fs.closeSync(fd);
449
+ fd = null;
450
+ }
451
+ resolve(found);
452
+ });
453
+ gunzip.on('error', fail);
454
+ input.on('error', fail);
455
+ input.pipe(gunzip);
456
+ });
457
+ }
458
+
459
+ // ---- Install / find ---------------------------------------------------------------
460
+
461
+ /** Whether `nodePath --version` prints v<version>; `output` explains a failure. */
462
+ function nodeRuns(nodePath, version) {
463
+ const result = childProcess.spawnSync(nodePath, ['--version'], { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'pipe'] });
464
+ const output = ((result.stdout || '') + (result.stderr || '') || (result.error ? result.error.message : '')).trim();
465
+ return { ok: result.status === 0 && String(result.stdout).trim() === 'v' + version, output };
466
+ }
467
+
468
+ /** The newest installed supported Node that runs: { nodePath, version } or null. */
469
+ function findManagedNode(dataDir) {
470
+ let names = [];
471
+ try {
472
+ names = fs.readdirSync(dataDir);
473
+ } catch (error) {
474
+ return null;
475
+ }
476
+ const versions = names
477
+ .filter((name) => /^v\d+\.\d+\.\d+$/.test(name) && nodeSupported(name))
478
+ .map((name) => name.slice(1))
479
+ .sort(compareVersionsDesc);
480
+ for (const version of versions) {
481
+ const nodePath = path.join(dataDir, 'v' + version, 'bin', 'node');
482
+ if (fs.existsSync(nodePath) && nodeRuns(nodePath, version).ok) return { nodePath, version };
483
+ }
484
+ return null;
485
+ }
486
+
487
+ function hostOf(source) {
488
+ try {
489
+ return new URL(source).host;
490
+ } catch (error) {
491
+ return source;
492
+ }
493
+ }
494
+
495
+ /** One source: resolves with the installed { nodePath, version }. */
496
+ async function installFrom(source, { dataDir, target, env, tlsOptions, say, onProgress }) {
497
+ const request = { env, tlsOptions };
498
+ const work = fs.mkdtempSync(path.join(dataDir, '.download-'));
499
+ try {
500
+ const release = pickRelease(JSON.parse(await httpText(source + '/index.json', request)), target);
501
+ if (!release) throw new Error('没有找到合适的 LTS 版本');
502
+ const fileName = 'node-v' + release.version + '-' + target.suffix + '.tar.gz';
503
+ let expected = checksumFor(await httpText(source + '/v' + release.version + '/SHASUMS256.txt', request), fileName);
504
+ if (!expected) throw new Error('SHASUMS256.txt 里没有 ' + fileName);
505
+ if (source === MIRROR_SOURCE) {
506
+ let official = '';
507
+ try {
508
+ official = checksumFor(await httpText(OFFICIAL_SOURCE + '/v' + release.version + '/SHASUMS256.txt', { env, timeoutMs: 10000 }), fileName);
509
+ } catch (error) {
510
+ say('无法访问 nodejs.org 核对校验值,使用 ' + hostOf(source) + ' 提供的校验值');
511
+ }
512
+ if (official && official !== expected) throw new Error('镜像的校验值与 nodejs.org 不一致,已停止');
513
+ if (official) expected = official;
514
+ }
515
+ const url = source + '/v' + release.version + '/' + fileName;
516
+ say('下载 ' + url);
517
+ const archive = path.join(work, fileName);
518
+ const got = await downloadFile(url, archive, { env, tlsOptions, onProgress });
519
+ if (got.sha256 !== expected) throw new Error(fileName + ' 的 SHA-256 与 SHASUMS256.txt 不一致,已丢弃');
520
+ say('✓ 校验通过(SHA-256)');
521
+ const staged = path.join(work, 'v' + release.version);
522
+ fs.mkdirSync(path.join(staged, 'bin'), { recursive: true });
523
+ const stagedNode = path.join(staged, 'bin', 'node');
524
+ const entry = 'node-v' + release.version + '-' + target.suffix + '/bin/node';
525
+ if (!(await extractTarEntry(archive, entry, stagedNode))) throw new Error('压缩包里没有 ' + entry);
526
+ fs.chmodSync(stagedNode, 0o755);
527
+ const check = nodeRuns(stagedNode, release.version);
528
+ if (!check.ok) throw new Error('下载的 Node 无法在这台机器上运行:' + (check.output.slice(0, 300) || '没有输出'));
529
+ const final = path.join(dataDir, 'v' + release.version);
530
+ removeTree(final);
531
+ fs.renameSync(staged, final);
532
+ // Older managed versions are no longer needed.
533
+ for (const name of fs.readdirSync(dataDir)) {
534
+ if (/^v\d+\.\d+\.\d+$/.test(name) && name !== 'v' + release.version) removeTree(path.join(dataDir, name));
535
+ }
536
+ return { nodePath: path.join(final, 'bin', 'node'), version: release.version };
537
+ } finally {
538
+ removeTree(work);
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Downloads and installs the latest LTS Node into `dataDir`; resolves with
544
+ * { nodePath, version, source }. `sources`: tried in order (GC_RUNNER_NODE_MIRROR
545
+ * when set, else nodejs.org then npmmirror). With the mirror, its checksum is
546
+ * cross-checked against nodejs.org when that answers. `say(text)` reports
547
+ * steps, `onProgress(received, total)` the download.
548
+ */
549
+ async function installManagedNode(options) {
550
+ const platform = options.platform || process.platform;
551
+ const arch = options.arch || process.arch;
552
+ const env = options.env || process.env;
553
+ const say = options.say || (() => {});
554
+ const dataDir = options.dataDir;
555
+ const target = distTarget(platform, arch, options.musl);
556
+ if (!target) throw new Error('没有适用于 ' + platform + '/' + arch + ' 的 Node.js 官方版本,请自行安装 Node ' + NODE_REQUIREMENT);
557
+ const list = options.sources || (env.GC_RUNNER_NODE_MIRROR ? [env.GC_RUNNER_NODE_MIRROR.replace(/\/+$/, '')] : [OFFICIAL_SOURCE, MIRROR_SOURCE]);
558
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
559
+ // Left by an interrupted download (Ctrl+C skips the cleanup in installFrom).
560
+ for (const name of fs.readdirSync(dataDir)) {
561
+ if (name.indexOf('.download-') === 0) removeTree(path.join(dataDir, name));
562
+ }
563
+ const problems = [];
564
+ for (let index = 0; index < list.length; index += 1) {
565
+ const source = list[index];
566
+ try {
567
+ const installed = await installFrom(source, { dataDir, target, env, tlsOptions: options.tlsOptions, say, onProgress: options.onProgress });
568
+ return { nodePath: installed.nodePath, version: installed.version, source };
569
+ } catch (error) {
570
+ problems.push(hostOf(source) + ':' + error.message);
571
+ if (index < list.length - 1) say(hostOf(source) + ' 下载失败(' + error.message + '),改用下一个来源');
572
+ }
573
+ }
574
+ throw new Error(problems.join(';'));
575
+ }
576
+
577
+ module.exports = {
578
+ NODE_REQUIREMENT,
579
+ OFFICIAL_SOURCE,
580
+ MIRROR_SOURCE,
581
+ nodeSupported,
582
+ nodeDataDir,
583
+ distTarget,
584
+ pickRelease,
585
+ proxyFor,
586
+ httpGet,
587
+ httpText,
588
+ downloadFile,
589
+ checksumFor,
590
+ extractTarEntry,
591
+ nodeRuns,
592
+ findManagedNode,
593
+ installManagedNode,
594
+ };