@hit-sudomaker/ccw 0.4.0 → 0.5.0
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/README.md +54 -52
- package/assets/ccline/config.toml +34 -34
- package/assets/skills/amirc-research/SKILL.md +39 -39
- package/dist/ccline.js +149 -616
- package/dist/ccw.js +167 -378
- package/dist/claude-program.js +191 -0
- package/dist/claude.js +177 -0
- package/dist/cleanup.js +150 -348
- package/dist/effect-machine.js +65 -0
- package/dist/frozen-json.js +99 -0
- package/dist/instance.js +71 -0
- package/dist/machine.js +613 -573
- package/dist/main.js +68 -58
- package/dist/management-catalog.js +60 -54
- package/dist/messages.js +182 -0
- package/dist/model.js +39 -144
- package/dist/npm-registry.js +110 -27
- package/dist/officecli.js +274 -404
- package/dist/planning.js +141 -0
- package/dist/plugins.js +134 -294
- package/dist/program-channels.js +94 -384
- package/dist/program-operations.js +155 -0
- package/dist/read-machine.js +94 -43
- package/dist/render.js +350 -347
- package/dist/settings.js +380 -0
- package/dist/skill-files.js +184 -77
- package/dist/skills.js +393 -237
- package/dist/terminal-view.js +303 -395
- package/dist/terminal.js +207 -467
- package/dist/work.js +135 -0
- package/package.json +1 -2
- package/dist/claude-config.js +0 -347
- package/dist/errors.js +0 -139
- package/dist/legacy-amirc.js +0 -60
- package/dist/mcp.js +0 -299
- package/dist/programs.js +0 -778
- package/dist/run-presentation.js +0 -155
- package/dist/titles.js +0 -43
- package/dist/warnings.js +0 -6
package/dist/machine.js
CHANGED
|
@@ -6,95 +6,307 @@ import path from 'node:path';
|
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import { pipeline } from 'node:stream/promises';
|
|
8
8
|
import { StringDecoder } from 'node:string_decoder';
|
|
9
|
-
/**
|
|
9
|
+
/** 只读短命令的默认毫秒时限 */
|
|
10
10
|
export const READ_COMMAND_TIMEOUT_MS = 5_000;
|
|
11
|
+
/** Git 元数据查询的默认毫秒时限 */
|
|
11
12
|
export const GIT_COMMAND_TIMEOUT_MS = 15_000;
|
|
13
|
+
/** 远端文本下载的默认毫秒时限 */
|
|
12
14
|
export const FETCH_TEXT_TIMEOUT_MS = 30_000;
|
|
15
|
+
/** 远端字节下载的默认毫秒时限 */
|
|
13
16
|
export const FETCH_BYTES_TIMEOUT_MS = 120_000;
|
|
17
|
+
/** Git 来源检出的默认总毫秒时限 */
|
|
14
18
|
export const SOURCE_TIMEOUT_MS = 120_000;
|
|
19
|
+
const COMMAND_TIMEOUT_MS = 300_000;
|
|
20
|
+
const INTERACTIVE_COMMAND_TIMEOUT_MS = 900_000;
|
|
21
|
+
const FORCE_STOP_DELAY_MS = 250;
|
|
22
|
+
/** 检查是否为 40 位小写十六进制提交号,不验证提交是否存在 */
|
|
23
|
+
export const isGitRevision = (value) => /^[a-f0-9]{40}$/.test(value);
|
|
15
24
|
/** 限制整读内容的内存占用 */
|
|
16
25
|
const FILE_LIMIT_BYTES = 2 * 1024 * 1024;
|
|
17
26
|
const OUTPUT_LIMIT_BYTES = 1024 * 1024;
|
|
18
27
|
const TEXT_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
19
28
|
const DOWNLOAD_LIMIT_BYTES = 256 * 1024 * 1024;
|
|
20
29
|
const SOURCE_LIMIT_BYTES = 256 * 1024 * 1024;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
throw
|
|
44
|
-
|
|
45
|
-
|
|
30
|
+
/**
|
|
31
|
+
* 创建隔离的环境副本,封装本机访问并在首次成功解析时固定 npm 身份
|
|
32
|
+
*
|
|
33
|
+
* @param environment - 命令环境初值,后续用户 PATH 更新只修改实例内副本
|
|
34
|
+
* @param cwd - 未单独指定工作目录时使用的目录
|
|
35
|
+
* @param handoff - 交互命令可选的终端交接回调,由回调负责执行传入工作
|
|
36
|
+
* @returns 具有直接系统访问能力的 Machine,调用方仍需施加读写权限包装
|
|
37
|
+
*/
|
|
38
|
+
export function createMachine(environment = process.env, cwd = process.cwd(), handoff) {
|
|
39
|
+
environment = normalizeEnvironment(environment);
|
|
40
|
+
const inheritedPath = environment.PATH ?? '';
|
|
41
|
+
let npmTool;
|
|
42
|
+
const resolveNpm = async (signal) => {
|
|
43
|
+
npmTool ??= (async () => {
|
|
44
|
+
const entry = path.resolve(await npmPath(environment));
|
|
45
|
+
const binary = await fs.realpath(entry);
|
|
46
|
+
const stamp = await fingerprint(binary);
|
|
47
|
+
if (stamp === null)
|
|
48
|
+
throw new Error('npm-not-found');
|
|
49
|
+
return { entry, binary, stamp };
|
|
50
|
+
})().catch(error => {
|
|
51
|
+
npmTool = undefined;
|
|
52
|
+
throw error;
|
|
53
|
+
});
|
|
54
|
+
const tool = await npmTool;
|
|
55
|
+
if ((await fs.realpath(tool.entry)) !== tool.binary || (await fingerprint(tool.binary, signal)) !== tool.stamp)
|
|
56
|
+
throw new Error('npm-changed');
|
|
57
|
+
return { ...tool };
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
read,
|
|
61
|
+
fingerprint,
|
|
62
|
+
editJson,
|
|
63
|
+
entries,
|
|
64
|
+
treeStamp,
|
|
65
|
+
removeTree,
|
|
66
|
+
replaceFile,
|
|
67
|
+
async realpath(file) {
|
|
68
|
+
try {
|
|
69
|
+
return await fs.realpath(file);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (errorCode(error) === 'ENOENT')
|
|
73
|
+
return null;
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
async locate(command) {
|
|
78
|
+
if (!/^[\w.-]+$/.test(command))
|
|
79
|
+
throw new Error('invalid-command');
|
|
80
|
+
const found = [];
|
|
81
|
+
for (const directory of (environment.PATH ?? '').split(path.delimiter).filter(Boolean)) {
|
|
82
|
+
for (const extension of process.platform === 'win32' ? ['.exe', '.cmd', '.ps1', ''] : ['']) {
|
|
83
|
+
const file = path.resolve(directory, `${command}${extension}`);
|
|
84
|
+
try {
|
|
85
|
+
if ((await fs.stat(file)).isFile() && !found.includes(file))
|
|
86
|
+
found.push(file);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (errorCode(error) !== 'ENOENT' && errorCode(error) !== 'ENOTDIR')
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return found;
|
|
95
|
+
},
|
|
96
|
+
execute(executable, args, options = {}) {
|
|
97
|
+
const work = () => run(executable, args, { ...environment, ...normalizeEnvironment(options.env ?? {}) }, options.cwd ?? cwd, options);
|
|
98
|
+
return options.isInteractive && handoff ? handoff(work) : work();
|
|
99
|
+
},
|
|
100
|
+
async processes(options = {}) {
|
|
101
|
+
const commandOptions = { ...options, timeoutMs: options.timeoutMs ?? READ_COMMAND_TIMEOUT_MS };
|
|
102
|
+
const result = process.platform === 'win32'
|
|
103
|
+
? await this.execute('powershell.exe', [
|
|
104
|
+
'-NoProfile',
|
|
105
|
+
'-NonInteractive',
|
|
106
|
+
'-Command',
|
|
107
|
+
"$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Select-Object Name,CommandLine) | ConvertTo-Json -Compress",
|
|
108
|
+
], commandOptions)
|
|
109
|
+
: await this.execute('ps', ['-A', '-o', 'comm=', '-o', 'args='], commandOptions);
|
|
110
|
+
if (!succeeded(result))
|
|
111
|
+
return null;
|
|
112
|
+
if (process.platform !== 'win32')
|
|
113
|
+
return result.stdout.split('\n').flatMap(line => {
|
|
114
|
+
const match = /^(\S+)\s+(.*)$/.exec(line.trim());
|
|
115
|
+
return match === null ? [] : [{ name: match[1] ?? '', command: match[2] ?? '' }];
|
|
116
|
+
});
|
|
117
|
+
try {
|
|
118
|
+
const value = result.stdout.trim() ? JSON.parse(result.stdout) : [];
|
|
119
|
+
const list = Array.isArray(value) ? value : [value];
|
|
120
|
+
const found = [];
|
|
121
|
+
for (const entry of list) {
|
|
122
|
+
if (!isObject(entry) || typeof entry.Name !== 'string')
|
|
123
|
+
return null;
|
|
124
|
+
// 命令行不可读(如提权进程)按空串保留条目:名称可判定的进程不得因命令行缺失而漏报
|
|
125
|
+
found.push({ name: entry.Name, command: typeof entry.CommandLine === 'string' ? entry.CommandLine : '' });
|
|
126
|
+
}
|
|
127
|
+
return found;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
async fetchText(url, options = {}) {
|
|
134
|
+
return remoteRead(options, FETCH_TEXT_TIMEOUT_MS, async (reading) => new TextDecoder().decode(await download(url, TEXT_LIMIT_BYTES, reading)));
|
|
135
|
+
},
|
|
136
|
+
async fetchBytes(url, options = {}) {
|
|
137
|
+
return remoteRead(options, FETCH_BYTES_TIMEOUT_MS, reading => download(url, DOWNLOAD_LIMIT_BYTES, reading, true));
|
|
138
|
+
},
|
|
139
|
+
async userPathContains(directory, options = {}) {
|
|
140
|
+
if (pathIncludes(inheritedPath, directory))
|
|
141
|
+
return true;
|
|
142
|
+
const target = userPathProfile(environment, directory);
|
|
143
|
+
if (process.platform !== 'win32')
|
|
144
|
+
return (await read(target.profile))?.split(/\r?\n/).includes(target.line) ?? false;
|
|
145
|
+
const script = "$ErrorActionPreference='Stop'; $entry=$env:CCW_PATH_ENTRY; $parts=@(([Environment]::GetEnvironmentVariable('Path','User') + ';' + [Environment]::GetEnvironmentVariable('Path','Machine')) -split ';' | Where-Object { $_ }); if ($parts | Where-Object { $_.TrimEnd('\\') -ieq $entry.TrimEnd('\\') }) { 'true' } else { 'false' }";
|
|
146
|
+
const result = await this.execute('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
147
|
+
...options,
|
|
148
|
+
timeoutMs: options.timeoutMs ?? READ_COMMAND_TIMEOUT_MS,
|
|
149
|
+
env: { CCW_PATH_ENTRY: directory },
|
|
150
|
+
});
|
|
151
|
+
if (!succeeded(result) || !['true', 'false'].includes(result.stdout.trim()))
|
|
152
|
+
throw new Error('user-path-unconfirmed');
|
|
153
|
+
return result.stdout.trim() === 'true';
|
|
154
|
+
},
|
|
155
|
+
async ensureUserPath(directory) {
|
|
156
|
+
const separator = path.delimiter;
|
|
157
|
+
const current = environment.PATH ?? '';
|
|
158
|
+
if (pathIncludes(current, directory))
|
|
159
|
+
return;
|
|
160
|
+
const home = process.platform === 'win32'
|
|
161
|
+
? (environment.USERPROFILE ?? environment.HOME)
|
|
162
|
+
: (environment.HOME ?? environment.USERPROFILE);
|
|
163
|
+
if (!home || !path.isAbsolute(home))
|
|
164
|
+
throw new Error('user-home-unconfirmed');
|
|
165
|
+
if (process.platform === 'win32') {
|
|
166
|
+
const script = "$ErrorActionPreference='Stop'; $entry=$env:CCW_PATH_ENTRY; $current=[Environment]::GetEnvironmentVariable('Path','User'); $parts=@($current -split ';' | Where-Object { $_ }); if (-not ($parts | Where-Object { $_.TrimEnd('\\') -ieq $entry.TrimEnd('\\') })) { [Environment]::SetEnvironmentVariable('Path', (($parts + $entry) -join ';'), 'User') }";
|
|
167
|
+
const result = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { ...environment, CCW_PATH_ENTRY: directory }, cwd);
|
|
168
|
+
if (!succeeded(result))
|
|
169
|
+
throw new Error('user-path-save-failed');
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
const { profile, line } = userPathProfile(environment, directory);
|
|
173
|
+
const before = await read(profile);
|
|
174
|
+
if (!before?.split(/\r?\n/).includes(line)) {
|
|
175
|
+
const expected = before === null ? null : createHash('sha256').update(before).digest('hex');
|
|
176
|
+
await replaceFile(profile, Buffer.from(`${before ?? ''}${before?.endsWith('\n') || !before ? '' : '\n'}${line}\n`), expected);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const updated = `${directory}${current ? separator + current : ''}`;
|
|
180
|
+
environment.PATH = updated;
|
|
181
|
+
},
|
|
182
|
+
async replaceTree(directory, files, expected, preserveAt) {
|
|
183
|
+
await prepareParent(directory);
|
|
184
|
+
const staged = `${directory}.${randomUUID()}.tmp`;
|
|
185
|
+
await fs.mkdir(staged, { mode: 0o700 });
|
|
186
|
+
try {
|
|
187
|
+
for (const file of files) {
|
|
188
|
+
const target = relativeFile(staged, file.path);
|
|
189
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
190
|
+
await fs.writeFile(target, file.data, { flag: 'wx', mode: 0o600 });
|
|
191
|
+
}
|
|
192
|
+
if ((await treeStamp(directory)) !== expected)
|
|
193
|
+
throw new Error('target-changed');
|
|
194
|
+
if (expected !== null)
|
|
195
|
+
await removeTree(directory, expected, preserveAt);
|
|
196
|
+
await fs.rename(staged, directory);
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
await fs.rm(staged, { recursive: true, force: true });
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
async source(repository, revision, subdirectory, options = {}) {
|
|
203
|
+
return remoteRead(options, SOURCE_TIMEOUT_MS, async (reading) => {
|
|
204
|
+
if (!/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+(?:\.git)?$/.test(repository) || !isGitRevision(revision))
|
|
205
|
+
throw new Error('invalid-source');
|
|
206
|
+
const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'ccw-source-'));
|
|
207
|
+
const git = async (args) => {
|
|
208
|
+
reading.check();
|
|
209
|
+
const result = await this.execute('git', ['-c', 'core.hooksPath=/dev/null', ...args], {
|
|
210
|
+
env: { GIT_TERMINAL_PROMPT: '0' },
|
|
211
|
+
cwd: temporary,
|
|
212
|
+
signal: reading.signal,
|
|
213
|
+
timeoutMs: options.timeoutMs ?? SOURCE_TIMEOUT_MS,
|
|
214
|
+
});
|
|
215
|
+
reading.check();
|
|
216
|
+
if (!succeeded(result))
|
|
217
|
+
throw new Error('source-unavailable');
|
|
218
|
+
return result.stdout;
|
|
219
|
+
};
|
|
220
|
+
try {
|
|
221
|
+
const root = subdirectory === '.' ? temporary : relativeFile(temporary, subdirectory);
|
|
222
|
+
await git(['init', '--quiet']);
|
|
223
|
+
if (subdirectory !== '.')
|
|
224
|
+
await git(['sparse-checkout', 'set', '--cone', subdirectory]);
|
|
225
|
+
await git([
|
|
226
|
+
'-c',
|
|
227
|
+
'protocol.version=2',
|
|
228
|
+
'fetch',
|
|
229
|
+
'--quiet',
|
|
230
|
+
'--filter=blob:none',
|
|
231
|
+
'--depth=1',
|
|
232
|
+
repository,
|
|
233
|
+
revision,
|
|
234
|
+
]);
|
|
235
|
+
await git(['checkout', '--quiet', '--detach', 'FETCH_HEAD']);
|
|
236
|
+
const files = [];
|
|
237
|
+
let sizeBytes = 0;
|
|
238
|
+
const collect = async (directory) => {
|
|
239
|
+
reading.check();
|
|
240
|
+
for (const entry of await entries(directory)) {
|
|
241
|
+
reading.check();
|
|
242
|
+
if (directory === temporary && entry.name === '.git')
|
|
243
|
+
continue;
|
|
244
|
+
const file = path.join(directory, entry.name);
|
|
245
|
+
if (entry.kind === 'link')
|
|
246
|
+
throw new Error('source-link-unsupported');
|
|
247
|
+
if (entry.kind === 'directory')
|
|
248
|
+
await collect(file);
|
|
249
|
+
else {
|
|
250
|
+
sizeBytes += Number(entry.sizeBytes);
|
|
251
|
+
if (sizeBytes > SOURCE_LIMIT_BYTES)
|
|
252
|
+
throw new Error('source-too-large');
|
|
253
|
+
files.push({
|
|
254
|
+
path: path.relative(root, file).split(path.sep).join('/'),
|
|
255
|
+
data: await fs.readFile(file, { signal: reading.signal }),
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
await collect(root);
|
|
261
|
+
if (files.length === 0)
|
|
262
|
+
throw new Error('source-empty');
|
|
263
|
+
return files;
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
await fs.rm(temporary, { recursive: true, force: true });
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
},
|
|
270
|
+
async initialize(file, text) {
|
|
271
|
+
await prepareParent(file);
|
|
272
|
+
try {
|
|
273
|
+
await fs.writeFile(file, text, { flag: 'wx', mode: 0o600 });
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
if (errorCode(error) === 'EEXIST') {
|
|
278
|
+
await fileStat(file);
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
npmIdentity: resolveNpm,
|
|
285
|
+
async npm(args, options) {
|
|
286
|
+
try {
|
|
287
|
+
const tool = await resolveNpm(options?.signal);
|
|
288
|
+
return await run(process.execPath, [tool.binary, ...args], { ...environment, ...normalizeEnvironment(options?.env ?? {}) }, options?.cwd ?? cwd, options);
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
if (errorCode(error) === 'npm-changed')
|
|
292
|
+
throw error;
|
|
293
|
+
return {
|
|
294
|
+
code: null,
|
|
295
|
+
stdout: '',
|
|
296
|
+
failed: true,
|
|
297
|
+
...(errorCode(error) === 'npm-not-found' ? { reason: 'npm-not-found' } : {}),
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
},
|
|
46
301
|
};
|
|
47
|
-
try {
|
|
48
|
-
check();
|
|
49
|
-
const result = await read({ signal, check });
|
|
50
|
-
check();
|
|
51
|
-
return result;
|
|
52
|
-
}
|
|
53
|
-
catch (error) {
|
|
54
|
-
check();
|
|
55
|
-
throw error;
|
|
56
|
-
}
|
|
57
|
-
finally {
|
|
58
|
-
clearTimeout(timer);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
async function download(url, maximumBytes, reading, needsBody = false) {
|
|
62
|
-
if (new URL(url).protocol !== 'https:')
|
|
63
|
-
throw new Error('invalid-source-url');
|
|
64
|
-
reading.check();
|
|
65
|
-
const response = await fetch(url, { signal: reading.signal });
|
|
66
|
-
try {
|
|
67
|
-
reading.check();
|
|
68
|
-
}
|
|
69
|
-
catch (error) {
|
|
70
|
-
await response.body?.cancel().catch(() => undefined);
|
|
71
|
-
throw error;
|
|
72
|
-
}
|
|
73
|
-
const problem = new URL(response.url || url).protocol !== 'https:'
|
|
74
|
-
? 'invalid-source-url'
|
|
75
|
-
: !response.ok || (needsBody && !response.body)
|
|
76
|
-
? 'source-unavailable'
|
|
77
|
-
: Number(response.headers.get('content-length')) > maximumBytes
|
|
78
|
-
? 'source-too-large'
|
|
79
|
-
: undefined;
|
|
80
|
-
if (problem) {
|
|
81
|
-
await response.body?.cancel().catch(() => undefined);
|
|
82
|
-
throw new Error(problem);
|
|
83
|
-
}
|
|
84
|
-
const chunks = [];
|
|
85
|
-
let sizeBytes = 0;
|
|
86
|
-
if (response.body)
|
|
87
|
-
for await (const chunk of response.body) {
|
|
88
|
-
reading.check();
|
|
89
|
-
sizeBytes += chunk.byteLength;
|
|
90
|
-
if (sizeBytes > maximumBytes)
|
|
91
|
-
throw new Error('source-too-large');
|
|
92
|
-
chunks.push(chunk);
|
|
93
|
-
}
|
|
94
|
-
reading.check();
|
|
95
|
-
return Buffer.concat(chunks, sizeBytes);
|
|
96
302
|
}
|
|
97
|
-
/**
|
|
303
|
+
/**
|
|
304
|
+
* 按 treeStamp 的目录规则计算文件集合摘要
|
|
305
|
+
*
|
|
306
|
+
* @param files - 使用斜杠分隔的相对路径,不得重复或形成文件与目录冲突
|
|
307
|
+
* @returns 部署这些文件后可用于核验的 SHA-256 目录摘要
|
|
308
|
+
* @throws Error - 路径为空、越界、含禁用片段、重复或冲突时抛出 invalid-source-path
|
|
309
|
+
*/
|
|
98
310
|
export function treeFilesStamp(files) {
|
|
99
311
|
const root = new Map();
|
|
100
312
|
for (const file of files) {
|
|
@@ -129,209 +341,59 @@ export function treeFilesStamp(files) {
|
|
|
129
341
|
}
|
|
130
342
|
return hash.digest('hex');
|
|
131
343
|
};
|
|
132
|
-
return stamp(root);
|
|
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
|
-
const
|
|
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
|
-
try {
|
|
186
|
-
const before = await read(file);
|
|
187
|
-
const value = before === null ? {} : JSON.parse(before);
|
|
188
|
-
if (!isObject(value))
|
|
189
|
-
throw new Error('invalid-settings');
|
|
190
|
-
edit(value);
|
|
191
|
-
const stat = await fileStat(file);
|
|
192
|
-
await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx', mode: stat?.mode ?? 0o600 });
|
|
193
|
-
if ((await read(file)) !== before)
|
|
194
|
-
throw new Error('settings-changed');
|
|
195
|
-
await fs.rename(temporary, file);
|
|
196
|
-
}
|
|
197
|
-
finally {
|
|
198
|
-
await fs.rm(temporary, { force: true });
|
|
199
|
-
await lock.close();
|
|
200
|
-
await fs.unlink(lockPath);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
function normalizeEnvironment(environment) {
|
|
204
|
-
if (process.platform !== 'win32')
|
|
205
|
-
return { ...environment };
|
|
206
|
-
const normalized = {};
|
|
207
|
-
// 与 Node 的重复键优先级一致;调用选项在归一后覆盖已有环境
|
|
208
|
-
for (const key of Object.keys(environment).sort()) {
|
|
209
|
-
const name = key.toUpperCase();
|
|
210
|
-
if (!Object.hasOwn(normalized, name))
|
|
211
|
-
normalized[name] = environment[key];
|
|
212
|
-
}
|
|
213
|
-
return normalized;
|
|
214
|
-
}
|
|
215
|
-
async function npmPath(environment) {
|
|
216
|
-
const candidates = [
|
|
217
|
-
environment[process.platform === 'win32' ? 'NPM_EXECPATH' : 'npm_execpath'],
|
|
218
|
-
path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
|
|
219
|
-
];
|
|
220
|
-
for (const directory of (environment.PATH ?? '').split(path.delimiter)) {
|
|
221
|
-
candidates.push(path.join(directory, 'node_modules/npm/bin/npm-cli.js'));
|
|
222
|
-
if (process.platform !== 'win32') {
|
|
223
|
-
try {
|
|
224
|
-
candidates.push(await fs.realpath(path.join(directory, 'npm')));
|
|
225
|
-
}
|
|
226
|
-
catch {
|
|
227
|
-
// 不可解析的 PATH 位置跳过,继续收集
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
for (const candidate of candidates) {
|
|
232
|
-
if (candidate?.endsWith('npm-cli.js') && (await fileStat(candidate)) !== null)
|
|
233
|
-
return candidate;
|
|
234
|
-
}
|
|
235
|
-
throw new Error('npm-not-found');
|
|
236
|
-
}
|
|
237
|
-
/** 执行结构化命令,不经过 shell;输出有上限,超时不报告成功 */
|
|
238
|
-
async function run(executable, args, environment, cwd, options = {}) {
|
|
239
|
-
if (options.signal?.aborted)
|
|
240
|
-
return { code: null, stdout: '', failed: true };
|
|
241
|
-
if (process.platform === 'win32') {
|
|
242
|
-
if (path.extname(executable).toLowerCase() === '.ps1' || executable === 'scoop') {
|
|
243
|
-
const candidates = executable === 'scoop'
|
|
244
|
-
? (environment.PATH ?? '')
|
|
245
|
-
.split(path.delimiter)
|
|
246
|
-
.filter(Boolean)
|
|
247
|
-
.map(directory => path.join(directory, 'scoop.ps1'))
|
|
248
|
-
: [executable];
|
|
249
|
-
for (const candidate of candidates)
|
|
250
|
-
if ((await fileStat(candidate)) !== null)
|
|
251
|
-
return run('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', candidate, ...args], environment, cwd, options);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
return new Promise(resolve => {
|
|
255
|
-
const child = spawn(executable, [...args], {
|
|
256
|
-
cwd,
|
|
257
|
-
env: environment,
|
|
258
|
-
windowsHide: true,
|
|
259
|
-
detached: process.platform !== 'win32' && !options.isInteractive,
|
|
260
|
-
stdio: options.isInteractive ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
|
261
|
-
});
|
|
262
|
-
let stdout = '';
|
|
263
|
-
let sizeBytes = 0;
|
|
264
|
-
let hasFailed = false;
|
|
265
|
-
let isStopping = false;
|
|
266
|
-
const decoder = new StringDecoder('utf8');
|
|
267
|
-
let forceStop;
|
|
268
|
-
const stop = () => {
|
|
269
|
-
hasFailed = true;
|
|
270
|
-
if (isStopping || child.pid === undefined)
|
|
271
|
-
return;
|
|
272
|
-
isStopping = true;
|
|
273
|
-
// Git 的 HTTP helper 继承输出管道;只杀父进程无法结束等待
|
|
274
|
-
if (process.platform === 'win32') {
|
|
275
|
-
const killer = spawn(path.join(process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows', 'System32/taskkill.exe'), ['/PID', `${child.pid}`, '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
276
|
-
killer.once('error', () => {
|
|
277
|
-
child.kill();
|
|
278
|
-
});
|
|
279
|
-
killer.once('close', code => {
|
|
280
|
-
if (code !== 0)
|
|
281
|
-
child.kill();
|
|
282
|
-
});
|
|
283
|
-
}
|
|
284
|
-
else if (!options.isInteractive) {
|
|
285
|
-
const pid = child.pid;
|
|
286
|
-
try {
|
|
287
|
-
process.kill(-pid, 'SIGTERM');
|
|
288
|
-
forceStop = setTimeout(() => {
|
|
289
|
-
try {
|
|
290
|
-
process.kill(-pid, 'SIGKILL');
|
|
291
|
-
}
|
|
292
|
-
catch {
|
|
293
|
-
child.kill('SIGKILL');
|
|
294
|
-
}
|
|
295
|
-
}, 250);
|
|
296
|
-
}
|
|
297
|
-
catch {
|
|
298
|
-
child.kill('SIGKILL');
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
else {
|
|
302
|
-
// 交互命令共享终端进程组,只终止所选子进程
|
|
303
|
-
child.kill();
|
|
304
|
-
forceStop = setTimeout(() => {
|
|
305
|
-
child.kill('SIGKILL');
|
|
306
|
-
}, 250);
|
|
307
|
-
}
|
|
308
|
-
};
|
|
309
|
-
const timer = setTimeout(stop, options.timeoutMs ?? (options.isInteractive ? 900_000 : 300_000));
|
|
310
|
-
options.signal?.addEventListener('abort', stop, { once: true });
|
|
311
|
-
if (options.signal?.aborted)
|
|
312
|
-
stop();
|
|
313
|
-
child.stdout?.on('data', (chunk) => {
|
|
314
|
-
sizeBytes += chunk.length;
|
|
315
|
-
if (sizeBytes > OUTPUT_LIMIT_BYTES)
|
|
316
|
-
stop();
|
|
317
|
-
else
|
|
318
|
-
stdout += decoder.write(chunk);
|
|
319
|
-
});
|
|
320
|
-
child.stderr?.on('data', () => {
|
|
321
|
-
/* 不向结果或日志暴露外部配置及凭据 */
|
|
322
|
-
});
|
|
323
|
-
child.once('error', () => {
|
|
324
|
-
hasFailed = true;
|
|
325
|
-
});
|
|
326
|
-
child.once('close', code => {
|
|
327
|
-
if (sizeBytes <= OUTPUT_LIMIT_BYTES)
|
|
328
|
-
stdout += decoder.end();
|
|
329
|
-
clearTimeout(timer);
|
|
330
|
-
clearTimeout(forceStop);
|
|
331
|
-
options.signal?.removeEventListener('abort', stop);
|
|
332
|
-
resolve({ code, stdout, failed: hasFailed });
|
|
333
|
-
});
|
|
334
|
-
});
|
|
344
|
+
return stamp(root);
|
|
345
|
+
}
|
|
346
|
+
/** 仅在未标记失败且退出码为零时确认命令成功 */
|
|
347
|
+
export function succeeded(result) {
|
|
348
|
+
return !(result.failed || result.code !== 0);
|
|
349
|
+
}
|
|
350
|
+
/** 提取字符串 code 或符合错误码形状的 Error.message,否则返回 operation-failed */
|
|
351
|
+
export function errorCode(error) {
|
|
352
|
+
if (isObject(error) && typeof error.code === 'string')
|
|
353
|
+
return error.code;
|
|
354
|
+
if (error instanceof Error && /^[a-z][a-z-]+$/.test(error.message))
|
|
355
|
+
return error.message;
|
|
356
|
+
return 'operation-failed';
|
|
357
|
+
}
|
|
358
|
+
/** 判断值是否为非 null、非数组对象,不验证原型或属性内容 */
|
|
359
|
+
export function isObject(value) {
|
|
360
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
361
|
+
}
|
|
362
|
+
async function read(file) {
|
|
363
|
+
const stat = await fileStat(file);
|
|
364
|
+
if (stat === null)
|
|
365
|
+
return null;
|
|
366
|
+
if (stat.size > FILE_LIMIT_BYTES)
|
|
367
|
+
throw new Error('file-too-large');
|
|
368
|
+
return fs.readFile(file, 'utf8');
|
|
369
|
+
}
|
|
370
|
+
async function fingerprint(file, signal) {
|
|
371
|
+
signal?.throwIfAborted();
|
|
372
|
+
const stat = await fileStat(file);
|
|
373
|
+
if (stat === null)
|
|
374
|
+
return null;
|
|
375
|
+
const hash = createHash('sha256');
|
|
376
|
+
await pipeline(createReadStream(file), hash, { signal });
|
|
377
|
+
return hash.digest('hex');
|
|
378
|
+
}
|
|
379
|
+
async function editJson(file, edit) {
|
|
380
|
+
await prepareParent(file);
|
|
381
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
382
|
+
try {
|
|
383
|
+
const before = await read(file);
|
|
384
|
+
const value = before === null ? {} : JSON.parse(before);
|
|
385
|
+
if (!isObject(value))
|
|
386
|
+
throw new Error('invalid-settings');
|
|
387
|
+
edit(value);
|
|
388
|
+
const stat = await fileStat(file);
|
|
389
|
+
await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx', mode: stat?.mode ?? 0o600 });
|
|
390
|
+
if ((await read(file)) !== before)
|
|
391
|
+
throw new Error('settings-changed');
|
|
392
|
+
await fs.rename(temporary, file);
|
|
393
|
+
}
|
|
394
|
+
finally {
|
|
395
|
+
await fs.rm(temporary, { force: true });
|
|
396
|
+
}
|
|
335
397
|
}
|
|
336
398
|
async function entries(directory) {
|
|
337
399
|
try {
|
|
@@ -394,15 +456,6 @@ async function removeTree(file, expected, preserveAt) {
|
|
|
394
456
|
if ((await treeStamp(file)) !== null)
|
|
395
457
|
throw new Error('target-remains');
|
|
396
458
|
}
|
|
397
|
-
function relativeFile(root, relative) {
|
|
398
|
-
const result = path.resolve(root, relative);
|
|
399
|
-
if (!result.startsWith(`${path.resolve(root)}${path.sep}`) ||
|
|
400
|
-
relative.includes('\\') ||
|
|
401
|
-
relative.split('/').some(part => part === '.' || part === '..' || part === '.git') ||
|
|
402
|
-
path.isAbsolute(relative))
|
|
403
|
-
throw new Error('invalid-source-path');
|
|
404
|
-
return result;
|
|
405
|
-
}
|
|
406
459
|
async function replaceFile(file, data, expected, shouldMarkExecutable = false) {
|
|
407
460
|
await prepareParent(file);
|
|
408
461
|
const stat = await fileStat(file);
|
|
@@ -410,10 +463,18 @@ async function replaceFile(file, data, expected, shouldMarkExecutable = false) {
|
|
|
410
463
|
throw new Error('target-changed');
|
|
411
464
|
const staged = `${file}.${randomUUID()}.tmp`;
|
|
412
465
|
try {
|
|
413
|
-
await fs.
|
|
466
|
+
const output = await fs.open(staged, 'wx', shouldMarkExecutable ? 0o755 : (stat?.mode ?? 0o600));
|
|
467
|
+
try {
|
|
468
|
+
await output.writeFile(data);
|
|
469
|
+
await output.sync();
|
|
470
|
+
}
|
|
471
|
+
finally {
|
|
472
|
+
await output.close();
|
|
473
|
+
}
|
|
414
474
|
if ((await fingerprint(file)) !== expected)
|
|
415
475
|
throw new Error('target-changed');
|
|
416
476
|
await fs.rename(staged, file);
|
|
477
|
+
await syncParentDirectory(file);
|
|
417
478
|
if ((await fingerprint(file)) !== createHash('sha256').update(data).digest('hex'))
|
|
418
479
|
throw new Error('target-changed');
|
|
419
480
|
}
|
|
@@ -421,298 +482,277 @@ async function replaceFile(file, data, expected, shouldMarkExecutable = false) {
|
|
|
421
482
|
await fs.rm(staged, { force: true });
|
|
422
483
|
}
|
|
423
484
|
}
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
const
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
npmTool = undefined;
|
|
437
|
-
throw error;
|
|
438
|
-
});
|
|
439
|
-
return npmTool;
|
|
485
|
+
/** 统一远端读取的总期限、取消与迟到结果 */
|
|
486
|
+
async function remoteRead(options, timeoutMs, read) {
|
|
487
|
+
const timeout = new AbortController();
|
|
488
|
+
const timer = setTimeout(() => {
|
|
489
|
+
timeout.abort();
|
|
490
|
+
}, options.timeoutMs ?? timeoutMs);
|
|
491
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout.signal]) : timeout.signal;
|
|
492
|
+
const check = () => {
|
|
493
|
+
if (options.signal?.aborted)
|
|
494
|
+
throw new Error('cancelled');
|
|
495
|
+
if (timeout.signal.aborted)
|
|
496
|
+
throw new Error('source-timeout');
|
|
440
497
|
};
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
if (
|
|
480
|
-
throw new Error('
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
'-NonInteractive',
|
|
507
|
-
'-Command',
|
|
508
|
-
"$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Select-Object Name,CommandLine) | ConvertTo-Json -Compress",
|
|
509
|
-
], options)
|
|
510
|
-
: await this.execute('ps', ['-A', '-o', 'comm=', '-o', 'args='], options);
|
|
511
|
-
if (!succeeded(result))
|
|
512
|
-
return null;
|
|
513
|
-
if (process.platform !== 'win32')
|
|
514
|
-
return result.stdout.split('\n').flatMap(line => {
|
|
515
|
-
const match = /^(\S+)\s+(.*)$/.exec(line.trim());
|
|
516
|
-
return match === null ? [] : [{ name: match[1] ?? '', command: match[2] ?? '' }];
|
|
517
|
-
});
|
|
518
|
-
try {
|
|
519
|
-
const value = result.stdout.trim() ? JSON.parse(result.stdout) : [];
|
|
520
|
-
const list = Array.isArray(value) ? value : [value];
|
|
521
|
-
const found = [];
|
|
522
|
-
for (const entry of list) {
|
|
523
|
-
if (!isObject(entry) || typeof entry.Name !== 'string')
|
|
524
|
-
return null;
|
|
525
|
-
// 命令行不可读(如提权进程)按空串保留条目:名称可判定的进程不得因命令行缺失而漏报
|
|
526
|
-
found.push({ name: entry.Name, command: typeof entry.CommandLine === 'string' ? entry.CommandLine : '' });
|
|
527
|
-
}
|
|
528
|
-
return found;
|
|
529
|
-
}
|
|
530
|
-
catch {
|
|
531
|
-
return null;
|
|
532
|
-
}
|
|
533
|
-
},
|
|
534
|
-
async fetchText(url, options = {}) {
|
|
535
|
-
return remoteRead(options, FETCH_TEXT_TIMEOUT_MS, async (reading) => new TextDecoder().decode(await download(url, TEXT_LIMIT_BYTES, reading)));
|
|
536
|
-
},
|
|
537
|
-
async fetchBytes(url, options = {}) {
|
|
538
|
-
return remoteRead(options, FETCH_BYTES_TIMEOUT_MS, reading => download(url, DOWNLOAD_LIMIT_BYTES, reading, true));
|
|
539
|
-
},
|
|
540
|
-
async ensureUserPath(directory) {
|
|
541
|
-
if (!path.isAbsolute(directory) ||
|
|
542
|
-
path.parse(directory).root === path.resolve(directory) ||
|
|
543
|
-
/[\r\n\0]/.test(directory))
|
|
544
|
-
throw new Error('invalid-target');
|
|
545
|
-
const separator = path.delimiter;
|
|
546
|
-
const current = environment.PATH ?? '';
|
|
547
|
-
const same = (value) => process.platform === 'win32'
|
|
548
|
-
? path.resolve(value).toLowerCase() === path.resolve(directory).toLowerCase()
|
|
549
|
-
: value === directory;
|
|
550
|
-
if (current.split(separator).filter(Boolean).some(same))
|
|
551
|
-
return;
|
|
552
|
-
const home = process.platform === 'win32'
|
|
553
|
-
? (environment.USERPROFILE ?? environment.HOME)
|
|
554
|
-
: (environment.HOME ?? environment.USERPROFILE);
|
|
555
|
-
if (!home || !path.isAbsolute(home))
|
|
556
|
-
throw new Error('user-home-unconfirmed');
|
|
557
|
-
if (process.platform === 'win32') {
|
|
558
|
-
const script = "$ErrorActionPreference='Stop'; $entry=$env:CCW_PATH_ENTRY; $current=[Environment]::GetEnvironmentVariable('Path','User'); $parts=@($current -split ';' | Where-Object { $_ }); if (-not ($parts | Where-Object { $_.TrimEnd('\\') -ieq $entry.TrimEnd('\\') })) { [Environment]::SetEnvironmentVariable('Path', (($parts + $entry) -join ';'), 'User') }";
|
|
559
|
-
const result = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { ...environment, CCW_PATH_ENTRY: directory }, cwd);
|
|
560
|
-
if (!succeeded(result))
|
|
561
|
-
throw new Error('user-path-save-failed');
|
|
562
|
-
}
|
|
563
|
-
else {
|
|
564
|
-
const shell = path.basename(environment.SHELL ?? '');
|
|
565
|
-
const shellRoot = shell === 'zsh'
|
|
566
|
-
? (environment.ZDOTDIR ?? home)
|
|
567
|
-
: shell === 'fish'
|
|
568
|
-
? environment.XDG_CONFIG_HOME || path.join(home, '.config')
|
|
569
|
-
: home;
|
|
570
|
-
if (!path.isAbsolute(shellRoot))
|
|
571
|
-
throw new Error('user-home-unconfirmed');
|
|
572
|
-
const profile = path.join(shellRoot, shell === 'fish'
|
|
573
|
-
? 'fish/config.fish'
|
|
574
|
-
: shell === 'zsh'
|
|
575
|
-
? '.zshrc'
|
|
576
|
-
: shell === 'bash'
|
|
577
|
-
? '.bashrc'
|
|
578
|
-
: '.profile');
|
|
579
|
-
const quoted = `'${directory.replaceAll("'", "'\\''")}'`;
|
|
580
|
-
const line = shell === 'fish' ? `fish_add_path -- ${quoted}` : `export PATH=${quoted}:"$PATH"`;
|
|
581
|
-
const before = await read(profile);
|
|
582
|
-
if (!before?.split(/\r?\n/).includes(line)) {
|
|
583
|
-
const expected = before === null ? null : createHash('sha256').update(before).digest('hex');
|
|
584
|
-
await replaceFile(profile, Buffer.from(`${before ?? ''}${before?.endsWith('\n') || !before ? '' : '\n'}${line}\n`), expected);
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
const updated = `${directory}${current ? separator + current : ''}`;
|
|
588
|
-
environment.PATH = updated;
|
|
589
|
-
},
|
|
590
|
-
async replaceTree(directory, files, expected, preserveAt) {
|
|
591
|
-
await prepareParent(directory);
|
|
592
|
-
const staged = `${directory}.${randomUUID()}.tmp`;
|
|
593
|
-
await fs.mkdir(staged, { mode: 0o700 });
|
|
498
|
+
try {
|
|
499
|
+
check();
|
|
500
|
+
return await read({ signal, check });
|
|
501
|
+
}
|
|
502
|
+
finally {
|
|
503
|
+
clearTimeout(timer);
|
|
504
|
+
check();
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async function download(url, maximumBytes, reading, needsBody = false) {
|
|
508
|
+
if (new URL(url).protocol !== 'https:')
|
|
509
|
+
throw new Error('invalid-source-url');
|
|
510
|
+
reading.check();
|
|
511
|
+
const response = await fetch(url, { signal: reading.signal });
|
|
512
|
+
try {
|
|
513
|
+
reading.check();
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
await response.body?.cancel().catch(() => undefined);
|
|
517
|
+
throw error;
|
|
518
|
+
}
|
|
519
|
+
const problem = new URL(response.url || url).protocol !== 'https:'
|
|
520
|
+
? 'invalid-source-url'
|
|
521
|
+
: !response.ok || (needsBody && !response.body)
|
|
522
|
+
? 'source-unavailable'
|
|
523
|
+
: Number(response.headers.get('content-length')) > maximumBytes
|
|
524
|
+
? 'source-too-large'
|
|
525
|
+
: undefined;
|
|
526
|
+
if (problem) {
|
|
527
|
+
await response.body?.cancel().catch(() => undefined);
|
|
528
|
+
throw new Error(problem);
|
|
529
|
+
}
|
|
530
|
+
const chunks = [];
|
|
531
|
+
let sizeBytes = 0;
|
|
532
|
+
if (response.body)
|
|
533
|
+
for await (const chunk of response.body) {
|
|
534
|
+
reading.check();
|
|
535
|
+
sizeBytes += chunk.byteLength;
|
|
536
|
+
if (sizeBytes > maximumBytes)
|
|
537
|
+
throw new Error('source-too-large');
|
|
538
|
+
chunks.push(chunk);
|
|
539
|
+
}
|
|
540
|
+
reading.check();
|
|
541
|
+
return Buffer.concat(chunks, sizeBytes);
|
|
542
|
+
}
|
|
543
|
+
function normalizeEnvironment(environment) {
|
|
544
|
+
if (process.platform !== 'win32')
|
|
545
|
+
return { ...environment };
|
|
546
|
+
const normalized = {};
|
|
547
|
+
// 与 Node 的重复键优先级一致;调用选项在归一后覆盖已有环境
|
|
548
|
+
for (const key of Object.keys(environment).sort()) {
|
|
549
|
+
const name = key.toUpperCase();
|
|
550
|
+
if (!Object.hasOwn(normalized, name))
|
|
551
|
+
normalized[name] = environment[key];
|
|
552
|
+
}
|
|
553
|
+
return normalized;
|
|
554
|
+
}
|
|
555
|
+
async function npmPath(environment) {
|
|
556
|
+
const candidates = [
|
|
557
|
+
environment[process.platform === 'win32' ? 'NPM_EXECPATH' : 'npm_execpath'],
|
|
558
|
+
path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
|
|
559
|
+
];
|
|
560
|
+
for (const directory of (environment.PATH ?? '').split(path.delimiter)) {
|
|
561
|
+
candidates.push(path.join(directory, 'node_modules/npm/bin/npm-cli.js'));
|
|
562
|
+
if (process.platform !== 'win32') {
|
|
594
563
|
try {
|
|
595
|
-
|
|
596
|
-
const target = relativeFile(staged, file.path);
|
|
597
|
-
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
598
|
-
await fs.writeFile(target, file.data, { flag: 'wx', mode: 0o600 });
|
|
599
|
-
}
|
|
600
|
-
if ((await treeStamp(directory)) !== expected)
|
|
601
|
-
throw new Error('target-changed');
|
|
602
|
-
if (expected !== null)
|
|
603
|
-
await removeTree(directory, expected, preserveAt);
|
|
604
|
-
await fs.rename(staged, directory);
|
|
564
|
+
candidates.push(await fs.realpath(path.join(directory, 'npm')));
|
|
605
565
|
}
|
|
606
|
-
|
|
607
|
-
|
|
566
|
+
catch {
|
|
567
|
+
// 不可解析的 PATH 位置跳过,继续收集
|
|
608
568
|
}
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
for (const candidate of candidates) {
|
|
572
|
+
if (candidate?.endsWith('npm-cli.js') && (await fileStat(candidate)) !== null)
|
|
573
|
+
return candidate;
|
|
574
|
+
}
|
|
575
|
+
throw new Error('npm-not-found');
|
|
576
|
+
}
|
|
577
|
+
/** 执行结构化命令,不经过 shell;输出有上限,超时不报告成功 */
|
|
578
|
+
async function run(executable, args, environment, cwd, options = {}) {
|
|
579
|
+
if (options.signal?.aborted)
|
|
580
|
+
return { code: null, stdout: '', failed: true };
|
|
581
|
+
if (process.platform === 'win32') {
|
|
582
|
+
if (path.extname(executable).toLowerCase() === '.ps1' || executable === 'scoop') {
|
|
583
|
+
const candidates = executable === 'scoop'
|
|
584
|
+
? (environment.PATH ?? '')
|
|
585
|
+
.split(path.delimiter)
|
|
586
|
+
.filter(Boolean)
|
|
587
|
+
.map(directory => path.join(directory, 'scoop.ps1'))
|
|
588
|
+
: [executable];
|
|
589
|
+
for (const candidate of candidates)
|
|
590
|
+
if ((await fileStat(candidate)) !== null)
|
|
591
|
+
return run('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', candidate, ...args], environment, cwd, options);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return new Promise(resolve => {
|
|
595
|
+
const child = spawn(executable, args, {
|
|
596
|
+
cwd,
|
|
597
|
+
env: environment,
|
|
598
|
+
windowsHide: true,
|
|
599
|
+
detached: process.platform !== 'win32' && !options.isInteractive,
|
|
600
|
+
stdio: options.isInteractive ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
|
601
|
+
});
|
|
602
|
+
let stdout = '';
|
|
603
|
+
let sizeBytes = 0;
|
|
604
|
+
let hasFailed = false;
|
|
605
|
+
let isStopping = false;
|
|
606
|
+
const decoder = new StringDecoder('utf8');
|
|
607
|
+
let forceStop;
|
|
608
|
+
const stop = () => {
|
|
609
|
+
hasFailed = true;
|
|
610
|
+
if (isStopping || child.pid === undefined)
|
|
611
|
+
return;
|
|
612
|
+
isStopping = true;
|
|
613
|
+
// Git 的 HTTP helper 继承输出管道;只杀父进程无法结束等待
|
|
614
|
+
if (process.platform === 'win32') {
|
|
615
|
+
const killer = spawn(path.join(process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows', 'System32/taskkill.exe'), ['/PID', `${child.pid}`, '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
616
|
+
killer.once('error', () => {
|
|
617
|
+
child.kill();
|
|
618
|
+
});
|
|
619
|
+
killer.once('close', code => {
|
|
620
|
+
if (code !== 0)
|
|
621
|
+
child.kill();
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
else if (!options.isInteractive) {
|
|
625
|
+
const pid = child.pid;
|
|
628
626
|
try {
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
'-c',
|
|
634
|
-
'protocol.version=2',
|
|
635
|
-
'fetch',
|
|
636
|
-
'--quiet',
|
|
637
|
-
'--filter=blob:none',
|
|
638
|
-
'--depth=1',
|
|
639
|
-
repository,
|
|
640
|
-
revision,
|
|
641
|
-
]);
|
|
642
|
-
await git(['checkout', '--quiet', '--detach', 'FETCH_HEAD']);
|
|
643
|
-
const files = [];
|
|
644
|
-
let sizeBytes = 0;
|
|
645
|
-
const collect = async (directory) => {
|
|
646
|
-
reading.check();
|
|
647
|
-
for (const entry of await entries(directory)) {
|
|
648
|
-
reading.check();
|
|
649
|
-
const file = path.join(directory, entry.name);
|
|
650
|
-
if (entry.kind === 'link')
|
|
651
|
-
throw new Error('source-link-unsupported');
|
|
652
|
-
if (entry.kind === 'directory')
|
|
653
|
-
await collect(file);
|
|
654
|
-
else {
|
|
655
|
-
sizeBytes += Number(entry.sizeBytes);
|
|
656
|
-
if (sizeBytes > SOURCE_LIMIT_BYTES)
|
|
657
|
-
throw new Error('source-too-large');
|
|
658
|
-
files.push({
|
|
659
|
-
path: path.relative(root, file).split(path.sep).join('/'),
|
|
660
|
-
data: await fs.readFile(file, { signal: reading.signal }),
|
|
661
|
-
});
|
|
662
|
-
}
|
|
627
|
+
process.kill(-pid, 'SIGTERM');
|
|
628
|
+
forceStop = setTimeout(() => {
|
|
629
|
+
try {
|
|
630
|
+
process.kill(-pid, 'SIGKILL');
|
|
663
631
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
return files;
|
|
669
|
-
}
|
|
670
|
-
finally {
|
|
671
|
-
await fs.rm(temporary, { recursive: true, force: true });
|
|
632
|
+
catch {
|
|
633
|
+
child.kill('SIGKILL');
|
|
634
|
+
}
|
|
635
|
+
}, FORCE_STOP_DELAY_MS);
|
|
672
636
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
async initialize(file, text) {
|
|
676
|
-
await prepareParent(file);
|
|
677
|
-
try {
|
|
678
|
-
await fs.writeFile(file, text, { flag: 'wx', mode: 0o600 });
|
|
679
|
-
return true;
|
|
680
|
-
}
|
|
681
|
-
catch (error) {
|
|
682
|
-
if (errorCode(error) === 'EEXIST') {
|
|
683
|
-
await fileStat(file);
|
|
684
|
-
return false;
|
|
637
|
+
catch {
|
|
638
|
+
child.kill('SIGKILL');
|
|
685
639
|
}
|
|
686
|
-
throw error;
|
|
687
|
-
}
|
|
688
|
-
},
|
|
689
|
-
async remove(file, expected) {
|
|
690
|
-
await prepareParent(file);
|
|
691
|
-
const current = await fingerprint(file);
|
|
692
|
-
if (current === null)
|
|
693
|
-
return;
|
|
694
|
-
if (current !== expected)
|
|
695
|
-
throw new Error('binary-changed');
|
|
696
|
-
await fs.unlink(file);
|
|
697
|
-
},
|
|
698
|
-
async npm(args, options) {
|
|
699
|
-
try {
|
|
700
|
-
const tool = await resolveNpm();
|
|
701
|
-
if ((await fs.realpath(tool.entry)) !== tool.binary ||
|
|
702
|
-
(await fingerprint(tool.binary, options?.signal)) !== tool.stamp)
|
|
703
|
-
throw new Error('npm-changed');
|
|
704
|
-
return await run(process.execPath, [tool.binary, ...args], environment, cwd, options);
|
|
705
640
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
failed: true,
|
|
713
|
-
...(errorCode(error) === 'npm-not-found' ? { reason: 'npm-not-found' } : {}),
|
|
714
|
-
};
|
|
641
|
+
else {
|
|
642
|
+
// 交互命令共享终端进程组,只终止所选子进程
|
|
643
|
+
child.kill();
|
|
644
|
+
forceStop = setTimeout(() => {
|
|
645
|
+
child.kill('SIGKILL');
|
|
646
|
+
}, FORCE_STOP_DELAY_MS);
|
|
715
647
|
}
|
|
716
|
-
}
|
|
717
|
-
|
|
648
|
+
};
|
|
649
|
+
const timer = setTimeout(stop, options.timeoutMs ?? (options.isInteractive ? INTERACTIVE_COMMAND_TIMEOUT_MS : COMMAND_TIMEOUT_MS));
|
|
650
|
+
options.signal?.addEventListener('abort', stop, { once: true });
|
|
651
|
+
if (options.signal?.aborted)
|
|
652
|
+
stop();
|
|
653
|
+
child.stdout?.on('data', (chunk) => {
|
|
654
|
+
sizeBytes += chunk.length;
|
|
655
|
+
if (sizeBytes > OUTPUT_LIMIT_BYTES)
|
|
656
|
+
stop();
|
|
657
|
+
else
|
|
658
|
+
stdout += decoder.write(chunk);
|
|
659
|
+
});
|
|
660
|
+
child.stderr?.on('data', () => {
|
|
661
|
+
/* 不向结果或日志暴露外部配置及凭据 */
|
|
662
|
+
});
|
|
663
|
+
child.once('error', () => {
|
|
664
|
+
hasFailed = true;
|
|
665
|
+
});
|
|
666
|
+
child.once('close', code => {
|
|
667
|
+
if (sizeBytes <= OUTPUT_LIMIT_BYTES)
|
|
668
|
+
stdout += decoder.end();
|
|
669
|
+
clearTimeout(timer);
|
|
670
|
+
clearTimeout(forceStop);
|
|
671
|
+
options.signal?.removeEventListener('abort', stop);
|
|
672
|
+
resolve({ code, stdout, failed: hasFailed });
|
|
673
|
+
});
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
/** 为已校验的目录生成用户 PATH 配置位置与写入行 */
|
|
677
|
+
function userPathProfile(environment, directory) {
|
|
678
|
+
const home = process.platform === 'win32'
|
|
679
|
+
? (environment.USERPROFILE ?? environment.HOME)
|
|
680
|
+
: (environment.HOME ?? environment.USERPROFILE);
|
|
681
|
+
if (!home || !path.isAbsolute(home))
|
|
682
|
+
throw new Error('user-home-unconfirmed');
|
|
683
|
+
const shell = path.basename(environment.SHELL ?? '');
|
|
684
|
+
const shellRoot = shell === 'zsh'
|
|
685
|
+
? (environment.ZDOTDIR ?? home)
|
|
686
|
+
: shell === 'fish'
|
|
687
|
+
? environment.XDG_CONFIG_HOME || path.join(home, '.config')
|
|
688
|
+
: home;
|
|
689
|
+
if (!path.isAbsolute(shellRoot))
|
|
690
|
+
throw new Error('user-home-unconfirmed');
|
|
691
|
+
const profile = path.join(shellRoot, shell === 'fish' ? 'fish/config.fish' : shell === 'zsh' ? '.zshrc' : shell === 'bash' ? '.bashrc' : '.profile');
|
|
692
|
+
const quoted = "'" + directory.replaceAll("'", "'\\''") + "'";
|
|
693
|
+
const line = shell === 'fish' ? 'fish_add_path -- ' + quoted : 'export PATH=' + quoted + ':"$PATH"';
|
|
694
|
+
return { profile, line };
|
|
695
|
+
}
|
|
696
|
+
/** 校验目标目录,并按平台规则检查 PATH 是否包含它 */
|
|
697
|
+
function pathIncludes(value, directory) {
|
|
698
|
+
if (!path.isAbsolute(directory) ||
|
|
699
|
+
path.parse(directory).root === path.resolve(directory) ||
|
|
700
|
+
/[\r\n\0]/.test(directory))
|
|
701
|
+
throw new Error('invalid-target');
|
|
702
|
+
return value
|
|
703
|
+
.split(path.delimiter)
|
|
704
|
+
.filter(Boolean)
|
|
705
|
+
.some(entry => process.platform === 'win32'
|
|
706
|
+
? path.resolve(entry).toLowerCase() === path.resolve(directory).toLowerCase()
|
|
707
|
+
: entry === directory);
|
|
708
|
+
}
|
|
709
|
+
function relativeFile(root, relative) {
|
|
710
|
+
const result = path.resolve(root, relative);
|
|
711
|
+
if (!result.startsWith(`${path.resolve(root)}${path.sep}`) ||
|
|
712
|
+
relative.includes('\\') ||
|
|
713
|
+
relative.split('/').some(part => part === '.' || part === '..' || part === '.git') ||
|
|
714
|
+
path.isAbsolute(relative))
|
|
715
|
+
throw new Error('invalid-source-path');
|
|
716
|
+
return result;
|
|
717
|
+
}
|
|
718
|
+
async function prepareParent(file) {
|
|
719
|
+
// 拒绝通过已有链接目录写到其他根;不追随链接部署或删除资产
|
|
720
|
+
let directory = path.dirname(file);
|
|
721
|
+
while (directory !== path.dirname(directory)) {
|
|
722
|
+
try {
|
|
723
|
+
if ((await fs.lstat(directory)).isSymbolicLink())
|
|
724
|
+
throw new Error('linked-parent');
|
|
725
|
+
}
|
|
726
|
+
catch (error) {
|
|
727
|
+
if (errorCode(error) !== 'ENOENT')
|
|
728
|
+
throw error;
|
|
729
|
+
}
|
|
730
|
+
directory = path.dirname(directory);
|
|
731
|
+
}
|
|
732
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
733
|
+
}
|
|
734
|
+
async function fileStat(file) {
|
|
735
|
+
try {
|
|
736
|
+
const stat = await fs.lstat(file);
|
|
737
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
738
|
+
throw new Error('not-regular-file');
|
|
739
|
+
return stat;
|
|
740
|
+
}
|
|
741
|
+
catch (error) {
|
|
742
|
+
if (errorCode(error) === 'ENOENT')
|
|
743
|
+
return null;
|
|
744
|
+
throw error;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/** POSIX 还需提交目录项;Windows 不支持用普通目录句柄执行 fsync */
|
|
748
|
+
async function syncParentDirectory(file) {
|
|
749
|
+
if (os.type() === 'Windows_NT')
|
|
750
|
+
return;
|
|
751
|
+
const directory = await fs.open(path.dirname(file), 'r');
|
|
752
|
+
try {
|
|
753
|
+
await directory.sync();
|
|
754
|
+
}
|
|
755
|
+
finally {
|
|
756
|
+
await directory.close();
|
|
757
|
+
}
|
|
718
758
|
}
|