@iyowei/sweep-node-modules-cli 0.2.1 → 0.4.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 +30 -21
- package/README.zh-CN.md +44 -35
- package/bin/bunfig.toml +3 -0
- package/bin/sweep-nm.mjs +201 -97
- package/dist/cli.js +22 -2359
- package/dist/manifest.json +3 -3
- package/package.json +9 -7
package/dist/cli.js
CHANGED
|
@@ -1,2359 +1,22 @@
|
|
|
1
|
-
// src/cli.ts
|
|
2
|
-
import { lstat as lstat3, mkdir, writeFile } from "node:fs/promises";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
// ../sweep-node-modules/src/config.ts
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import { posix, win32 } from "node:path";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
var
|
|
12
|
-
"
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
"
|
|
18
|
-
]);
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
code;
|
|
23
|
-
details;
|
|
24
|
-
constructor(code, message, details) {
|
|
25
|
-
super(message);
|
|
26
|
-
this.code = code;
|
|
27
|
-
this.details = details;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// ../sweep-node-modules/src/config.ts
|
|
32
|
-
var DEFAULT_EXCLUDE = [
|
|
33
|
-
".bun",
|
|
34
|
-
".npm",
|
|
35
|
-
".pnpm-store",
|
|
36
|
-
".yarn",
|
|
37
|
-
".nvm",
|
|
38
|
-
"nvm",
|
|
39
|
-
".fnm",
|
|
40
|
-
".volta",
|
|
41
|
-
".asdf",
|
|
42
|
-
".n",
|
|
43
|
-
".vscode",
|
|
44
|
-
".vscode-insiders",
|
|
45
|
-
".vscode-server",
|
|
46
|
-
".cursor",
|
|
47
|
-
".antigravity",
|
|
48
|
-
"Library",
|
|
49
|
-
".local",
|
|
50
|
-
".config",
|
|
51
|
-
".cache",
|
|
52
|
-
".claude"
|
|
53
|
-
];
|
|
54
|
-
function platformDefaultPath(platform, env, home) {
|
|
55
|
-
if (platform === "win32") {
|
|
56
|
-
const roaming = env.APPDATA || win32.join(env.USERPROFILE || home, "AppData", "Roaming");
|
|
57
|
-
return win32.join(roaming, "sweep-node-modules", "config.json");
|
|
58
|
-
}
|
|
59
|
-
return posix.join(home, ".config", "sweep-node-modules", "config.json");
|
|
60
|
-
}
|
|
61
|
-
function resolveConfigPath(options) {
|
|
62
|
-
if (options.flag) {
|
|
63
|
-
return { path: options.flag, source: "flag" };
|
|
64
|
-
}
|
|
65
|
-
const env = options.env ?? process.env;
|
|
66
|
-
if (env.SWEEP_NM_CONFIG) {
|
|
67
|
-
return { path: env.SWEEP_NM_CONFIG, source: "env" };
|
|
68
|
-
}
|
|
69
|
-
const platform = options.platform ?? process.platform;
|
|
70
|
-
const home = options.homedir ?? homedir();
|
|
71
|
-
return {
|
|
72
|
-
path: platformDefaultPath(platform, env, home),
|
|
73
|
-
source: "platform-default"
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
function describeActual(value) {
|
|
77
|
-
if (value === undefined)
|
|
78
|
-
return "缺失";
|
|
79
|
-
if (value === null)
|
|
80
|
-
return "null";
|
|
81
|
-
if (Array.isArray(value))
|
|
82
|
-
return "array";
|
|
83
|
-
return typeof value;
|
|
84
|
-
}
|
|
85
|
-
function fieldError(container, field, optional) {
|
|
86
|
-
const value = container[field];
|
|
87
|
-
if (value === undefined) {
|
|
88
|
-
return optional ? null : { field, message: `${field} 应为字符串数组 (实际: 缺失)` };
|
|
89
|
-
}
|
|
90
|
-
if (!Array.isArray(value)) {
|
|
91
|
-
return {
|
|
92
|
-
field,
|
|
93
|
-
message: `${field} 应为字符串数组 (实际: ${describeActual(value)})`
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
const badIndex = value.findIndex((item) => typeof item !== "string");
|
|
97
|
-
if (badIndex !== -1) {
|
|
98
|
-
return {
|
|
99
|
-
field,
|
|
100
|
-
message: `${field} 第 ${badIndex + 1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
return null;
|
|
104
|
-
}
|
|
105
|
-
function shapeError(value) {
|
|
106
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
107
|
-
return {
|
|
108
|
-
field: "顶层",
|
|
109
|
-
message: `顶层应为对象 (实际: ${describeActual(value)})`
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
const candidate = value;
|
|
113
|
-
const rootsError = fieldError(candidate, "roots", false);
|
|
114
|
-
if (rootsError !== null)
|
|
115
|
-
return rootsError;
|
|
116
|
-
const excludeError = fieldError(candidate, "exclude", true);
|
|
117
|
-
if (excludeError !== null)
|
|
118
|
-
return excludeError;
|
|
119
|
-
return fieldError(candidate, "include", true);
|
|
120
|
-
}
|
|
121
|
-
async function loadConfig(path) {
|
|
122
|
-
let text;
|
|
123
|
-
try {
|
|
124
|
-
text = await readFile(path, "utf8");
|
|
125
|
-
} catch (error) {
|
|
126
|
-
if (error.code === "ENOENT")
|
|
127
|
-
return { state: "absent" };
|
|
128
|
-
throw new SweepError("CONFIG_READ_FAILED", `配置读取失败 (${path}): ${error.message}`, { path, errno: error.code });
|
|
129
|
-
}
|
|
130
|
-
let data;
|
|
131
|
-
try {
|
|
132
|
-
data = JSON.parse(text);
|
|
133
|
-
} catch (error) {
|
|
134
|
-
throw new SweepError("CONFIG_CORRUPT_JSON", `配置损坏 (${path}): JSON 解析失败: ${error.message}`, { path });
|
|
135
|
-
}
|
|
136
|
-
const problem = shapeError(data);
|
|
137
|
-
if (problem !== null) {
|
|
138
|
-
throw new SweepError("CONFIG_CORRUPT_SHAPE", `配置损坏 (${path}): ${problem.message}`, { path, field: problem.field });
|
|
139
|
-
}
|
|
140
|
-
const raw = data;
|
|
141
|
-
return {
|
|
142
|
-
state: "ok",
|
|
143
|
-
config: {
|
|
144
|
-
roots: raw.roots,
|
|
145
|
-
exclude: raw.exclude ?? [...DEFAULT_EXCLUDE],
|
|
146
|
-
include: raw.include ?? []
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
async function loadResolvedConfig(resolved) {
|
|
151
|
-
const result = await loadConfig(resolved.path);
|
|
152
|
-
if (result.state === "absent" && resolved.source !== "platform-default") {
|
|
153
|
-
throw new SweepError("CONFIG_ABSENT", `配置不存在 (${resolved.path}), 请检查路径`, { path: resolved.path, source: resolved.source });
|
|
154
|
-
}
|
|
155
|
-
return result;
|
|
156
|
-
}
|
|
157
|
-
function mergeNames(configNames, cliNames) {
|
|
158
|
-
return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
|
|
159
|
-
}
|
|
160
|
-
// ../sweep-node-modules/src/display.ts
|
|
161
|
-
function formatBytes(bytes) {
|
|
162
|
-
if (bytes < 1024)
|
|
163
|
-
return `${Math.round(bytes)} B`;
|
|
164
|
-
const units = ["KB", "MB", "GB", "TB"];
|
|
165
|
-
let value = bytes;
|
|
166
|
-
let index = -1;
|
|
167
|
-
do {
|
|
168
|
-
value /= 1024;
|
|
169
|
-
index += 1;
|
|
170
|
-
} while (value >= 1024 && index < units.length - 1);
|
|
171
|
-
return `${Math.round(value * 10) / 10} ${units[index]}`;
|
|
172
|
-
}
|
|
173
|
-
var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
|
|
174
|
-
var sanitizeOutputLine = (text) => {
|
|
175
|
-
const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
|
|
176
|
-
return `${indent}${sanitizeLine(text)}`;
|
|
177
|
-
};
|
|
178
|
-
// ../sweep-node-modules/src/guard.ts
|
|
179
|
-
import { lstat, realpath, stat } from "node:fs/promises";
|
|
180
|
-
import { homedir as homedir2 } from "node:os";
|
|
181
|
-
import { posix as posix2, win32 as win322 } from "node:path";
|
|
182
|
-
var POSIX_STYLE = {
|
|
183
|
-
name: "posix",
|
|
184
|
-
ops: posix2,
|
|
185
|
-
caseInsensitive: false
|
|
186
|
-
};
|
|
187
|
-
var WIN32_STYLE = {
|
|
188
|
-
name: "win32",
|
|
189
|
-
ops: win322,
|
|
190
|
-
caseInsensitive: true
|
|
191
|
-
};
|
|
192
|
-
function nativeStyle() {
|
|
193
|
-
return process.platform === "win32" ? WIN32_STYLE : POSIX_STYLE;
|
|
194
|
-
}
|
|
195
|
-
function fold(p, style) {
|
|
196
|
-
return style.caseInsensitive ? p.toLowerCase() : p;
|
|
197
|
-
}
|
|
198
|
-
function dedupeKey(realPath, style) {
|
|
199
|
-
return fold(realPath, style);
|
|
200
|
-
}
|
|
201
|
-
function hasNodeModulesLeaf(target, style) {
|
|
202
|
-
return fold(style.ops.basename(target), style) === "node_modules";
|
|
203
|
-
}
|
|
204
|
-
function insideAnyRoot(realPath, roots, style) {
|
|
205
|
-
return roots.some((root) => {
|
|
206
|
-
const rel = style.ops.relative(fold(root, style), fold(realPath, style));
|
|
207
|
-
if (rel === "" || style.ops.isAbsolute(rel))
|
|
208
|
-
return false;
|
|
209
|
-
return rel !== ".." && !rel.startsWith(`..${style.ops.sep}`);
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
function isFilesystemRootBody(realPath, style) {
|
|
213
|
-
return fold(style.ops.parse(realPath).root, style) === fold(realPath, style);
|
|
214
|
-
}
|
|
215
|
-
function isHomeBody(realPath, home, style) {
|
|
216
|
-
return home !== null && dedupeKey(realPath, style) === dedupeKey(home, style);
|
|
217
|
-
}
|
|
218
|
-
function firstSymlinkOnAnchor(links) {
|
|
219
|
-
for (const link of links) {
|
|
220
|
-
if (link.symlink)
|
|
221
|
-
return link.path;
|
|
222
|
-
}
|
|
223
|
-
return null;
|
|
224
|
-
}
|
|
225
|
-
function anchorChainPaths(root, style) {
|
|
226
|
-
const absolute = style.ops.isAbsolute(root) ? root : style.ops.resolve(root);
|
|
227
|
-
const prefix = style.ops.parse(absolute).root;
|
|
228
|
-
const chain = [];
|
|
229
|
-
let cursor = prefix;
|
|
230
|
-
for (const part of absolute.slice(prefix.length).split(style.ops.sep)) {
|
|
231
|
-
if (part === "")
|
|
232
|
-
continue;
|
|
233
|
-
cursor = style.ops.join(cursor, part);
|
|
234
|
-
chain.push(cursor);
|
|
235
|
-
}
|
|
236
|
-
return chain;
|
|
237
|
-
}
|
|
238
|
-
async function tryRealpath(p) {
|
|
239
|
-
try {
|
|
240
|
-
return await realpath(p);
|
|
241
|
-
} catch {
|
|
242
|
-
return null;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
async function collectAnchorLinks(root, style) {
|
|
246
|
-
const links = [];
|
|
247
|
-
for (const path of anchorChainPaths(root, style)) {
|
|
248
|
-
try {
|
|
249
|
-
links.push({ path, symlink: (await lstat(path)).isSymbolicLink() });
|
|
250
|
-
} catch {}
|
|
251
|
-
}
|
|
252
|
-
return links;
|
|
253
|
-
}
|
|
254
|
-
async function firstSymlinkOnTarget(target) {
|
|
255
|
-
return firstSymlinkOnAnchor(await collectAnchorLinks(target, nativeStyle()));
|
|
256
|
-
}
|
|
257
|
-
async function firstSymlinkOnRoot(root) {
|
|
258
|
-
return firstSymlinkOnTarget(root);
|
|
259
|
-
}
|
|
260
|
-
async function validateTargets(targets, options) {
|
|
261
|
-
const style = options.style ?? nativeStyle();
|
|
262
|
-
const homeOption = options.home === undefined ? homedir2() : options.home;
|
|
263
|
-
const anchors = [];
|
|
264
|
-
for (const root of options.roots) {
|
|
265
|
-
anchors.push({
|
|
266
|
-
configured: root,
|
|
267
|
-
real: await tryRealpath(root),
|
|
268
|
-
link: firstSymlinkOnAnchor(await collectAnchorLinks(root, style))
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
const brokenAnchors = anchors.filter((anchor) => anchor.real !== null && anchor.link !== null);
|
|
272
|
-
const roots = [];
|
|
273
|
-
for (const anchor of anchors) {
|
|
274
|
-
if (anchor.real !== null)
|
|
275
|
-
roots.push(anchor.real);
|
|
276
|
-
}
|
|
277
|
-
const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
|
|
278
|
-
const accepted = [];
|
|
279
|
-
const rejected = [];
|
|
280
|
-
const mappings = [];
|
|
281
|
-
const seen = new Set;
|
|
282
|
-
for (const target of targets) {
|
|
283
|
-
if (options.signal?.aborted) {
|
|
284
|
-
throw new SweepError("CANCELLED", "安全闸校验在逐目标检查点被取消", {
|
|
285
|
-
phase: "validate"
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
if (!hasNodeModulesLeaf(target, style)) {
|
|
289
|
-
rejected.push({
|
|
290
|
-
target,
|
|
291
|
-
code: "GUARD_LEAF_NOT_NODE_MODULES",
|
|
292
|
-
message: "路径末段不是 node_modules"
|
|
293
|
-
});
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
let real = null;
|
|
297
|
-
let realpathErrno;
|
|
298
|
-
try {
|
|
299
|
-
real = await realpath(target);
|
|
300
|
-
} catch (error) {
|
|
301
|
-
realpathErrno = error.code;
|
|
302
|
-
}
|
|
303
|
-
if (real === null) {
|
|
304
|
-
let code = "GUARD_REALPATH_FAILED";
|
|
305
|
-
if (realpathErrno === "ENOENT")
|
|
306
|
-
code = "GUARD_TARGET_MISSING";
|
|
307
|
-
else if (realpathErrno === "EACCES" || realpathErrno === "EPERM") {
|
|
308
|
-
code = "GUARD_TARGET_UNREADABLE";
|
|
309
|
-
}
|
|
310
|
-
rejected.push({
|
|
311
|
-
target,
|
|
312
|
-
code,
|
|
313
|
-
message: "realpath 失败 (目标不存在或不可读)",
|
|
314
|
-
details: { errno: realpathErrno }
|
|
315
|
-
});
|
|
316
|
-
continue;
|
|
317
|
-
}
|
|
318
|
-
const brokenAnchor = brokenAnchors.find((anchor) => insideAnyRoot(real, [anchor.real], style));
|
|
319
|
-
if (brokenAnchor !== undefined) {
|
|
320
|
-
rejected.push({
|
|
321
|
-
target,
|
|
322
|
-
code: "GUARD_ROOT_ANCHOR_SYMLINK",
|
|
323
|
-
message: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`,
|
|
324
|
-
details: { root: brokenAnchor.configured, symlink: brokenAnchor.link }
|
|
325
|
-
});
|
|
326
|
-
continue;
|
|
327
|
-
}
|
|
328
|
-
if (isFilesystemRootBody(real, style)) {
|
|
329
|
-
rejected.push({
|
|
330
|
-
target,
|
|
331
|
-
code: "GUARD_FILESYSTEM_ROOT_BODY",
|
|
332
|
-
message: "目标是文件系统根本体"
|
|
333
|
-
});
|
|
334
|
-
continue;
|
|
335
|
-
}
|
|
336
|
-
if (isHomeBody(real, home, style)) {
|
|
337
|
-
rejected.push({
|
|
338
|
-
target,
|
|
339
|
-
code: "GUARD_HOME_BODY",
|
|
340
|
-
message: "目标是 home 本体"
|
|
341
|
-
});
|
|
342
|
-
continue;
|
|
343
|
-
}
|
|
344
|
-
if (!hasNodeModulesLeaf(real, style)) {
|
|
345
|
-
rejected.push({
|
|
346
|
-
target,
|
|
347
|
-
code: "GUARD_REAL_LEAF_NOT_NODE_MODULES",
|
|
348
|
-
message: "realpath 后的末段不是 node_modules"
|
|
349
|
-
});
|
|
350
|
-
continue;
|
|
351
|
-
}
|
|
352
|
-
if (!insideAnyRoot(real, roots, style)) {
|
|
353
|
-
rejected.push({
|
|
354
|
-
target,
|
|
355
|
-
code: "GUARD_OUTSIDE_ROOTS",
|
|
356
|
-
message: "realpath 后不在任何 root 之下"
|
|
357
|
-
});
|
|
358
|
-
continue;
|
|
359
|
-
}
|
|
360
|
-
const key = dedupeKey(real, style);
|
|
361
|
-
if (seen.has(key)) {
|
|
362
|
-
rejected.push({
|
|
363
|
-
target,
|
|
364
|
-
code: "GUARD_DUPLICATE_TARGET",
|
|
365
|
-
message: "重复目标 (realpath 去重)"
|
|
366
|
-
});
|
|
367
|
-
continue;
|
|
368
|
-
}
|
|
369
|
-
seen.add(key);
|
|
370
|
-
accepted.push(real);
|
|
371
|
-
mappings.push({ original: target, real });
|
|
372
|
-
}
|
|
373
|
-
return { accepted, rejected, mappings };
|
|
374
|
-
}
|
|
375
|
-
var fsDeviceProbe = async (path, follow) => {
|
|
376
|
-
try {
|
|
377
|
-
return (await (follow ? stat : lstat)(path)).dev;
|
|
378
|
-
} catch {
|
|
379
|
-
return null;
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
function owningRoot(target, roots, style) {
|
|
383
|
-
let best = null;
|
|
384
|
-
for (const root of roots) {
|
|
385
|
-
if (!insideAnyRoot(target, [root], style))
|
|
386
|
-
continue;
|
|
387
|
-
if (best === null || root.length > best.length)
|
|
388
|
-
best = root;
|
|
389
|
-
}
|
|
390
|
-
return best;
|
|
391
|
-
}
|
|
392
|
-
async function findCrossDeviceTargets(targets, options) {
|
|
393
|
-
const style = options.style ?? nativeStyle();
|
|
394
|
-
const probe = options.probe ?? fsDeviceProbe;
|
|
395
|
-
const devices = new Map;
|
|
396
|
-
const found = new Map;
|
|
397
|
-
for (const target of targets) {
|
|
398
|
-
const root = owningRoot(target, options.roots, style);
|
|
399
|
-
if (root === null)
|
|
400
|
-
continue;
|
|
401
|
-
let rootDev = devices.get(root);
|
|
402
|
-
if (rootDev === undefined) {
|
|
403
|
-
rootDev = await probe(root, true);
|
|
404
|
-
devices.set(root, rootDev);
|
|
405
|
-
}
|
|
406
|
-
if (rootDev === null)
|
|
407
|
-
continue;
|
|
408
|
-
const targetDev = await probe(target, false);
|
|
409
|
-
if (targetDev === null || targetDev === rootDev)
|
|
410
|
-
continue;
|
|
411
|
-
const parentDev = await probe(style.ops.dirname(target), true);
|
|
412
|
-
found.set(target, parentDev !== null && parentDev !== targetDev ? "target-itself" : "on-path");
|
|
413
|
-
}
|
|
414
|
-
return [...found.entries()].map(([target, kind]) => ({ target, kind }));
|
|
415
|
-
}
|
|
416
|
-
function crossDeviceIndex(entries) {
|
|
417
|
-
return new Map(entries.map((entry) => [entry.target, entry.kind]));
|
|
418
|
-
}
|
|
419
|
-
// ../sweep-node-modules/src/classify.ts
|
|
420
|
-
import { homedir as homedir3 } from "node:os";
|
|
421
|
-
var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
|
|
422
|
-
var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
|
|
423
|
-
function classifyTarget(target, options = {}) {
|
|
424
|
-
const style = options.style ?? nativeStyle();
|
|
425
|
-
const homeOption = options.home === undefined ? homedir3() : options.home;
|
|
426
|
-
const parts = target.split(style.ops.sep).filter((part) => part !== "");
|
|
427
|
-
const ancestors = parts.slice(0, -1);
|
|
428
|
-
for (const segment of ancestors) {
|
|
429
|
-
if (INSTALL_TREE_SEGMENTS.has(segment.toLowerCase()))
|
|
430
|
-
return {
|
|
431
|
-
kind: "suspect-install-tree",
|
|
432
|
-
reason: `位于 ${segment} 安装树目录`
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
const parent = ancestors[ancestors.length - 1];
|
|
436
|
-
if (parent !== undefined && parent.toLowerCase() === "lib")
|
|
437
|
-
return {
|
|
438
|
-
kind: "suspect-install-tree",
|
|
439
|
-
reason: "父目录为 lib, 形如版本管理器的 node 安装树"
|
|
440
|
-
};
|
|
441
|
-
if (homeOption !== null) {
|
|
442
|
-
const relative = style.ops.relative(fold2(homeOption, style), fold2(target, style));
|
|
443
|
-
const [first] = relative.split(style.ops.sep);
|
|
444
|
-
if (first !== undefined && first !== ".." && first !== "." && first.startsWith(".") && !style.ops.isAbsolute(relative))
|
|
445
|
-
return {
|
|
446
|
-
kind: "suspect-install-tree",
|
|
447
|
-
reason: `位于 ${first} (家目录下的隐藏目录)`
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
return { kind: "project" };
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
// ../sweep-node-modules/src/skip.ts
|
|
454
|
-
var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
|
|
455
|
-
var CROSS_DEVICE_NOTES = {
|
|
456
|
-
"on-path": "跨设备: 根与目标之间有挂载点",
|
|
457
|
-
"target-itself": "跨设备: 目标本体即挂载点"
|
|
458
|
-
};
|
|
459
|
-
var CROSS_DEVICE_HINTS = {
|
|
460
|
-
"on-path": "已跳过 (把该挂载点声明为独立根即可清理)",
|
|
461
|
-
"target-itself": "已跳过 (挂载点无法删除, 需先卸载该卷)"
|
|
462
|
-
};
|
|
463
|
-
var CROSS_DEVICE_TRAILER_ACTIONS = {
|
|
464
|
-
"on-path": "把根与目标之间的挂载点声明为独立根即可清理",
|
|
465
|
-
"target-itself": "目标本体即挂载点, 需先卸载该卷"
|
|
466
|
-
};
|
|
467
|
-
function crossDeviceNote(kind) {
|
|
468
|
-
return CROSS_DEVICE_NOTES[kind];
|
|
469
|
-
}
|
|
470
|
-
function skipReasonOf(entry, crossDevice, policy) {
|
|
471
|
-
const deviceKind = crossDevice.get(entry.target);
|
|
472
|
-
if (deviceKind !== undefined) {
|
|
473
|
-
return deviceKind === "on-path" ? "cross-device:on-path" : "cross-device:target-itself";
|
|
474
|
-
}
|
|
475
|
-
if (entry.bytes === undefined)
|
|
476
|
-
return "unmeasured";
|
|
477
|
-
if (entry.suspect && !policy.releaseSuspects)
|
|
478
|
-
return "suspect-install-tree";
|
|
479
|
-
return null;
|
|
480
|
-
}
|
|
481
|
-
function skipsBatch(entry, crossDevice, policy) {
|
|
482
|
-
return skipReasonOf(entry, crossDevice, policy) !== null;
|
|
483
|
-
}
|
|
484
|
-
function deletionBatch(entries, crossDevice, policy) {
|
|
485
|
-
return entries.filter((entry) => !skipsBatch(entry, crossDevice, policy)).map((entry) => entry.target);
|
|
486
|
-
}
|
|
487
|
-
function noteOf(entry, reason) {
|
|
488
|
-
if (reason === "suspect-install-tree")
|
|
489
|
-
return SUSPECT_HINT;
|
|
490
|
-
if (reason === "unmeasured") {
|
|
491
|
-
return `体积统计失败: ${entry.unmeasuredReason ?? "原因未知"}`;
|
|
492
|
-
}
|
|
493
|
-
return CROSS_DEVICE_HINTS[reason === "cross-device:on-path" ? "on-path" : "target-itself"];
|
|
494
|
-
}
|
|
495
|
-
function collectSkips(entries, crossDevice, policy) {
|
|
496
|
-
const suspectSkipped = policy.releaseSuspects ? [] : entries.filter((entry) => entry.suspect);
|
|
497
|
-
const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
|
|
498
|
-
const trailer = [
|
|
499
|
-
...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
|
|
500
|
-
...["on-path", "target-itself"].flatMap((kind) => {
|
|
501
|
-
const count = deviceSkipped.filter((entry) => crossDevice.get(entry.target) === kind).length;
|
|
502
|
-
return count === 0 ? [] : [
|
|
503
|
-
`跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`
|
|
504
|
-
];
|
|
505
|
-
})
|
|
506
|
-
];
|
|
507
|
-
const hints = new Map;
|
|
508
|
-
for (const entry of suspectSkipped) {
|
|
509
|
-
if (entry.bytes !== undefined)
|
|
510
|
-
hints.set(entry.target, SUSPECT_HINT);
|
|
511
|
-
}
|
|
512
|
-
for (const entry of deviceSkipped) {
|
|
513
|
-
const kind = crossDevice.get(entry.target);
|
|
514
|
-
if (entry.bytes !== undefined && kind !== undefined) {
|
|
515
|
-
hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
const book = [];
|
|
519
|
-
for (const entry of entries) {
|
|
520
|
-
const reason = skipReasonOf(entry, crossDevice, policy);
|
|
521
|
-
if (reason === null)
|
|
522
|
-
continue;
|
|
523
|
-
book.push({ target: entry.target, reason, note: noteOf(entry, reason) });
|
|
524
|
-
}
|
|
525
|
-
return { entries: book, trailer, hints };
|
|
526
|
-
}
|
|
527
|
-
// ../sweep-node-modules/src/summary.ts
|
|
528
|
-
var SUCCESS_KINDS = new Set([
|
|
529
|
-
"removed",
|
|
530
|
-
"missing",
|
|
531
|
-
"stale"
|
|
532
|
-
]);
|
|
533
|
-
function isSuccessOutcome(outcome) {
|
|
534
|
-
return SUCCESS_KINDS.has(outcome.kind);
|
|
535
|
-
}
|
|
536
|
-
function summarizeReport(report) {
|
|
537
|
-
const counts = {
|
|
538
|
-
removed: 0,
|
|
539
|
-
missing: 0,
|
|
540
|
-
stale: 0,
|
|
541
|
-
failed: 0,
|
|
542
|
-
rejected: 0,
|
|
543
|
-
"not-attempted": 0,
|
|
544
|
-
"not-expected": 0,
|
|
545
|
-
skipped: 0
|
|
546
|
-
};
|
|
547
|
-
for (const entry of report.entries)
|
|
548
|
-
counts[entry.outcome.kind] += 1;
|
|
549
|
-
return {
|
|
550
|
-
counts,
|
|
551
|
-
succeeded: counts.removed + counts.missing + counts.stale,
|
|
552
|
-
unprocessed: counts.skipped + counts.rejected + counts["not-attempted"] + counts["not-expected"],
|
|
553
|
-
failed: counts.failed,
|
|
554
|
-
aborted: report.removal?.aborted !== undefined
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
// ../sweep-node-modules/src/sweep.ts
|
|
558
|
-
import { homedir as homedir4 } from "node:os";
|
|
559
|
-
|
|
560
|
-
// ../sweep-node-modules/src/delete.ts
|
|
561
|
-
import { lstat as lstat2, realpath as realpath2, rm } from "node:fs/promises";
|
|
562
|
-
import { isAbsolute, join, relative, sep } from "node:path";
|
|
563
|
-
var ERROR_HINTS = {
|
|
564
|
-
EACCES: "权限不足, 拒绝删除",
|
|
565
|
-
EPERM: "操作不被允许",
|
|
566
|
-
EBUSY: "目标被占用",
|
|
567
|
-
ENOTEMPTY: "目录非空",
|
|
568
|
-
EROFS: "目标位于只读文件系统"
|
|
569
|
-
};
|
|
570
|
-
var PARTIAL_DELETION_HINT = "注意: 目录内容可能已被部分或全部删除, 请复查";
|
|
571
|
-
function describeCode(error) {
|
|
572
|
-
const fsError = error;
|
|
573
|
-
const code = fsError?.code;
|
|
574
|
-
if (typeof code !== "string" || code === "") {
|
|
575
|
-
return `未知错误: ${fsError?.message ?? String(error)}`;
|
|
576
|
-
}
|
|
577
|
-
return `${code}: ${ERROR_HINTS[code] ?? "删除未成功"}`;
|
|
578
|
-
}
|
|
579
|
-
function describeRemovalError(target, error) {
|
|
580
|
-
return `${describeCode(error)} (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
|
|
581
|
-
}
|
|
582
|
-
function describeReviewError(target, path, error) {
|
|
583
|
-
return `安全复核未完成 (${describeCode(error)}) (目标: ${target}; 组件: ${path}; 未执行删除)`;
|
|
584
|
-
}
|
|
585
|
-
function describeVanishedReview(target, path) {
|
|
586
|
-
return `安全复核未完成 (ENOENT: 路径组件消失) (目标: ${target}; 组件: ${path}; 请复查目标是否仍存在; 未执行删除; 若目标确已不存在, 可忽略此条)`;
|
|
587
|
-
}
|
|
588
|
-
async function checkGone(path) {
|
|
589
|
-
try {
|
|
590
|
-
await lstat2(path);
|
|
591
|
-
return "present";
|
|
592
|
-
} catch (error) {
|
|
593
|
-
return error?.code === "ENOENT" ? "gone" : "unknown";
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
function describeSurvivor(target, state) {
|
|
597
|
-
const review = state === "present" ? "复核确认目标仍存在" : "目标是否仍存在未能核验";
|
|
598
|
-
return `ENOENT: 删除中途失败 (${review}) (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
|
|
599
|
-
}
|
|
600
|
-
function isUnder(root, target) {
|
|
601
|
-
const rel = relative(root, target);
|
|
602
|
-
if (rel === "" || isAbsolute(rel))
|
|
603
|
-
return false;
|
|
604
|
-
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
605
|
-
}
|
|
606
|
-
function componentChain(root, target) {
|
|
607
|
-
const chain = [root];
|
|
608
|
-
let cursor = root;
|
|
609
|
-
for (const part of relative(root, target).split(sep).slice(0, -1)) {
|
|
610
|
-
cursor = join(cursor, part);
|
|
611
|
-
chain.push(cursor);
|
|
612
|
-
}
|
|
613
|
-
return chain;
|
|
614
|
-
}
|
|
615
|
-
async function isSymlinkHead(path) {
|
|
616
|
-
try {
|
|
617
|
-
return (await lstat2(path)).isSymbolicLink();
|
|
618
|
-
} catch {
|
|
619
|
-
return false;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
async function reviewComponents(chain) {
|
|
623
|
-
for (const path of chain) {
|
|
624
|
-
try {
|
|
625
|
-
const stats = await lstat2(path);
|
|
626
|
-
if (!stats.isDirectory())
|
|
627
|
-
return { kind: "unsafe", path };
|
|
628
|
-
} catch (error) {
|
|
629
|
-
const code = error?.code;
|
|
630
|
-
if (code === "ENOENT")
|
|
631
|
-
return { kind: "vanished", path };
|
|
632
|
-
return { kind: "unverified", path, error };
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
return null;
|
|
636
|
-
}
|
|
637
|
-
var REMOVAL_CONCURRENCY = 4;
|
|
638
|
-
async function removeTargets(targets, options) {
|
|
639
|
-
const roots = options?.roots ?? [];
|
|
640
|
-
const signal = options?.signal;
|
|
641
|
-
const emit = options?.onProgress;
|
|
642
|
-
const slots = Array.from({
|
|
643
|
-
length: targets.length
|
|
644
|
-
});
|
|
645
|
-
let aborted;
|
|
646
|
-
let abortedIndex = Number.POSITIVE_INFINITY;
|
|
647
|
-
const recordAbort = (index, info) => {
|
|
648
|
-
if (index >= abortedIndex)
|
|
649
|
-
return;
|
|
650
|
-
aborted = info;
|
|
651
|
-
abortedIndex = index;
|
|
652
|
-
};
|
|
653
|
-
let cancelled = false;
|
|
654
|
-
const failures = [];
|
|
655
|
-
let next = 0;
|
|
656
|
-
let active = 0;
|
|
657
|
-
let resolveDrained = null;
|
|
658
|
-
const drained = new Promise((resolve) => {
|
|
659
|
-
resolveDrained = resolve;
|
|
660
|
-
});
|
|
661
|
-
const halted = () => cancelled || aborted !== undefined;
|
|
662
|
-
function pump() {
|
|
663
|
-
while (active < REMOVAL_CONCURRENCY && next < targets.length && !halted()) {
|
|
664
|
-
const index = next;
|
|
665
|
-
next += 1;
|
|
666
|
-
active += 1;
|
|
667
|
-
removeOne(index);
|
|
668
|
-
}
|
|
669
|
-
if (active === 0 && resolveDrained !== null) {
|
|
670
|
-
const resolve = resolveDrained;
|
|
671
|
-
resolveDrained = null;
|
|
672
|
-
resolve();
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
async function removeOne(index) {
|
|
676
|
-
try {
|
|
677
|
-
const target = targets[index];
|
|
678
|
-
if (target === undefined)
|
|
679
|
-
return;
|
|
680
|
-
if (signal?.aborted) {
|
|
681
|
-
cancelled = true;
|
|
682
|
-
return;
|
|
683
|
-
}
|
|
684
|
-
const root = roots.find((candidate) => isUnder(candidate.real, target));
|
|
685
|
-
if (root === undefined) {
|
|
686
|
-
const info = {
|
|
687
|
-
target,
|
|
688
|
-
code: "REVIEW_NOT_UNDER_ANY_ROOT",
|
|
689
|
-
message: `安全复核失败 (目标不在任何 roots 之下): ${target}`,
|
|
690
|
-
path: target
|
|
691
|
-
};
|
|
692
|
-
recordAbort(index, info);
|
|
693
|
-
slots[index] = { kind: "aborted" };
|
|
694
|
-
emit?.({ kind: "aborted", aborted: info });
|
|
695
|
-
return;
|
|
696
|
-
}
|
|
697
|
-
if (await isSymlinkHead(root.configured)) {
|
|
698
|
-
const info = {
|
|
699
|
-
target,
|
|
700
|
-
code: "REVIEW_HEAD_SYMLINK",
|
|
701
|
-
message: `安全复核失败 (根被替换为符号链接): ${root.configured}`,
|
|
702
|
-
path: root.configured
|
|
703
|
-
};
|
|
704
|
-
recordAbort(index, info);
|
|
705
|
-
slots[index] = { kind: "aborted" };
|
|
706
|
-
emit?.({ kind: "aborted", aborted: info });
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
const finding = await reviewComponents(componentChain(root.real, target));
|
|
710
|
-
if (finding !== null) {
|
|
711
|
-
if (finding.kind === "vanished") {
|
|
712
|
-
const vanished = {
|
|
713
|
-
target,
|
|
714
|
-
code: "REVIEW_COMPONENT_VANISHED",
|
|
715
|
-
message: describeVanishedReview(target, finding.path),
|
|
716
|
-
partialRisk: false
|
|
717
|
-
};
|
|
718
|
-
slots[index] = { kind: "failed", failure: vanished };
|
|
719
|
-
emit?.({ kind: "failed", failure: vanished });
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
if (finding.kind === "unsafe") {
|
|
723
|
-
const info = {
|
|
724
|
-
target,
|
|
725
|
-
code: "REVIEW_COMPONENT_REPLACED",
|
|
726
|
-
message: `安全复核失败 (路径组件被替换): ${finding.path}`,
|
|
727
|
-
path: finding.path
|
|
728
|
-
};
|
|
729
|
-
recordAbort(index, info);
|
|
730
|
-
slots[index] = { kind: "aborted" };
|
|
731
|
-
emit?.({ kind: "aborted", aborted: info });
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
const unverified = {
|
|
735
|
-
target,
|
|
736
|
-
code: "REVIEW_UNVERIFIED",
|
|
737
|
-
message: describeReviewError(target, finding.path, finding.error),
|
|
738
|
-
partialRisk: false
|
|
739
|
-
};
|
|
740
|
-
slots[index] = { kind: "failed", failure: unverified };
|
|
741
|
-
emit?.({ kind: "failed", failure: unverified });
|
|
742
|
-
return;
|
|
743
|
-
}
|
|
744
|
-
try {
|
|
745
|
-
await rm(target, { recursive: true, force: false });
|
|
746
|
-
slots[index] = { kind: "removed", target };
|
|
747
|
-
emit?.({ kind: "removed", target });
|
|
748
|
-
} catch (error) {
|
|
749
|
-
if (error?.code === "ENOENT") {
|
|
750
|
-
const state = await checkGone(target);
|
|
751
|
-
if (state === "gone") {
|
|
752
|
-
slots[index] = { kind: "missing", target };
|
|
753
|
-
emit?.({ kind: "missing", target });
|
|
754
|
-
return;
|
|
755
|
-
}
|
|
756
|
-
const survivor = {
|
|
757
|
-
target,
|
|
758
|
-
code: "REMOVE_ENOENT_SURVIVOR",
|
|
759
|
-
message: describeSurvivor(target, state),
|
|
760
|
-
partialRisk: true
|
|
761
|
-
};
|
|
762
|
-
slots[index] = { kind: "failed", failure: survivor };
|
|
763
|
-
emit?.({ kind: "failed", failure: survivor });
|
|
764
|
-
return;
|
|
765
|
-
}
|
|
766
|
-
const failure = {
|
|
767
|
-
target,
|
|
768
|
-
code: "REMOVE_FAILED",
|
|
769
|
-
errno: error?.code,
|
|
770
|
-
message: describeRemovalError(target, error),
|
|
771
|
-
partialRisk: true
|
|
772
|
-
};
|
|
773
|
-
slots[index] = { kind: "failed", failure };
|
|
774
|
-
emit?.({ kind: "failed", failure });
|
|
775
|
-
}
|
|
776
|
-
} catch (error) {
|
|
777
|
-
if (failures.length === 0)
|
|
778
|
-
failures.push(error);
|
|
779
|
-
} finally {
|
|
780
|
-
if (signal?.aborted)
|
|
781
|
-
cancelled = true;
|
|
782
|
-
active -= 1;
|
|
783
|
-
pump();
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
pump();
|
|
787
|
-
await drained;
|
|
788
|
-
if (failures.length > 0)
|
|
789
|
-
throw failures[0];
|
|
790
|
-
const result = { removed: [], missing: [], failed: [] };
|
|
791
|
-
for (const slot of slots) {
|
|
792
|
-
if (slot === undefined)
|
|
793
|
-
continue;
|
|
794
|
-
switch (slot.kind) {
|
|
795
|
-
case "removed":
|
|
796
|
-
result.removed.push(slot.target);
|
|
797
|
-
break;
|
|
798
|
-
case "missing":
|
|
799
|
-
result.missing.push(slot.target);
|
|
800
|
-
break;
|
|
801
|
-
case "failed":
|
|
802
|
-
result.failed.push(slot.failure);
|
|
803
|
-
break;
|
|
804
|
-
case "aborted":
|
|
805
|
-
break;
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
if (aborted !== undefined)
|
|
809
|
-
result.aborted = aborted;
|
|
810
|
-
if (cancelled) {
|
|
811
|
-
throw new SweepError("CANCELLED", "删除在条目间检查点被取消", {
|
|
812
|
-
phase: "remove",
|
|
813
|
-
partial: result
|
|
814
|
-
});
|
|
815
|
-
}
|
|
816
|
-
return result;
|
|
817
|
-
}
|
|
818
|
-
async function toTrustRoots(roots) {
|
|
819
|
-
return Promise.all(roots.map(async (root) => ({
|
|
820
|
-
configured: root,
|
|
821
|
-
real: await realpath2(root).catch(() => null) ?? root
|
|
822
|
-
})));
|
|
823
|
-
}
|
|
824
|
-
function splitStaleRejections(rejected, staleTargets) {
|
|
825
|
-
if (staleTargets !== "missing")
|
|
826
|
-
return { rejected, stale: [] };
|
|
827
|
-
const rest = [];
|
|
828
|
-
const stale = [];
|
|
829
|
-
for (const item of rejected) {
|
|
830
|
-
if (item.code === "GUARD_TARGET_MISSING")
|
|
831
|
-
stale.push(item.target);
|
|
832
|
-
else
|
|
833
|
-
rest.push(item);
|
|
834
|
-
}
|
|
835
|
-
return { rejected: rest, stale };
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
// ../sweep-node-modules/src/scan-parallel.ts
|
|
839
|
-
import { readdir, realpath as realpath3, stat as stat2 } from "node:fs/promises";
|
|
840
|
-
import { join as join2 } from "node:path";
|
|
841
|
-
var NODE_MODULES = "node_modules";
|
|
842
|
-
var GIT_DIR = ".git";
|
|
843
|
-
var CONCURRENCY = 32;
|
|
844
|
-
function compareTarget(a, b) {
|
|
845
|
-
if (a.target < b.target)
|
|
846
|
-
return -1;
|
|
847
|
-
if (a.target > b.target)
|
|
848
|
-
return 1;
|
|
849
|
-
return 0;
|
|
850
|
-
}
|
|
851
|
-
function rootFailureWarning(error, root) {
|
|
852
|
-
const { code } = error;
|
|
853
|
-
switch (code) {
|
|
854
|
-
case "ENOENT":
|
|
855
|
-
return {
|
|
856
|
-
code: "SCAN_ROOT_MISSING",
|
|
857
|
-
message: `根不存在, 已跳过: ${root}`,
|
|
858
|
-
path: root
|
|
859
|
-
};
|
|
860
|
-
case "EACCES":
|
|
861
|
-
case "EPERM":
|
|
862
|
-
return {
|
|
863
|
-
code: "SCAN_ROOT_UNREADABLE",
|
|
864
|
-
message: `根不可读 (权限不足), 已跳过: ${root}`,
|
|
865
|
-
path: root,
|
|
866
|
-
errno: code
|
|
867
|
-
};
|
|
868
|
-
case "ENOTDIR":
|
|
869
|
-
return {
|
|
870
|
-
code: "SCAN_ROOT_NOT_DIR",
|
|
871
|
-
message: `根不是目录, 已跳过: ${root}`,
|
|
872
|
-
path: root
|
|
873
|
-
};
|
|
874
|
-
default:
|
|
875
|
-
return {
|
|
876
|
-
code: "SCAN_ROOT_UNAVAILABLE",
|
|
877
|
-
message: `根不可用 (${code ?? "UNKNOWN"}), 已跳过: ${root}`,
|
|
878
|
-
path: root,
|
|
879
|
-
errno: code
|
|
880
|
-
};
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
async function walkRoot(root, ctx) {
|
|
884
|
-
const {
|
|
885
|
-
style,
|
|
886
|
-
exclude,
|
|
887
|
-
excludeCounts,
|
|
888
|
-
include,
|
|
889
|
-
includeCounts,
|
|
890
|
-
hits,
|
|
891
|
-
warnings,
|
|
892
|
-
signal,
|
|
893
|
-
onProgress
|
|
894
|
-
} = ctx;
|
|
895
|
-
const stack = [{ dir: root, included: include.size === 0 }];
|
|
896
|
-
let outstanding = 1;
|
|
897
|
-
let active = 0;
|
|
898
|
-
const failures = [];
|
|
899
|
-
let resolveDrained = null;
|
|
900
|
-
const drained = new Promise((resolve) => {
|
|
901
|
-
resolveDrained = resolve;
|
|
902
|
-
});
|
|
903
|
-
function pump() {
|
|
904
|
-
while (active < CONCURRENCY && stack.length > 0) {
|
|
905
|
-
const next = stack.pop();
|
|
906
|
-
active += 1;
|
|
907
|
-
visit(next.dir, next.included);
|
|
908
|
-
}
|
|
909
|
-
if (outstanding === 0 && resolveDrained !== null) {
|
|
910
|
-
const resolve = resolveDrained;
|
|
911
|
-
resolveDrained = null;
|
|
912
|
-
resolve();
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
async function visit(dir, included) {
|
|
916
|
-
try {
|
|
917
|
-
if (signal?.aborted) {
|
|
918
|
-
throw new SweepError("CANCELLED", "扫描在遍历任务检查点被取消", {
|
|
919
|
-
phase: "scan"
|
|
920
|
-
});
|
|
921
|
-
}
|
|
922
|
-
let entries;
|
|
923
|
-
try {
|
|
924
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
925
|
-
} catch {
|
|
926
|
-
warnings.push({
|
|
927
|
-
code: "SCAN_DIR_UNREADABLE",
|
|
928
|
-
message: `目录不可读, 已跳过: ${dir}`,
|
|
929
|
-
path: dir
|
|
930
|
-
});
|
|
931
|
-
return;
|
|
932
|
-
}
|
|
933
|
-
for (const entry of entries) {
|
|
934
|
-
if (!entry.isDirectory())
|
|
935
|
-
continue;
|
|
936
|
-
const name = entry.name;
|
|
937
|
-
if (name === NODE_MODULES) {
|
|
938
|
-
if (!included)
|
|
939
|
-
continue;
|
|
940
|
-
const target = join2(dir, name);
|
|
941
|
-
const key = dedupeKey(await realpath3(target).catch(() => target), style);
|
|
942
|
-
if (!hits.has(key)) {
|
|
943
|
-
const hit = { project: dir, target, root };
|
|
944
|
-
hits.set(key, hit);
|
|
945
|
-
onProgress?.({ kind: "hit", hit });
|
|
946
|
-
}
|
|
947
|
-
continue;
|
|
948
|
-
}
|
|
949
|
-
if (name === GIT_DIR)
|
|
950
|
-
continue;
|
|
951
|
-
const childIncluded = included || include.has(name);
|
|
952
|
-
if (!included && include.has(name)) {
|
|
953
|
-
includeCounts.set(name, (includeCounts.get(name) ?? 0) + 1);
|
|
954
|
-
}
|
|
955
|
-
if (exclude.has(name)) {
|
|
956
|
-
excludeCounts.set(name, (excludeCounts.get(name) ?? 0) + 1);
|
|
957
|
-
continue;
|
|
958
|
-
}
|
|
959
|
-
stack.push({ dir: join2(dir, name), included: childIncluded });
|
|
960
|
-
outstanding += 1;
|
|
961
|
-
}
|
|
962
|
-
} catch (error) {
|
|
963
|
-
if (failures.length === 0)
|
|
964
|
-
failures.push(error);
|
|
965
|
-
} finally {
|
|
966
|
-
active -= 1;
|
|
967
|
-
outstanding -= 1;
|
|
968
|
-
pump();
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
pump();
|
|
972
|
-
await drained;
|
|
973
|
-
if (failures.length > 0)
|
|
974
|
-
throw failures[0];
|
|
975
|
-
}
|
|
976
|
-
function createParallelScanner() {
|
|
977
|
-
return {
|
|
978
|
-
name: "parallel",
|
|
979
|
-
async scan(options) {
|
|
980
|
-
const warnings = [];
|
|
981
|
-
const exclude = new Set(options.exclude);
|
|
982
|
-
const excludeCounts = new Map;
|
|
983
|
-
for (const name of options.exclude) {
|
|
984
|
-
if (!excludeCounts.has(name))
|
|
985
|
-
excludeCounts.set(name, 0);
|
|
986
|
-
}
|
|
987
|
-
const include = new Set(options.include);
|
|
988
|
-
const includeCounts = new Map;
|
|
989
|
-
for (const name of options.include) {
|
|
990
|
-
if (!includeCounts.has(name))
|
|
991
|
-
includeCounts.set(name, 0);
|
|
992
|
-
}
|
|
993
|
-
const hitsByRealTarget = new Map;
|
|
994
|
-
const style = nativeStyle();
|
|
995
|
-
const seenRoots = new Set;
|
|
996
|
-
const roots = [];
|
|
997
|
-
for (const root of options.roots) {
|
|
998
|
-
let key;
|
|
999
|
-
try {
|
|
1000
|
-
const resolved = await realpath3(root);
|
|
1001
|
-
if (!(await stat2(resolved)).isDirectory()) {
|
|
1002
|
-
warnings.push({
|
|
1003
|
-
code: "SCAN_ROOT_NOT_DIR",
|
|
1004
|
-
message: `根不是目录, 已跳过: ${root}`,
|
|
1005
|
-
path: root
|
|
1006
|
-
});
|
|
1007
|
-
continue;
|
|
1008
|
-
}
|
|
1009
|
-
key = dedupeKey(resolved, style);
|
|
1010
|
-
} catch (error) {
|
|
1011
|
-
warnings.push(rootFailureWarning(error, root));
|
|
1012
|
-
continue;
|
|
1013
|
-
}
|
|
1014
|
-
if (seenRoots.has(key))
|
|
1015
|
-
continue;
|
|
1016
|
-
seenRoots.add(key);
|
|
1017
|
-
roots.push(root);
|
|
1018
|
-
}
|
|
1019
|
-
const context = {
|
|
1020
|
-
style,
|
|
1021
|
-
exclude,
|
|
1022
|
-
excludeCounts,
|
|
1023
|
-
include,
|
|
1024
|
-
includeCounts,
|
|
1025
|
-
hits: hitsByRealTarget,
|
|
1026
|
-
warnings,
|
|
1027
|
-
signal: options.signal,
|
|
1028
|
-
onProgress: options.onProgress
|
|
1029
|
-
};
|
|
1030
|
-
for (const root of roots) {
|
|
1031
|
-
await walkRoot(root, context);
|
|
1032
|
-
}
|
|
1033
|
-
const hits = [...hitsByRealTarget.values()].sort(compareTarget);
|
|
1034
|
-
const excludeMatches = options.exclude.map((name) => ({
|
|
1035
|
-
name,
|
|
1036
|
-
hits: excludeCounts.get(name) ?? 0
|
|
1037
|
-
}));
|
|
1038
|
-
const includeMatches = options.include.map((name) => ({
|
|
1039
|
-
name,
|
|
1040
|
-
hits: includeCounts.get(name) ?? 0
|
|
1041
|
-
}));
|
|
1042
|
-
return { hits, warnings, excludeMatches, includeMatches };
|
|
1043
|
-
}
|
|
1044
|
-
};
|
|
1045
|
-
}
|
|
1046
|
-
// ../sweep-node-modules/src/size-du.ts
|
|
1047
|
-
import { spawn } from "node:child_process";
|
|
1048
|
-
import { accessSync, constants } from "node:fs";
|
|
1049
|
-
var DU_PROBES = ["/usr/bin/du", "/bin/du"];
|
|
1050
|
-
var hasControlChar = (target) => target.includes(`
|
|
1051
|
-
`) || target.includes("\r");
|
|
1052
|
-
var PROG_PREFIX_RE = /^(?:\/[^\s:]*)?[a-z][a-z0-9_-]*:\s+/;
|
|
1053
|
-
function findDu(platform = process.platform) {
|
|
1054
|
-
if (platform === "win32")
|
|
1055
|
-
return null;
|
|
1056
|
-
for (const probe of DU_PROBES) {
|
|
1057
|
-
try {
|
|
1058
|
-
accessSync(probe, constants.X_OK);
|
|
1059
|
-
return probe;
|
|
1060
|
-
} catch {}
|
|
1061
|
-
}
|
|
1062
|
-
return null;
|
|
1063
|
-
}
|
|
1064
|
-
function runDu(bin, targets) {
|
|
1065
|
-
return new Promise((resolve) => {
|
|
1066
|
-
const child = spawn(bin, ["-sk", "--", ...targets], {
|
|
1067
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
1068
|
-
});
|
|
1069
|
-
let stdout = "";
|
|
1070
|
-
let stderr = "";
|
|
1071
|
-
child.stdout.on("data", (chunk) => {
|
|
1072
|
-
stdout += chunk;
|
|
1073
|
-
});
|
|
1074
|
-
child.stderr.on("data", (chunk) => {
|
|
1075
|
-
stderr += chunk;
|
|
1076
|
-
});
|
|
1077
|
-
child.on("error", (error) => {
|
|
1078
|
-
resolve({ stdout, stderr: `${stderr}${String(error)}` });
|
|
1079
|
-
});
|
|
1080
|
-
child.on("close", () => resolve({ stdout, stderr }));
|
|
1081
|
-
});
|
|
1082
|
-
}
|
|
1083
|
-
function parseDuSizes(stdout) {
|
|
1084
|
-
const sizes = new Map;
|
|
1085
|
-
let duplicated = false;
|
|
1086
|
-
for (const line of stdout.split(`
|
|
1087
|
-
`)) {
|
|
1088
|
-
const match = /^(\d+)\t(.+)$/.exec(line);
|
|
1089
|
-
if (match === null)
|
|
1090
|
-
continue;
|
|
1091
|
-
const sizeKiB = match[1];
|
|
1092
|
-
const path = match[2];
|
|
1093
|
-
if (sizeKiB === undefined || path === undefined)
|
|
1094
|
-
continue;
|
|
1095
|
-
if (sizes.has(path))
|
|
1096
|
-
duplicated = true;
|
|
1097
|
-
sizes.set(path, Number(sizeKiB) * 1024);
|
|
1098
|
-
}
|
|
1099
|
-
return { sizes, duplicated };
|
|
1100
|
-
}
|
|
1101
|
-
function assessDuOutput(stdout, safeTargets) {
|
|
1102
|
-
const safeSet = new Set(safeTargets);
|
|
1103
|
-
const parsed = parseDuSizes(stdout);
|
|
1104
|
-
let unexpected = false;
|
|
1105
|
-
for (const path of parsed.sizes.keys()) {
|
|
1106
|
-
if (!safeSet.has(path))
|
|
1107
|
-
unexpected = true;
|
|
1108
|
-
}
|
|
1109
|
-
const intact = !parsed.duplicated && parsed.sizes.size <= safeTargets.length && !unexpected;
|
|
1110
|
-
return {
|
|
1111
|
-
sizes: parsed.sizes,
|
|
1112
|
-
intact,
|
|
1113
|
-
duplicated: parsed.duplicated,
|
|
1114
|
-
unexpected
|
|
1115
|
-
};
|
|
1116
|
-
}
|
|
1117
|
-
function describeAnomaly(assessment) {
|
|
1118
|
-
const shapes = [];
|
|
1119
|
-
if (assessment.duplicated)
|
|
1120
|
-
shapes.push("同一路径多行");
|
|
1121
|
-
if (assessment.unexpected)
|
|
1122
|
-
shapes.push("含输入之外的路径");
|
|
1123
|
-
if (shapes.length === 0)
|
|
1124
|
-
shapes.push("行数与输入不符");
|
|
1125
|
-
return shapes.join(" / ");
|
|
1126
|
-
}
|
|
1127
|
-
function describeDuFailure(detail) {
|
|
1128
|
-
if (/no such file or directory/i.test(detail))
|
|
1129
|
-
return { missing: true, reason: "不存在" };
|
|
1130
|
-
if (/permission denied/i.test(detail))
|
|
1131
|
-
return {
|
|
1132
|
-
missing: false,
|
|
1133
|
-
code: "SIZE_UNMEASURED_PERMISSION",
|
|
1134
|
-
reason: "权限不足, 无法读取"
|
|
1135
|
-
};
|
|
1136
|
-
if (/not a directory/i.test(detail))
|
|
1137
|
-
return {
|
|
1138
|
-
missing: false,
|
|
1139
|
-
code: "SIZE_UNMEASURED_NOT_DIR",
|
|
1140
|
-
reason: "不是目录"
|
|
1141
|
-
};
|
|
1142
|
-
if (/too many levels of symbolic links/i.test(detail)) {
|
|
1143
|
-
return {
|
|
1144
|
-
missing: false,
|
|
1145
|
-
code: "SIZE_UNMEASURED_LOOP",
|
|
1146
|
-
reason: "符号链接层级过深"
|
|
1147
|
-
};
|
|
1148
|
-
}
|
|
1149
|
-
return {
|
|
1150
|
-
missing: false,
|
|
1151
|
-
code: "SIZE_UNMEASURED_OTHER",
|
|
1152
|
-
reason: `读取失败 (${detail})`
|
|
1153
|
-
};
|
|
1154
|
-
}
|
|
1155
|
-
function parseDuErrorLine(line) {
|
|
1156
|
-
const body = line.replace(PROG_PREFIX_RE, "");
|
|
1157
|
-
const gnu = /^cannot\s+(?:access|read directory|stat|open)\s+'(.*)':\s+(.+)$/.exec(body);
|
|
1158
|
-
if (gnu !== null) {
|
|
1159
|
-
const path = gnu[1];
|
|
1160
|
-
const detail = gnu[2];
|
|
1161
|
-
if (path !== undefined && detail !== undefined)
|
|
1162
|
-
return { path, detail };
|
|
1163
|
-
}
|
|
1164
|
-
const match = /^(.+):\s+(.+)$/.exec(body);
|
|
1165
|
-
if (match === null)
|
|
1166
|
-
return null;
|
|
1167
|
-
const path = match[1];
|
|
1168
|
-
const detail = match[2];
|
|
1169
|
-
if (path === undefined || detail === undefined)
|
|
1170
|
-
return null;
|
|
1171
|
-
return { path, detail };
|
|
1172
|
-
}
|
|
1173
|
-
function createDuSizer(bin = findDu()) {
|
|
1174
|
-
return {
|
|
1175
|
-
name: "du",
|
|
1176
|
-
basis: "disk-usage",
|
|
1177
|
-
async measure(targets, options) {
|
|
1178
|
-
if (bin === null) {
|
|
1179
|
-
return {
|
|
1180
|
-
entries: [],
|
|
1181
|
-
basis: "disk-usage",
|
|
1182
|
-
warnings: [
|
|
1183
|
-
{
|
|
1184
|
-
code: "SIZE_DU_UNAVAILABLE",
|
|
1185
|
-
message: "du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"
|
|
1186
|
-
}
|
|
1187
|
-
],
|
|
1188
|
-
unmeasured: [],
|
|
1189
|
-
gone: []
|
|
1190
|
-
};
|
|
1191
|
-
}
|
|
1192
|
-
if (targets.length === 0) {
|
|
1193
|
-
return {
|
|
1194
|
-
entries: [],
|
|
1195
|
-
basis: "disk-usage",
|
|
1196
|
-
warnings: [],
|
|
1197
|
-
unmeasured: [],
|
|
1198
|
-
gone: []
|
|
1199
|
-
};
|
|
1200
|
-
}
|
|
1201
|
-
const sorted = [...targets].sort();
|
|
1202
|
-
const warnings = [];
|
|
1203
|
-
const entries = [];
|
|
1204
|
-
const unmeasured = [];
|
|
1205
|
-
const gone = [];
|
|
1206
|
-
const emit = options?.onProgress;
|
|
1207
|
-
const safeTargets = sorted.filter((target) => !hasControlChar(target));
|
|
1208
|
-
const safeSet = new Set(safeTargets);
|
|
1209
|
-
const sizes = new Map;
|
|
1210
|
-
const failures = new Map;
|
|
1211
|
-
let intact = true;
|
|
1212
|
-
if (safeTargets.length > 0) {
|
|
1213
|
-
const { stdout, stderr } = await runDu(bin, safeTargets);
|
|
1214
|
-
const assessment = assessDuOutput(stdout, safeTargets);
|
|
1215
|
-
intact = assessment.intact;
|
|
1216
|
-
if (!intact) {
|
|
1217
|
-
warnings.push({
|
|
1218
|
-
code: "SIZE_DU_OUTPUT_MISMATCH",
|
|
1219
|
-
message: `du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`
|
|
1220
|
-
});
|
|
1221
|
-
}
|
|
1222
|
-
for (const [path, bytes] of assessment.sizes)
|
|
1223
|
-
sizes.set(path, bytes);
|
|
1224
|
-
for (const line of stderr.split(`
|
|
1225
|
-
`)) {
|
|
1226
|
-
if (line.trim() === "")
|
|
1227
|
-
continue;
|
|
1228
|
-
const errorLine = parseDuErrorLine(line);
|
|
1229
|
-
if (errorLine === null) {
|
|
1230
|
-
warnings.push({
|
|
1231
|
-
code: "SIZE_DU_LINE_UNATTRIBUTED",
|
|
1232
|
-
message: `体积统计失败 (未归因): ${line.replace(PROG_PREFIX_RE, "").trim()}`
|
|
1233
|
-
});
|
|
1234
|
-
continue;
|
|
1235
|
-
}
|
|
1236
|
-
const failure = describeDuFailure(errorLine.detail);
|
|
1237
|
-
if (!safeSet.has(errorLine.path)) {
|
|
1238
|
-
warnings.push({
|
|
1239
|
-
code: "SIZE_SUBPATH_FAILED",
|
|
1240
|
-
message: `体积统计失败 (${failure.reason}): ${errorLine.path}`,
|
|
1241
|
-
path: errorLine.path
|
|
1242
|
-
});
|
|
1243
|
-
continue;
|
|
1244
|
-
}
|
|
1245
|
-
failures.set(errorLine.path, failure);
|
|
1246
|
-
}
|
|
1247
|
-
for (const path of failures.keys())
|
|
1248
|
-
sizes.delete(path);
|
|
1249
|
-
}
|
|
1250
|
-
const pushUnmeasured = (target, code, reason) => {
|
|
1251
|
-
unmeasured.push({ target, code, reason });
|
|
1252
|
-
emit?.({ kind: "unmeasured", target, code, reason });
|
|
1253
|
-
};
|
|
1254
|
-
for (const target of sorted) {
|
|
1255
|
-
if (options?.signal?.aborted) {
|
|
1256
|
-
throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
|
|
1257
|
-
phase: "measure"
|
|
1258
|
-
});
|
|
1259
|
-
}
|
|
1260
|
-
if (hasControlChar(target)) {
|
|
1261
|
-
pushUnmeasured(target, "SIZE_UNMEASURED_CONTROL_CHAR", "路径含控制字符");
|
|
1262
|
-
continue;
|
|
1263
|
-
}
|
|
1264
|
-
if (!intact) {
|
|
1265
|
-
pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
|
|
1266
|
-
continue;
|
|
1267
|
-
}
|
|
1268
|
-
const bytes = sizes.get(target);
|
|
1269
|
-
if (bytes !== undefined) {
|
|
1270
|
-
entries.push({ target, bytes });
|
|
1271
|
-
emit?.({ kind: "measured", target, bytes, basis: "disk-usage" });
|
|
1272
|
-
continue;
|
|
1273
|
-
}
|
|
1274
|
-
const failure = failures.get(target);
|
|
1275
|
-
if (failure === undefined) {
|
|
1276
|
-
pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
|
|
1277
|
-
continue;
|
|
1278
|
-
}
|
|
1279
|
-
if (failure.missing) {
|
|
1280
|
-
gone.push(target);
|
|
1281
|
-
warnings.push({
|
|
1282
|
-
code: "SIZE_TARGET_VANISHED",
|
|
1283
|
-
message: `体积统计失败 (不存在): ${target}`,
|
|
1284
|
-
path: target
|
|
1285
|
-
});
|
|
1286
|
-
emit?.({ kind: "gone", target });
|
|
1287
|
-
continue;
|
|
1288
|
-
}
|
|
1289
|
-
pushUnmeasured(target, failure.code, failure.reason);
|
|
1290
|
-
}
|
|
1291
|
-
return { entries, basis: "disk-usage", warnings, unmeasured, gone };
|
|
1292
|
-
}
|
|
1293
|
-
};
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
// ../sweep-node-modules/src/size-js.ts
|
|
1297
|
-
import { readdir as readdir2, stat as stat3 } from "node:fs/promises";
|
|
1298
|
-
import { join as join3 } from "node:path";
|
|
1299
|
-
function describeFailure(code) {
|
|
1300
|
-
switch (code) {
|
|
1301
|
-
case "ENOENT":
|
|
1302
|
-
return { missing: true, reason: "不存在" };
|
|
1303
|
-
case "EACCES":
|
|
1304
|
-
case "EPERM":
|
|
1305
|
-
return {
|
|
1306
|
-
missing: false,
|
|
1307
|
-
code: "SIZE_UNMEASURED_PERMISSION",
|
|
1308
|
-
reason: "权限不足, 无法读取"
|
|
1309
|
-
};
|
|
1310
|
-
case "ENOTDIR":
|
|
1311
|
-
return {
|
|
1312
|
-
missing: false,
|
|
1313
|
-
code: "SIZE_UNMEASURED_NOT_DIR",
|
|
1314
|
-
reason: "不是目录"
|
|
1315
|
-
};
|
|
1316
|
-
case "ELOOP":
|
|
1317
|
-
return {
|
|
1318
|
-
missing: false,
|
|
1319
|
-
code: "SIZE_UNMEASURED_LOOP",
|
|
1320
|
-
reason: "符号链接层级过深"
|
|
1321
|
-
};
|
|
1322
|
-
default:
|
|
1323
|
-
return {
|
|
1324
|
-
missing: false,
|
|
1325
|
-
code: "SIZE_UNMEASURED_OTHER",
|
|
1326
|
-
reason: code === undefined ? "读取失败" : `读取失败 (${code})`
|
|
1327
|
-
};
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
function errorCode(error) {
|
|
1331
|
-
return error?.code;
|
|
1332
|
-
}
|
|
1333
|
-
async function sumEntries(dirents, dir, warnings) {
|
|
1334
|
-
let total = 0;
|
|
1335
|
-
for (const dirent of dirents) {
|
|
1336
|
-
if (dirent.isSymbolicLink())
|
|
1337
|
-
continue;
|
|
1338
|
-
const path = join3(dir, dirent.name);
|
|
1339
|
-
if (dirent.isDirectory()) {
|
|
1340
|
-
try {
|
|
1341
|
-
total += await sumEntries(await readdir2(path, { withFileTypes: true }), path, warnings);
|
|
1342
|
-
} catch (error) {
|
|
1343
|
-
warnings.push({
|
|
1344
|
-
code: "SIZE_SUBPATH_FAILED",
|
|
1345
|
-
message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
|
|
1346
|
-
path
|
|
1347
|
-
});
|
|
1348
|
-
}
|
|
1349
|
-
} else if (dirent.isFile()) {
|
|
1350
|
-
try {
|
|
1351
|
-
total += (await stat3(path)).size;
|
|
1352
|
-
} catch (error) {
|
|
1353
|
-
warnings.push({
|
|
1354
|
-
code: "SIZE_SUBPATH_FAILED",
|
|
1355
|
-
message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
|
|
1356
|
-
path
|
|
1357
|
-
});
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
return total;
|
|
1362
|
-
}
|
|
1363
|
-
function createJsSizer() {
|
|
1364
|
-
return {
|
|
1365
|
-
name: "js",
|
|
1366
|
-
basis: "logical-bytes",
|
|
1367
|
-
async measure(targets, options) {
|
|
1368
|
-
const warnings = [];
|
|
1369
|
-
const entries = [];
|
|
1370
|
-
const unmeasured = [];
|
|
1371
|
-
const gone = [];
|
|
1372
|
-
const emit = options?.onProgress;
|
|
1373
|
-
const pushUnmeasured = (target, code, reason) => {
|
|
1374
|
-
unmeasured.push({ target, code, reason });
|
|
1375
|
-
emit?.({ kind: "unmeasured", target, code, reason });
|
|
1376
|
-
};
|
|
1377
|
-
for (const target of [...targets].sort()) {
|
|
1378
|
-
if (options?.signal?.aborted) {
|
|
1379
|
-
throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
|
|
1380
|
-
phase: "measure"
|
|
1381
|
-
});
|
|
1382
|
-
}
|
|
1383
|
-
let dirents;
|
|
1384
|
-
try {
|
|
1385
|
-
dirents = await readdir2(target, { withFileTypes: true });
|
|
1386
|
-
} catch (error) {
|
|
1387
|
-
const failure = describeFailure(errorCode(error));
|
|
1388
|
-
if (failure.missing) {
|
|
1389
|
-
gone.push(target);
|
|
1390
|
-
warnings.push({
|
|
1391
|
-
code: "SIZE_TARGET_VANISHED",
|
|
1392
|
-
message: `体积统计失败 (${failure.reason}): ${target}`,
|
|
1393
|
-
path: target
|
|
1394
|
-
});
|
|
1395
|
-
emit?.({ kind: "gone", target });
|
|
1396
|
-
} else {
|
|
1397
|
-
pushUnmeasured(target, failure.code, failure.reason);
|
|
1398
|
-
}
|
|
1399
|
-
continue;
|
|
1400
|
-
}
|
|
1401
|
-
const bytes = await sumEntries(dirents, target, warnings);
|
|
1402
|
-
entries.push({ target, bytes });
|
|
1403
|
-
emit?.({ kind: "measured", target, bytes, basis: "logical-bytes" });
|
|
1404
|
-
}
|
|
1405
|
-
return { entries, basis: "logical-bytes", warnings, unmeasured, gone };
|
|
1406
|
-
}
|
|
1407
|
-
};
|
|
1408
|
-
}
|
|
1409
|
-
|
|
1410
|
-
// ../sweep-node-modules/src/size.ts
|
|
1411
|
-
function createSizer() {
|
|
1412
|
-
return findDu() !== null ? createDuSizer() : createJsSizer();
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
// ../sweep-node-modules/src/sweep.ts
|
|
1416
|
-
var invalidArgument = (field, message) => new SweepError("INVALID_ARGUMENT", `${message} (字段: ${field})`, { field });
|
|
1417
|
-
function assertNameArray(value, field, required) {
|
|
1418
|
-
if (value === undefined) {
|
|
1419
|
-
if (required)
|
|
1420
|
-
throw invalidArgument(field, "为必填项");
|
|
1421
|
-
return;
|
|
1422
|
-
}
|
|
1423
|
-
if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item === ""))
|
|
1424
|
-
throw invalidArgument(field, "必须是非空字符串数组");
|
|
1425
|
-
if (required && value.length === 0)
|
|
1426
|
-
throw invalidArgument(field, "不能为空数组");
|
|
1427
|
-
}
|
|
1428
|
-
function assertShape(options) {
|
|
1429
|
-
if (typeof options !== "object" || options === null)
|
|
1430
|
-
throw invalidArgument("options", "构造选项必须是对象");
|
|
1431
|
-
assertNameArray(options.roots, "roots", true);
|
|
1432
|
-
assertNameArray(options.exclude, "exclude", false);
|
|
1433
|
-
assertNameArray(options.include, "include", false);
|
|
1434
|
-
if (options.home !== undefined && options.home !== null && typeof options.home !== "string")
|
|
1435
|
-
throw invalidArgument("home", "必须是字符串或 null");
|
|
1436
|
-
if (options.policy !== undefined && (typeof options.policy !== "object" || options.policy === null || typeof options.policy.releaseSuspects !== "boolean"))
|
|
1437
|
-
throw invalidArgument("policy", "releaseSuspects 必须是布尔值");
|
|
1438
|
-
}
|
|
1439
|
-
function resolveOptions(options) {
|
|
1440
|
-
assertShape(options);
|
|
1441
|
-
return Object.freeze({
|
|
1442
|
-
roots: [...options.roots],
|
|
1443
|
-
exclude: mergeNames(options.exclude ?? [...DEFAULT_EXCLUDE], []),
|
|
1444
|
-
include: mergeNames(options.include ?? [], []),
|
|
1445
|
-
home: options.home === undefined ? homedir4() : options.home,
|
|
1446
|
-
style: options.style ?? nativeStyle(),
|
|
1447
|
-
policy: Object.freeze({
|
|
1448
|
-
releaseSuspects: options.policy?.releaseSuspects ?? false
|
|
1449
|
-
})
|
|
1450
|
-
});
|
|
1451
|
-
}
|
|
1452
|
-
var cancelledAt = (phase) => new SweepError("CANCELLED", `清理在 ${phase} 阶段被取消`, { phase });
|
|
1453
|
-
async function withPhase(phase, emit, signal, work) {
|
|
1454
|
-
if (signal?.aborted)
|
|
1455
|
-
throw cancelledAt(phase);
|
|
1456
|
-
const startedAt = Date.now();
|
|
1457
|
-
emit?.({ kind: "phase", phase, status: "start" });
|
|
1458
|
-
const value = await work();
|
|
1459
|
-
emit?.({
|
|
1460
|
-
kind: "phase",
|
|
1461
|
-
phase,
|
|
1462
|
-
status: "done",
|
|
1463
|
-
elapsedMs: Date.now() - startedAt
|
|
1464
|
-
});
|
|
1465
|
-
return value;
|
|
1466
|
-
}
|
|
1467
|
-
async function executePlan(resolved, options, signal) {
|
|
1468
|
-
const emit = options?.onProgress;
|
|
1469
|
-
const roots = resolved.roots;
|
|
1470
|
-
const scanResult = await withPhase("scan", emit, signal, async () => {
|
|
1471
|
-
const result = await createParallelScanner().scan({
|
|
1472
|
-
roots,
|
|
1473
|
-
exclude: resolved.exclude,
|
|
1474
|
-
include: resolved.include,
|
|
1475
|
-
signal,
|
|
1476
|
-
onProgress: (event) => emit?.(event)
|
|
1477
|
-
});
|
|
1478
|
-
for (const warning of result.warnings)
|
|
1479
|
-
emit?.({ kind: "warning", warning });
|
|
1480
|
-
return result;
|
|
1481
|
-
});
|
|
1482
|
-
const targets = scanResult.hits.map((hit) => hit.target);
|
|
1483
|
-
const sizeResult = await withPhase("measure", emit, signal, async () => {
|
|
1484
|
-
const result = await createSizer().measure(targets, {
|
|
1485
|
-
signal,
|
|
1486
|
-
onProgress: (event) => {
|
|
1487
|
-
if (event.kind === "gone")
|
|
1488
|
-
return;
|
|
1489
|
-
emit?.(event);
|
|
1490
|
-
}
|
|
1491
|
-
});
|
|
1492
|
-
for (const warning of result.warnings)
|
|
1493
|
-
emit?.({ kind: "warning", warning });
|
|
1494
|
-
return result;
|
|
1495
|
-
});
|
|
1496
|
-
const classifications = await withPhase("classify", emit, signal, () => scanResult.hits.map((hit) => classifyTarget(hit.target, {
|
|
1497
|
-
home: resolved.home,
|
|
1498
|
-
style: resolved.style
|
|
1499
|
-
})));
|
|
1500
|
-
const crossDevice = await withPhase("device", emit, signal, async () => crossDeviceIndex(await findCrossDeviceTargets(targets, {
|
|
1501
|
-
roots,
|
|
1502
|
-
style: resolved.style
|
|
1503
|
-
})));
|
|
1504
|
-
return withPhase("plan", emit, signal, () => {
|
|
1505
|
-
const policy = resolved.policy;
|
|
1506
|
-
const bytesOf = new Map(sizeResult.entries.map((entry) => [
|
|
1507
|
-
entry.target,
|
|
1508
|
-
entry.bytes
|
|
1509
|
-
]));
|
|
1510
|
-
const unmeasuredOf = new Map(sizeResult.unmeasured.map((item) => [item.target, item]));
|
|
1511
|
-
const goneSet = new Set(sizeResult.gone);
|
|
1512
|
-
const prepared = [];
|
|
1513
|
-
for (let index = 0;index < scanResult.hits.length; index += 1) {
|
|
1514
|
-
const hit = scanResult.hits[index];
|
|
1515
|
-
const classification = classifications[index];
|
|
1516
|
-
if (hit === undefined || classification === undefined)
|
|
1517
|
-
continue;
|
|
1518
|
-
if (goneSet.has(hit.target))
|
|
1519
|
-
continue;
|
|
1520
|
-
const bytes = bytesOf.get(hit.target);
|
|
1521
|
-
prepared.push({
|
|
1522
|
-
hit,
|
|
1523
|
-
classification,
|
|
1524
|
-
candidate: {
|
|
1525
|
-
target: hit.target,
|
|
1526
|
-
bytes,
|
|
1527
|
-
unmeasuredReason: bytes === undefined ? unmeasuredOf.get(hit.target)?.reason : undefined,
|
|
1528
|
-
suspect: classification.kind === "suspect-install-tree"
|
|
1529
|
-
}
|
|
1530
|
-
});
|
|
1531
|
-
}
|
|
1532
|
-
const candidates = prepared.map((item) => item.candidate);
|
|
1533
|
-
const batch = deletionBatch(candidates, crossDevice, policy);
|
|
1534
|
-
const book = collectSkips(candidates, crossDevice, policy);
|
|
1535
|
-
const noteOf = new Map(book.entries.map((item) => [item.target, item.note]));
|
|
1536
|
-
const entries = [];
|
|
1537
|
-
for (const { hit, classification, candidate } of prepared) {
|
|
1538
|
-
const reason = skipReasonOf(candidate, crossDevice, policy);
|
|
1539
|
-
const deviceKind = crossDevice.get(hit.target);
|
|
1540
|
-
const unmeasured = unmeasuredOf.get(hit.target);
|
|
1541
|
-
entries.push({
|
|
1542
|
-
target: hit.target,
|
|
1543
|
-
project: hit.project,
|
|
1544
|
-
root: hit.root,
|
|
1545
|
-
bytes: candidate.bytes,
|
|
1546
|
-
basis: candidate.bytes === undefined ? undefined : sizeResult.basis,
|
|
1547
|
-
kind: classification.kind,
|
|
1548
|
-
kindReason: classification.reason,
|
|
1549
|
-
crossDevice: deviceKind,
|
|
1550
|
-
unmeasuredCode: unmeasured?.code,
|
|
1551
|
-
unmeasuredReason: unmeasured?.reason,
|
|
1552
|
-
inBatch: reason === null,
|
|
1553
|
-
skipReason: reason ?? undefined,
|
|
1554
|
-
skipNote: reason === null ? undefined : noteOf.get(hit.target)
|
|
1555
|
-
});
|
|
1556
|
-
if (reason !== null)
|
|
1557
|
-
emit?.({ kind: "skipped", target: hit.target, reason });
|
|
1558
|
-
}
|
|
1559
|
-
return {
|
|
1560
|
-
roots: [...resolved.roots],
|
|
1561
|
-
exclude: [...resolved.exclude],
|
|
1562
|
-
include: [...resolved.include],
|
|
1563
|
-
policy,
|
|
1564
|
-
basis: entries.length > 0 ? sizeResult.basis : undefined,
|
|
1565
|
-
entries,
|
|
1566
|
-
batch,
|
|
1567
|
-
skipped: [...book.entries],
|
|
1568
|
-
warnings: [...scanResult.warnings, ...sizeResult.warnings],
|
|
1569
|
-
nameMatches: {
|
|
1570
|
-
exclude: scanResult.excludeMatches,
|
|
1571
|
-
include: scanResult.includeMatches
|
|
1572
|
-
}
|
|
1573
|
-
};
|
|
1574
|
-
});
|
|
1575
|
-
}
|
|
1576
|
-
function buildOutcomeEntries(plan, expectedSet, stale, rejected, removal) {
|
|
1577
|
-
const staleSet = new Set(stale);
|
|
1578
|
-
const rejectedMap = rejected.length > 0 ? new Map(rejected.map((item) => [item.target, item])) : undefined;
|
|
1579
|
-
const removedSet = new Set(removal?.removed ?? []);
|
|
1580
|
-
const missingSet = new Set(removal?.missing ?? []);
|
|
1581
|
-
const failedMap = new Map((removal?.failed ?? []).map((item) => [
|
|
1582
|
-
item.target,
|
|
1583
|
-
item
|
|
1584
|
-
]));
|
|
1585
|
-
const outcomeOf = (entry) => {
|
|
1586
|
-
if (!entry.inBatch)
|
|
1587
|
-
return { kind: "skipped", reason: entry.skipReason };
|
|
1588
|
-
if (expectedSet !== undefined && !expectedSet.has(entry.target))
|
|
1589
|
-
return { kind: "not-expected" };
|
|
1590
|
-
if (staleSet.has(entry.target))
|
|
1591
|
-
return { kind: "stale" };
|
|
1592
|
-
if (rejectedMap !== undefined)
|
|
1593
|
-
return { kind: "rejected", rejection: rejectedMap.get(entry.target) };
|
|
1594
|
-
if (removedSet.has(entry.target))
|
|
1595
|
-
return { kind: "removed" };
|
|
1596
|
-
if (missingSet.has(entry.target))
|
|
1597
|
-
return { kind: "missing" };
|
|
1598
|
-
const failure = failedMap.get(entry.target);
|
|
1599
|
-
if (failure !== undefined)
|
|
1600
|
-
return { kind: "failed", failure };
|
|
1601
|
-
return { kind: "not-attempted", code: removal.aborted.code };
|
|
1602
|
-
};
|
|
1603
|
-
return plan.entries.map((entry) => ({ ...entry, outcome: outcomeOf(entry) }));
|
|
1604
|
-
}
|
|
1605
|
-
async function executeRun(resolved, options, signal) {
|
|
1606
|
-
const emit = options?.onProgress;
|
|
1607
|
-
const startedAt = Date.now();
|
|
1608
|
-
const plan = await executePlan(resolved, options, signal);
|
|
1609
|
-
const expected = options?.expectedBatch;
|
|
1610
|
-
const expectedSet = expected === undefined ? undefined : new Set(expected);
|
|
1611
|
-
const face = expectedSet === undefined ? plan.batch : plan.batch.filter((target) => expectedSet.has(target));
|
|
1612
|
-
const liveSet = new Set(plan.batch);
|
|
1613
|
-
const drift = expected === undefined || expectedSet === undefined ? undefined : {
|
|
1614
|
-
added: plan.batch.filter((target) => !expectedSet.has(target)),
|
|
1615
|
-
removed: expected.filter((target) => !liveSet.has(target))
|
|
1616
|
-
};
|
|
1617
|
-
let validation;
|
|
1618
|
-
let removal;
|
|
1619
|
-
let stale = [];
|
|
1620
|
-
let rejected = [];
|
|
1621
|
-
if (face.length > 0) {
|
|
1622
|
-
const raw = await withPhase("validate", emit, signal, () => validateTargets(face, {
|
|
1623
|
-
roots: resolved.roots,
|
|
1624
|
-
home: resolved.home,
|
|
1625
|
-
style: resolved.style,
|
|
1626
|
-
signal
|
|
1627
|
-
}));
|
|
1628
|
-
const split = splitStaleRejections(raw.rejected, options?.staleTargets);
|
|
1629
|
-
stale = split.stale;
|
|
1630
|
-
rejected = split.rejected;
|
|
1631
|
-
validation = {
|
|
1632
|
-
accepted: raw.accepted,
|
|
1633
|
-
rejected,
|
|
1634
|
-
mappings: raw.mappings
|
|
1635
|
-
};
|
|
1636
|
-
if (rejected.length === 0) {
|
|
1637
|
-
removal = await withPhase("remove", emit, signal, async () => removeTargets(raw.accepted, {
|
|
1638
|
-
roots: await toTrustRoots(resolved.roots),
|
|
1639
|
-
signal,
|
|
1640
|
-
onProgress: (event) => {
|
|
1641
|
-
if (event.kind === "removed" || event.kind === "missing") {
|
|
1642
|
-
emit?.({
|
|
1643
|
-
kind: "removed",
|
|
1644
|
-
target: event.target,
|
|
1645
|
-
outcome: event.kind
|
|
1646
|
-
});
|
|
1647
|
-
return;
|
|
1648
|
-
}
|
|
1649
|
-
emit?.(event);
|
|
1650
|
-
}
|
|
1651
|
-
}));
|
|
1652
|
-
}
|
|
1653
|
-
}
|
|
1654
|
-
let status;
|
|
1655
|
-
if (face.length === 0)
|
|
1656
|
-
status = "nothing-to-do";
|
|
1657
|
-
else if (rejected.length > 0)
|
|
1658
|
-
status = "rejected";
|
|
1659
|
-
else
|
|
1660
|
-
status = "executed";
|
|
1661
|
-
const entries = buildOutcomeEntries(plan, expectedSet, stale, rejected, removal);
|
|
1662
|
-
const releasedBytes = entries.reduce((sum, entry) => isSuccessOutcome(entry.outcome) ? sum + (entry.bytes ?? 0) : sum, 0);
|
|
1663
|
-
const report = {
|
|
1664
|
-
status,
|
|
1665
|
-
plan,
|
|
1666
|
-
validation,
|
|
1667
|
-
removal,
|
|
1668
|
-
entries,
|
|
1669
|
-
stale,
|
|
1670
|
-
releasedBytes,
|
|
1671
|
-
drift
|
|
1672
|
-
};
|
|
1673
|
-
emit?.({ kind: "done", status, elapsedMs: Date.now() - startedAt });
|
|
1674
|
-
return report;
|
|
1675
|
-
}
|
|
1676
|
-
function createSweeper(options) {
|
|
1677
|
-
const resolved = resolveOptions(options);
|
|
1678
|
-
return {
|
|
1679
|
-
options: resolved,
|
|
1680
|
-
async plan(planOptions) {
|
|
1681
|
-
const startedAt = Date.now();
|
|
1682
|
-
const plan = await executePlan(resolved, planOptions, planOptions?.signal);
|
|
1683
|
-
planOptions?.onProgress?.({
|
|
1684
|
-
kind: "plan-done",
|
|
1685
|
-
plan,
|
|
1686
|
-
elapsedMs: Date.now() - startedAt
|
|
1687
|
-
});
|
|
1688
|
-
return plan;
|
|
1689
|
-
},
|
|
1690
|
-
run(runOptions) {
|
|
1691
|
-
return executeRun(resolved, runOptions, runOptions?.signal);
|
|
1692
|
-
}
|
|
1693
|
-
};
|
|
1694
|
-
}
|
|
1695
|
-
// src/render.ts
|
|
1696
|
-
var BANNER = "SWEEP-NM";
|
|
1697
|
-
var BAR_BLOCK = "▍";
|
|
1698
|
-
var TOTAL_BLOCK = "█";
|
|
1699
|
-
var NEUTRAL_BLOCK = "░";
|
|
1700
|
-
var PLATFORM_STYLE = nativeStyle();
|
|
1701
|
-
var NEUTRAL_TIER = { block: NEUTRAL_BLOCK, sgr: "2" };
|
|
1702
|
-
var ROOT_LIST_LIMIT = 3;
|
|
1703
|
-
var bannerLine = (suffix, color) => paint(`${BAR_BLOCK} ${BANNER} ${suffix}`, "1;7", color);
|
|
1704
|
-
var neutralLine = (text, color) => ` ${paint(`${NEUTRAL_BLOCK} ${text}`, "2", color)}`;
|
|
1705
|
-
var TIER_BIG = 512 * 1024 ** 2;
|
|
1706
|
-
var TIER_MID = 100 * 1024 ** 2;
|
|
1707
|
-
function render(options) {
|
|
1708
|
-
const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
|
|
1709
|
-
const style = pathStyle ?? PLATFORM_STYLE;
|
|
1710
|
-
const scope = roots.length > 0 && roots.length <= ROOT_LIST_LIMIT ? `${roots.length} 个根: ${roots.map((root) => sanitizeLine(shortenPath(root, style, home))).join(" · ")}` : `${roots.length} 个根`;
|
|
1711
|
-
const runtime = options.runtime ? ` · ${sanitizeLine(options.runtime)}` : "";
|
|
1712
|
-
const head = bannerLine(`${mode === "execute" ? "执行" : "预览"} · ${scope}${runtime}`, color);
|
|
1713
|
-
const notes = (options.notes ?? []).map((note) => neutralLine(sanitizeLine(note), color));
|
|
1714
|
-
const trailer = (options.trailer ?? []).map((line) => neutralLine(sanitizeLine(line), color));
|
|
1715
|
-
if (entries.length === 0) {
|
|
1716
|
-
return [
|
|
1717
|
-
head,
|
|
1718
|
-
...notes,
|
|
1719
|
-
` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`, "2", color)}`,
|
|
1720
|
-
...trailer
|
|
1721
|
-
].join(`
|
|
1722
|
-
`);
|
|
1723
|
-
}
|
|
1724
|
-
const rows = [...entries].sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
|
|
1725
|
-
const volumeWidth = Math.max(...rows.map((row) => displayWidth(volumeOf(row))));
|
|
1726
|
-
const nameWidth = Math.max(...rows.map((row) => displayWidth(sanitizeLine(row.project))));
|
|
1727
|
-
const body = rows.map((row) => {
|
|
1728
|
-
const fail = mode === "execute" && row.ok === false;
|
|
1729
|
-
const tier = row.bytes === undefined ? NEUTRAL_TIER : tierOf(row.bytes);
|
|
1730
|
-
const mark = mode === "execute" ? paint(fail ? "✗" : "✓", fail ? "31" : "32", color) : paint(tier.block, tier.sgr, color);
|
|
1731
|
-
const volume = padStart(volumeOf(row), volumeWidth);
|
|
1732
|
-
const name = sanitizeLine(row.project);
|
|
1733
|
-
const rawPath = displayPath(row.target, style, home, row.suspect === true);
|
|
1734
|
-
const path = sanitizeLine(rawPath);
|
|
1735
|
-
const rewritten = name !== row.project || path !== rawPath;
|
|
1736
|
-
const tail = tailsOf(row, fail, rewritten);
|
|
1737
|
-
const shown = `${paint(padEnd(name, nameWidth), "1", color)} ${paint(path, "2", color)}`;
|
|
1738
|
-
return ` ${mark} ${volume} ${shown}${tail ? ` ${paint(tail, "2", color)}` : ""}`;
|
|
1739
|
-
});
|
|
1740
|
-
const hint = [
|
|
1741
|
-
paint("加", "2", color),
|
|
1742
|
-
paint("--yes", "1", color),
|
|
1743
|
-
paint("执行删除", "2", color)
|
|
1744
|
-
].join(" ");
|
|
1745
|
-
const foot = mode === "execute" ? footExecute(rows, color, releasedBytes) : ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`合计 ${rows.length} 处 · ${formatBytes(sum(rows))}`, "1", color)} ${hint}`;
|
|
1746
|
-
return [head, ...notes, ...body, foot, ...trailer].join(`
|
|
1747
|
-
`);
|
|
1748
|
-
}
|
|
1749
|
-
function footExecute(rows, color, releasedBytes) {
|
|
1750
|
-
const failed = rows.filter((row) => row.ok === false).length;
|
|
1751
|
-
const released = releasedBytes === undefined ? "" : ` · 释放 ${formatBytes(releasedBytes)}`;
|
|
1752
|
-
return ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`汇总 成功 ${rows.length - failed} 处${released} · 失败 ${failed} 处`, "1", color)}`;
|
|
1753
|
-
}
|
|
1754
|
-
var volumeOf = (row) => row.bytes === undefined ? "?" : formatBytes(row.bytes);
|
|
1755
|
-
var SANITIZED_NOTE = "名字已净化显示";
|
|
1756
|
-
function tailsOf(row, fail, rewritten) {
|
|
1757
|
-
const parts = [];
|
|
1758
|
-
if (rewritten)
|
|
1759
|
-
parts.push(SANITIZED_NOTE);
|
|
1760
|
-
if (row.note)
|
|
1761
|
-
parts.push(sanitizeLine(row.note));
|
|
1762
|
-
if (fail && row.error)
|
|
1763
|
-
parts.push(sanitizeLine(row.error));
|
|
1764
|
-
return parts.join(" ");
|
|
1765
|
-
}
|
|
1766
|
-
function tierOf(bytes) {
|
|
1767
|
-
if (bytes >= TIER_BIG)
|
|
1768
|
-
return { block: "█", sgr: "31" };
|
|
1769
|
-
if (bytes >= TIER_MID)
|
|
1770
|
-
return { block: "▓", sgr: "33" };
|
|
1771
|
-
return { block: "▒", sgr: "36" };
|
|
1772
|
-
}
|
|
1773
|
-
var paint = (text, sgr, color) => color ? `\x1B[${sgr}m${text}\x1B[0m` : text;
|
|
1774
|
-
var sum = (rows) => rows.reduce((total, row) => total + (row.bytes ?? 0), 0);
|
|
1775
|
-
var fold3 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
|
|
1776
|
-
function shortenPath(path, style, home) {
|
|
1777
|
-
if (!home)
|
|
1778
|
-
return path;
|
|
1779
|
-
if (fold3(path, style) === fold3(home, style))
|
|
1780
|
-
return "~";
|
|
1781
|
-
const prefix = `${home}${style.ops.sep}`;
|
|
1782
|
-
return fold3(path, style).startsWith(fold3(prefix, style)) ? `~${path.slice(home.length)}` : path;
|
|
1783
|
-
}
|
|
1784
|
-
function shortenHome(path, home) {
|
|
1785
|
-
return shortenPath(path, PLATFORM_STYLE, home);
|
|
1786
|
-
}
|
|
1787
|
-
function displayPath(target, style, home, keepSuffix = false) {
|
|
1788
|
-
const suffix = `${style.ops.sep}node_modules`;
|
|
1789
|
-
const dir = keepSuffix || !fold3(target, style).endsWith(fold3(suffix, style)) ? target : target.slice(0, -suffix.length);
|
|
1790
|
-
return shortenPath(dir, style, home);
|
|
1791
|
-
}
|
|
1792
|
-
var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
|
|
1793
|
-
var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
|
|
1794
|
-
function displayWidth(text) {
|
|
1795
|
-
let width = 0;
|
|
1796
|
-
for (const char of text) {
|
|
1797
|
-
const code = char.codePointAt(0) ?? 0;
|
|
1798
|
-
width += isFullWidth(code) ? 2 : 1;
|
|
1799
|
-
}
|
|
1800
|
-
return width;
|
|
1801
|
-
}
|
|
1802
|
-
function isFullWidth(code) {
|
|
1803
|
-
return code >= 4352 && code <= 4447 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510;
|
|
1804
|
-
}
|
|
1805
|
-
|
|
1806
|
-
// src/help.ts
|
|
1807
|
-
var COMMAND_COLUMN = 25;
|
|
1808
|
-
function defaultConfigPath() {
|
|
1809
|
-
return resolveConfigPath({ env: {} }).path;
|
|
1810
|
-
}
|
|
1811
|
-
function helpText(color) {
|
|
1812
|
-
const row = (command, desc) => ` ${command.padEnd(COMMAND_COLUMN)} ${desc}`;
|
|
1813
|
-
return [
|
|
1814
|
-
bannerLine("工作区 node_modules 清理", color),
|
|
1815
|
-
"",
|
|
1816
|
-
row("sweep-nm", "预览: 清单 + 体积 + 合计, 零副作用"),
|
|
1817
|
-
row("sweep-nm --yes", "执行删除"),
|
|
1818
|
-
row("sweep-nm --force", "连同疑似安装树一并删除 (默认跳过)"),
|
|
1819
|
-
row("sweep-nm --exclude <name>", "临时追加排除 (可重复, 与配置合并)"),
|
|
1820
|
-
row("sweep-nm --include <name>", "只清理命中名单的目录 (可重复, 与配置合并)"),
|
|
1821
|
-
row("sweep-nm --config <path>", "指定配置文件 (优先于 SWEEP_NM_CONFIG)"),
|
|
1822
|
-
row("sweep-nm config", "查看实际生效的配置: 来源 + 路径 + 文件状态"),
|
|
1823
|
-
row("sweep-nm init", "初始化向导: 交互生成配置文件"),
|
|
1824
|
-
row("sweep-nm --help", "帮助"),
|
|
1825
|
-
"",
|
|
1826
|
-
"说明:",
|
|
1827
|
-
" --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过",
|
|
1828
|
-
" --include 同款匹配口径, 命中才纳入; 同时命中 exclude 的照旧跳过",
|
|
1829
|
-
" 配置未写 exclude 字段时使用内置默认名单 (包管理器 / 版本管理器 / 编辑器扩展等安装树目录)",
|
|
1830
|
-
" --force 只放行「疑似安装树」(安装树形态的目标), 不放宽删除安全闸",
|
|
1831
|
-
" 删除侧要求扫描根为真实路径 (根及其祖先链不含符号链接): 命中 (如 /tmp、/var 形态) 则 --yes 整批拒绝, 改写为真实路径形态 (如 /private/tmp/x) 即放行",
|
|
1832
|
-
` 默认配置位置 (平台自适应; 用了 --config 或 SWEEP_NM_CONFIG 时实际读的不是它): ${sanitizeLine(defaultConfigPath())}`,
|
|
1833
|
-
" 查实际生效的路径: sweep-nm config",
|
|
1834
|
-
"",
|
|
1835
|
-
"退出码: 0 成功 (含预览与空结果); 1 删除失败或跳过 / 配置损坏 / 参数错误"
|
|
1836
|
-
].join(`
|
|
1837
|
-
`);
|
|
1838
|
-
}
|
|
1839
|
-
|
|
1840
|
-
// src/init.ts
|
|
1841
|
-
import { homedir as homedir5 } from "node:os";
|
|
1842
|
-
import { join as join4 } from "node:path";
|
|
1843
|
-
import { createInterface } from "node:readline/promises";
|
|
1844
|
-
var WHITESPACE = /\s/;
|
|
1845
|
-
function expandHome(token) {
|
|
1846
|
-
if (token === "~")
|
|
1847
|
-
return homedir5();
|
|
1848
|
-
if (token.startsWith("~/") || token.startsWith("~\\"))
|
|
1849
|
-
return join4(homedir5(), token.slice(2));
|
|
1850
|
-
return token;
|
|
1851
|
-
}
|
|
1852
|
-
function splitAnswer(answer) {
|
|
1853
|
-
const items = [];
|
|
1854
|
-
let current = "";
|
|
1855
|
-
let openQuote = null;
|
|
1856
|
-
for (let index = 0;index < answer.length; index += 1) {
|
|
1857
|
-
const char = answer[index];
|
|
1858
|
-
if (openQuote !== null) {
|
|
1859
|
-
if (char === openQuote) {
|
|
1860
|
-
openQuote = null;
|
|
1861
|
-
continue;
|
|
1862
|
-
}
|
|
1863
|
-
current += char;
|
|
1864
|
-
continue;
|
|
1865
|
-
}
|
|
1866
|
-
if (char === '"' || char === "'") {
|
|
1867
|
-
if (answer.indexOf(char, index + 1) !== -1) {
|
|
1868
|
-
openQuote = char;
|
|
1869
|
-
continue;
|
|
1870
|
-
}
|
|
1871
|
-
current += char;
|
|
1872
|
-
continue;
|
|
1873
|
-
}
|
|
1874
|
-
if (char === "," || char === "," || WHITESPACE.test(char)) {
|
|
1875
|
-
if (current.length > 0)
|
|
1876
|
-
items.push(current);
|
|
1877
|
-
current = "";
|
|
1878
|
-
continue;
|
|
1879
|
-
}
|
|
1880
|
-
current += char;
|
|
1881
|
-
}
|
|
1882
|
-
if (current.length > 0)
|
|
1883
|
-
items.push(current);
|
|
1884
|
-
return items;
|
|
1885
|
-
}
|
|
1886
|
-
function parseList(answer, fallback) {
|
|
1887
|
-
if (answer === null)
|
|
1888
|
-
return [...fallback];
|
|
1889
|
-
const items = splitAnswer(answer).map(expandHome);
|
|
1890
|
-
return items.length > 0 ? items : [...fallback];
|
|
1891
|
-
}
|
|
1892
|
-
async function runInit(deps) {
|
|
1893
|
-
const {
|
|
1894
|
-
configPath,
|
|
1895
|
-
fileExists,
|
|
1896
|
-
firstSymlinkOnRoot,
|
|
1897
|
-
firstSymlinkOnTarget,
|
|
1898
|
-
writeFile,
|
|
1899
|
-
io
|
|
1900
|
-
} = deps;
|
|
1901
|
-
const { color } = io;
|
|
1902
|
-
function cancelled() {
|
|
1903
|
-
io.print("已取消, 未写入配置");
|
|
1904
|
-
return { state: "cancelled" };
|
|
1905
|
-
}
|
|
1906
|
-
io.print(bannerLine("初始化向导", color));
|
|
1907
|
-
if (await fileExists(configPath)) {
|
|
1908
|
-
const overwrite = await io.confirm(`配置已存在 (${sanitizeLine(configPath)}), 是否覆盖?`, false);
|
|
1909
|
-
if (!overwrite)
|
|
1910
|
-
return { state: "declined-overwrite" };
|
|
1911
|
-
}
|
|
1912
|
-
io.print(neutralLine("首次使用, 先确定扫描范围", color));
|
|
1913
|
-
const home = homedir5();
|
|
1914
|
-
let roots = [];
|
|
1915
|
-
for (;; ) {
|
|
1916
|
-
const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${sanitizeLine(shortenHome(home, home))}`);
|
|
1917
|
-
if (rootsAnswer === null)
|
|
1918
|
-
return cancelled();
|
|
1919
|
-
roots = parseList(rootsAnswer, [home]);
|
|
1920
|
-
const missing = [];
|
|
1921
|
-
const symlinked = [];
|
|
1922
|
-
for (const root of roots) {
|
|
1923
|
-
if (!await fileExists(root)) {
|
|
1924
|
-
missing.push(root);
|
|
1925
|
-
continue;
|
|
1926
|
-
}
|
|
1927
|
-
const link = await firstSymlinkOnRoot(root);
|
|
1928
|
-
if (link !== null)
|
|
1929
|
-
symlinked.push({ root, link });
|
|
1930
|
-
}
|
|
1931
|
-
if (missing.length === 0 && symlinked.length === 0)
|
|
1932
|
-
break;
|
|
1933
|
-
for (const path of missing)
|
|
1934
|
-
io.print(` ${paint("✗", "31", color)} 根不存在: ${sanitizeLine(path)}`);
|
|
1935
|
-
for (const item of symlinked)
|
|
1936
|
-
io.print(` ${paint("✗", "31", color)} 根锚点链上有符号链接: ${sanitizeLine(item.link)} (根: ${sanitizeLine(item.root)}); 删除侧要求真实路径, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`);
|
|
1937
|
-
}
|
|
1938
|
-
const excludeAnswer = await io.ask("排除名单 (目录名)", `回车采用默认名单 (${DEFAULT_EXCLUDE.length} 条)`);
|
|
1939
|
-
if (excludeAnswer === null)
|
|
1940
|
-
return cancelled();
|
|
1941
|
-
const exclude = parseList(excludeAnswer, [...DEFAULT_EXCLUDE]);
|
|
1942
|
-
const includeAnswer = await io.ask("包含名单 (目录名, 可留空)", "回车跳过");
|
|
1943
|
-
if (includeAnswer === null)
|
|
1944
|
-
return cancelled();
|
|
1945
|
-
const include = parseList(includeAnswer, []);
|
|
1946
|
-
io.print(neutralLine(`将写入 ${roots.length} 个扫描根 · 排除 ${exclude.length} 条 · 包含 ${include.length} 条`, color));
|
|
1947
|
-
for (;; ) {
|
|
1948
|
-
if (!await io.confirm("确认写入?", true))
|
|
1949
|
-
return cancelled();
|
|
1950
|
-
const link = await firstSymlinkOnTarget(configPath);
|
|
1951
|
-
if (link === null)
|
|
1952
|
-
break;
|
|
1953
|
-
io.print(` ${paint("✗", "31", color)} 配置路径锚点链上有符号链接: ${sanitizeLine(link)} (配置: ${sanitizeLine(configPath)}); 写入会跟随符号链接改写其目标, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`);
|
|
1954
|
-
}
|
|
1955
|
-
const config = { roots, exclude, include };
|
|
1956
|
-
const text = `${JSON.stringify(config, null, 2)}
|
|
1957
|
-
`;
|
|
1958
|
-
await writeFile(configPath, text);
|
|
1959
|
-
io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath, homedir5()))} ${paint("✓", "32", color)}`);
|
|
1960
|
-
io.print("");
|
|
1961
|
-
io.print(text.trimEnd().split(`
|
|
1962
|
-
`).map((line) => ` ${line}`).join(`
|
|
1963
|
-
`));
|
|
1964
|
-
io.print("");
|
|
1965
|
-
return { state: "written", config };
|
|
1966
|
-
}
|
|
1967
|
-
function setStdinRef(shouldRef) {
|
|
1968
|
-
const fn = shouldRef ? process.stdin.ref : process.stdin.unref;
|
|
1969
|
-
if (typeof fn === "function")
|
|
1970
|
-
fn.call(process.stdin);
|
|
1971
|
-
}
|
|
1972
|
-
function createReadlineIO(color) {
|
|
1973
|
-
const buffered = [];
|
|
1974
|
-
let rl = null;
|
|
1975
|
-
let ended = false;
|
|
1976
|
-
let pending = null;
|
|
1977
|
-
function ensure() {
|
|
1978
|
-
if (rl !== null)
|
|
1979
|
-
return rl;
|
|
1980
|
-
const created = createInterface({
|
|
1981
|
-
input: process.stdin,
|
|
1982
|
-
output: process.stdout
|
|
1983
|
-
});
|
|
1984
|
-
created.on("line", (line) => {
|
|
1985
|
-
if (pending === null) {
|
|
1986
|
-
buffered.push(line);
|
|
1987
|
-
return;
|
|
1988
|
-
}
|
|
1989
|
-
const resolve = pending;
|
|
1990
|
-
pending = null;
|
|
1991
|
-
setStdinRef(false);
|
|
1992
|
-
resolve(line);
|
|
1993
|
-
});
|
|
1994
|
-
created.on("close", () => {
|
|
1995
|
-
ended = true;
|
|
1996
|
-
if (pending === null)
|
|
1997
|
-
return;
|
|
1998
|
-
const resolve = pending;
|
|
1999
|
-
pending = null;
|
|
2000
|
-
setStdinRef(false);
|
|
2001
|
-
resolve(null);
|
|
2002
|
-
});
|
|
2003
|
-
created.on("SIGINT", () => created.close());
|
|
2004
|
-
rl = created;
|
|
2005
|
-
return created;
|
|
2006
|
-
}
|
|
2007
|
-
function readLine(prompt) {
|
|
2008
|
-
if (ended) {
|
|
2009
|
-
const bufferedLine = buffered.shift();
|
|
2010
|
-
if (bufferedLine === undefined)
|
|
2011
|
-
return Promise.resolve(null);
|
|
2012
|
-
process.stdout.write(prompt);
|
|
2013
|
-
return Promise.resolve(bufferedLine);
|
|
2014
|
-
}
|
|
2015
|
-
const created = ensure();
|
|
2016
|
-
created.setPrompt(prompt);
|
|
2017
|
-
created.prompt();
|
|
2018
|
-
const ready = buffered.shift();
|
|
2019
|
-
if (ready !== undefined)
|
|
2020
|
-
return Promise.resolve(ready);
|
|
2021
|
-
setStdinRef(true);
|
|
2022
|
-
return new Promise((resolve) => {
|
|
2023
|
-
pending = resolve;
|
|
2024
|
-
});
|
|
2025
|
-
}
|
|
2026
|
-
return {
|
|
2027
|
-
color,
|
|
2028
|
-
ask(question, hint) {
|
|
2029
|
-
const prompt = hint === undefined ? ` ${question} ` : ` ${question} [${paint(hint, "2", color)}] `;
|
|
2030
|
-
return readLine(prompt);
|
|
2031
|
-
},
|
|
2032
|
-
async confirm(question, defaultYes) {
|
|
2033
|
-
const mark = paint(defaultYes ? "(Y/n)" : "(y/N)", "2", color);
|
|
2034
|
-
const answer = await readLine(` ${question} ${mark} `);
|
|
2035
|
-
if (answer === null)
|
|
2036
|
-
return false;
|
|
2037
|
-
const normalized = answer.trim().toLowerCase();
|
|
2038
|
-
if (normalized === "")
|
|
2039
|
-
return defaultYes;
|
|
2040
|
-
return normalized === "y" || normalized === "yes";
|
|
2041
|
-
},
|
|
2042
|
-
print(line) {
|
|
2043
|
-
process.stdout.write(`${line}
|
|
2044
|
-
`);
|
|
2045
|
-
}
|
|
2046
|
-
};
|
|
2047
|
-
}
|
|
2048
|
-
|
|
2049
|
-
// src/cli.ts
|
|
2050
|
-
function parseArgs(argv) {
|
|
2051
|
-
const options = {
|
|
2052
|
-
command: "sweep",
|
|
2053
|
-
yes: false,
|
|
2054
|
-
force: false,
|
|
2055
|
-
exclude: [],
|
|
2056
|
-
include: [],
|
|
2057
|
-
help: false
|
|
2058
|
-
};
|
|
2059
|
-
const positionals = [];
|
|
2060
|
-
for (let index = 0;index < argv.length; index += 1) {
|
|
2061
|
-
const arg = argv[index];
|
|
2062
|
-
if (arg === undefined)
|
|
2063
|
-
continue;
|
|
2064
|
-
if (arg === "--yes") {
|
|
2065
|
-
options.yes = true;
|
|
2066
|
-
continue;
|
|
2067
|
-
}
|
|
2068
|
-
if (arg === "--force") {
|
|
2069
|
-
options.force = true;
|
|
2070
|
-
continue;
|
|
2071
|
-
}
|
|
2072
|
-
if (arg === "--help" || arg === "-h") {
|
|
2073
|
-
options.help = true;
|
|
2074
|
-
continue;
|
|
2075
|
-
}
|
|
2076
|
-
if (arg === "--exclude" || arg === "--include" || arg === "--config") {
|
|
2077
|
-
const value = argv[index + 1];
|
|
2078
|
-
if (value === undefined || value.startsWith("-")) {
|
|
2079
|
-
return { ok: false, message: `参数 ${arg} 缺少取值` };
|
|
2080
|
-
}
|
|
2081
|
-
if (arg === "--exclude")
|
|
2082
|
-
options.exclude.push(value);
|
|
2083
|
-
else if (arg === "--include")
|
|
2084
|
-
options.include.push(value);
|
|
2085
|
-
else
|
|
2086
|
-
options.config = value;
|
|
2087
|
-
index += 1;
|
|
2088
|
-
continue;
|
|
2089
|
-
}
|
|
2090
|
-
if (arg.startsWith("-"))
|
|
2091
|
-
return { ok: false, message: `未知参数: ${arg}` };
|
|
2092
|
-
positionals.push(arg);
|
|
2093
|
-
}
|
|
2094
|
-
const [only] = positionals;
|
|
2095
|
-
if (positionals.length > 1 || only !== undefined && only !== "init" && only !== "config") {
|
|
2096
|
-
return { ok: false, message: `未知参数: ${positionals.join(" ")}` };
|
|
2097
|
-
}
|
|
2098
|
-
if (only === "init" || only === "config")
|
|
2099
|
-
options.command = only;
|
|
2100
|
-
return { ok: true, options };
|
|
2101
|
-
}
|
|
2102
|
-
var RUNTIME_NAME = typeof Bun === "undefined" ? "node" : "bun";
|
|
2103
|
-
var runtimeLabel = `${RUNTIME_NAME} ${process.versions[RUNTIME_NAME] ?? "unknown"}`;
|
|
2104
|
-
function colorEnabled() {
|
|
2105
|
-
return process.stdout.isTTY === true && !process.env.NO_COLOR;
|
|
2106
|
-
}
|
|
2107
|
-
function interactive() {
|
|
2108
|
-
return process.stdin.isTTY === true && process.stdout.isTTY === true;
|
|
2109
|
-
}
|
|
2110
|
-
function print(line) {
|
|
2111
|
-
process.stdout.write(`${line}
|
|
2112
|
-
`);
|
|
2113
|
-
}
|
|
2114
|
-
function warn(line, color) {
|
|
2115
|
-
const text = sanitizeOutputLine(line);
|
|
2116
|
-
process.stderr.write(color ? `${paint("✗", "31", color)} ${text}
|
|
2117
|
-
` : `${text}
|
|
2118
|
-
`);
|
|
2119
|
-
}
|
|
2120
|
-
function notice(line) {
|
|
2121
|
-
process.stderr.write(`${sanitizeOutputLine(line)}
|
|
2122
|
-
`);
|
|
2123
|
-
}
|
|
2124
|
-
async function fileExists(path) {
|
|
2125
|
-
try {
|
|
2126
|
-
await lstat3(path);
|
|
2127
|
-
return true;
|
|
2128
|
-
} catch {
|
|
2129
|
-
return false;
|
|
2130
|
-
}
|
|
2131
|
-
}
|
|
2132
|
-
function runWizard(configPath, color) {
|
|
2133
|
-
return runInit({
|
|
2134
|
-
configPath,
|
|
2135
|
-
fileExists,
|
|
2136
|
-
firstSymlinkOnRoot,
|
|
2137
|
-
firstSymlinkOnTarget,
|
|
2138
|
-
async writeFile(path, text) {
|
|
2139
|
-
await mkdir(dirname(path), { recursive: true });
|
|
2140
|
-
await writeFile(path, text, "utf8");
|
|
2141
|
-
},
|
|
2142
|
-
io: createReadlineIO(color)
|
|
2143
|
-
});
|
|
2144
|
-
}
|
|
2145
|
-
var SOURCE_LABELS = {
|
|
2146
|
-
flag: "--config 指定",
|
|
2147
|
-
env: "环境变量 SWEEP_NM_CONFIG",
|
|
2148
|
-
"platform-default": "平台默认"
|
|
2149
|
-
};
|
|
2150
|
-
async function reportConfig(resolved, color) {
|
|
2151
|
-
const exists = await fileExists(resolved.path);
|
|
2152
|
-
print(bannerLine(`配置 · 来源: ${SOURCE_LABELS[resolved.source]}`, color));
|
|
2153
|
-
print(neutralLine(`配置路径: ${sanitizeLine(resolved.path)}`, color));
|
|
2154
|
-
print(neutralLine(`文件状态: ${exists ? "存在" : "不存在"}`, color));
|
|
2155
|
-
return 0;
|
|
2156
|
-
}
|
|
2157
|
-
async function resolveConfig(resolved, color) {
|
|
2158
|
-
const loaded = await loadResolvedConfig(resolved);
|
|
2159
|
-
if (loaded.state === "ok")
|
|
2160
|
-
return { config: loaded.config, source: "file" };
|
|
2161
|
-
if (!interactive())
|
|
2162
|
-
return {
|
|
2163
|
-
config: {
|
|
2164
|
-
roots: [process.cwd()],
|
|
2165
|
-
exclude: [...DEFAULT_EXCLUDE],
|
|
2166
|
-
include: []
|
|
2167
|
-
},
|
|
2168
|
-
source: "fallback"
|
|
2169
|
-
};
|
|
2170
|
-
const result = await runWizard(resolved.path, color);
|
|
2171
|
-
if (result.state === "written" && result.config !== undefined) {
|
|
2172
|
-
return { config: result.config, source: "wizard" };
|
|
2173
|
-
}
|
|
2174
|
-
print("配置未写入, 本次未执行清理");
|
|
2175
|
-
return null;
|
|
2176
|
-
}
|
|
2177
|
-
var ABORTED_HINT = "整批中止, 未执行删除";
|
|
2178
|
-
function toRenderEntry(entry) {
|
|
2179
|
-
const notes = [];
|
|
2180
|
-
if (entry.kind === "suspect-install-tree")
|
|
2181
|
-
notes.push(`疑似安装树: ${entry.kindReason}`);
|
|
2182
|
-
if (entry.crossDevice !== undefined)
|
|
2183
|
-
notes.push(crossDeviceNote(entry.crossDevice));
|
|
2184
|
-
if (entry.bytes === undefined && entry.unmeasuredReason !== undefined)
|
|
2185
|
-
notes.push(`体积统计失败: ${entry.unmeasuredReason}`);
|
|
2186
|
-
return {
|
|
2187
|
-
target: entry.target,
|
|
2188
|
-
bytes: entry.bytes,
|
|
2189
|
-
project: basename(entry.project),
|
|
2190
|
-
suspect: entry.kind === "suspect-install-tree",
|
|
2191
|
-
...notes.length > 0 ? { note: notes.join(" ") } : {}
|
|
2192
|
-
};
|
|
2193
|
-
}
|
|
2194
|
-
function outcomeResult(entry) {
|
|
2195
|
-
const { outcome } = entry;
|
|
2196
|
-
switch (outcome.kind) {
|
|
2197
|
-
case "removed":
|
|
2198
|
-
case "missing":
|
|
2199
|
-
case "stale":
|
|
2200
|
-
return { ok: true };
|
|
2201
|
-
case "failed":
|
|
2202
|
-
return { ok: false, error: outcome.failure.message };
|
|
2203
|
-
case "skipped":
|
|
2204
|
-
return outcome.reason === "unmeasured" ? { ok: false } : { ok: false, error: entry.skipNote };
|
|
2205
|
-
case "not-attempted":
|
|
2206
|
-
return { ok: false, error: ABORTED_HINT };
|
|
2207
|
-
case "rejected":
|
|
2208
|
-
case "not-expected":
|
|
2209
|
-
return { ok: false };
|
|
2210
|
-
}
|
|
2211
|
-
}
|
|
2212
|
-
var toExecuteEntry = (entry) => ({
|
|
2213
|
-
...toRenderEntry(entry),
|
|
2214
|
-
...outcomeResult(entry)
|
|
2215
|
-
});
|
|
2216
|
-
function planTrailer(plan) {
|
|
2217
|
-
const candidates = plan.entries.map((entry) => ({
|
|
2218
|
-
target: entry.target,
|
|
2219
|
-
bytes: entry.bytes,
|
|
2220
|
-
unmeasuredReason: entry.unmeasuredReason,
|
|
2221
|
-
suspect: entry.kind === "suspect-install-tree"
|
|
2222
|
-
}));
|
|
2223
|
-
const device = new Map;
|
|
2224
|
-
for (const entry of plan.entries) {
|
|
2225
|
-
if (entry.crossDevice !== undefined)
|
|
2226
|
-
device.set(entry.target, entry.crossDevice);
|
|
2227
|
-
}
|
|
2228
|
-
return [...collectSkips(candidates, device, plan.policy).trailer];
|
|
2229
|
-
}
|
|
2230
|
-
var BUILTIN_EXCLUDE_NAMES = new Set(DEFAULT_EXCLUDE);
|
|
2231
|
-
function collectNameNotes(excludeMatches, includeMatches, color) {
|
|
2232
|
-
const notes = [];
|
|
2233
|
-
const tty = process.stdout.isTTY === true;
|
|
2234
|
-
for (const item of excludeMatches ?? []) {
|
|
2235
|
-
if (item.hits === 0) {
|
|
2236
|
-
if (BUILTIN_EXCLUDE_NAMES.has(item.name))
|
|
2237
|
-
continue;
|
|
2238
|
-
warn(`排除名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
|
|
2239
|
-
} else if (tty)
|
|
2240
|
-
notes.push(`排除生效: ${item.name} (${item.hits} 处)`);
|
|
2241
|
-
}
|
|
2242
|
-
const includes = includeMatches ?? [];
|
|
2243
|
-
for (const item of includes) {
|
|
2244
|
-
if (item.hits === 0)
|
|
2245
|
-
warn(`包含名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
|
|
2246
|
-
else if (tty)
|
|
2247
|
-
notes.push(`包含命中: ${item.name} (${item.hits} 处)`);
|
|
2248
|
-
}
|
|
2249
|
-
if (includes.length > 0 && includes.every((item) => item.hits === 0))
|
|
2250
|
-
warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)", color);
|
|
2251
|
-
return notes;
|
|
2252
|
-
}
|
|
2253
|
-
async function sweep(config, options, color) {
|
|
2254
|
-
const sweeper = createSweeper({
|
|
2255
|
-
roots: config.roots,
|
|
2256
|
-
exclude: mergeNames(config.exclude, options.exclude),
|
|
2257
|
-
include: mergeNames(config.include, options.include),
|
|
2258
|
-
policy: { releaseSuspects: options.force }
|
|
2259
|
-
});
|
|
2260
|
-
const runtime = process.stdout.isTTY === true ? runtimeLabel : undefined;
|
|
2261
|
-
const home = homedir6();
|
|
2262
|
-
const onProgress = (event) => {
|
|
2263
|
-
if (event.kind === "warning")
|
|
2264
|
-
warn(event.warning.message, color);
|
|
2265
|
-
};
|
|
2266
|
-
const nameNotesOf = (plan) => collectNameNotes(plan.nameMatches.exclude, plan.nameMatches.include, color);
|
|
2267
|
-
if (!options.yes) {
|
|
2268
|
-
const plan = await sweeper.plan({ onProgress });
|
|
2269
|
-
print(render({
|
|
2270
|
-
mode: "preview",
|
|
2271
|
-
roots: plan.roots,
|
|
2272
|
-
entries: plan.entries.map(toRenderEntry),
|
|
2273
|
-
color,
|
|
2274
|
-
home,
|
|
2275
|
-
notes: nameNotesOf(plan),
|
|
2276
|
-
runtime,
|
|
2277
|
-
trailer: planTrailer(plan)
|
|
2278
|
-
}));
|
|
2279
|
-
return 0;
|
|
2280
|
-
}
|
|
2281
|
-
const report = await sweeper.run({ onProgress });
|
|
2282
|
-
if (report.status === "rejected") {
|
|
2283
|
-
const rejected = report.validation?.rejected ?? [];
|
|
2284
|
-
warn(`整批拒绝: ${rejected.length} 个目标未通过安全闸, 未执行任何删除`, color);
|
|
2285
|
-
for (const item of rejected)
|
|
2286
|
-
notice(` ${item.target} (${item.message})`);
|
|
2287
|
-
return 1;
|
|
2288
|
-
}
|
|
2289
|
-
print(render({
|
|
2290
|
-
mode: "execute",
|
|
2291
|
-
roots: report.plan.roots,
|
|
2292
|
-
entries: report.entries.map(toExecuteEntry),
|
|
2293
|
-
color,
|
|
2294
|
-
home,
|
|
2295
|
-
releasedBytes: report.releasedBytes,
|
|
2296
|
-
notes: nameNotesOf(report.plan),
|
|
2297
|
-
runtime,
|
|
2298
|
-
trailer: planTrailer(report.plan)
|
|
2299
|
-
}));
|
|
2300
|
-
if (report.removal?.aborted !== undefined) {
|
|
2301
|
-
warn(`整批中止: ${report.removal.aborted.message}`, color);
|
|
2302
|
-
notice(` 本轮未执行删除: ${report.plan.batch.length} 处`);
|
|
2303
|
-
}
|
|
2304
|
-
const summary = summarizeReport(report);
|
|
2305
|
-
return summary.failed === 0 && summary.unprocessed === 0 && !summary.aborted ? 0 : 1;
|
|
2306
|
-
}
|
|
2307
|
-
async function main() {
|
|
2308
|
-
const color = colorEnabled();
|
|
2309
|
-
const parsed = parseArgs(process.argv.slice(2));
|
|
2310
|
-
if (!parsed.ok) {
|
|
2311
|
-
warn(`参数错误: ${parsed.message} (用 --help 查看用法)`, color);
|
|
2312
|
-
return 1;
|
|
2313
|
-
}
|
|
2314
|
-
const { options } = parsed;
|
|
2315
|
-
if (options.help) {
|
|
2316
|
-
print(helpText(color));
|
|
2317
|
-
return 0;
|
|
2318
|
-
}
|
|
2319
|
-
try {
|
|
2320
|
-
const resolvedPath = resolveConfigPath({ flag: options.config });
|
|
2321
|
-
if (options.command === "init") {
|
|
2322
|
-
if (!interactive()) {
|
|
2323
|
-
warn("init 需要交互终端 (请在终端直接运行, 不要重定向或经管道)", color);
|
|
2324
|
-
return 1;
|
|
2325
|
-
}
|
|
2326
|
-
const result = await runWizard(resolvedPath.path, color);
|
|
2327
|
-
if (result.state === "written")
|
|
2328
|
-
print(neutralLine("运行 sweep-nm 查看预览", color));
|
|
2329
|
-
else
|
|
2330
|
-
print("配置未变更");
|
|
2331
|
-
return 0;
|
|
2332
|
-
}
|
|
2333
|
-
if (options.command === "config") {
|
|
2334
|
-
return await reportConfig(resolvedPath, color);
|
|
2335
|
-
}
|
|
2336
|
-
const resolved = await resolveConfig(resolvedPath, color);
|
|
2337
|
-
if (resolved === null)
|
|
2338
|
-
return 0;
|
|
2339
|
-
if (resolved.source === "fallback") {
|
|
2340
|
-
const roots = resolved.config.roots.join(", ");
|
|
2341
|
-
if (options.yes) {
|
|
2342
|
-
warn("拒绝执行: 当前无配置文件, --yes 不可用", color);
|
|
2343
|
-
notice(` 将扫的根: ${roots}`);
|
|
2344
|
-
notice(" 先 sweep-nm init 生成配置, 或用 --config 指定配置文件");
|
|
2345
|
-
return 1;
|
|
2346
|
-
}
|
|
2347
|
-
notice(`未找到配置文件, 本次以当前目录为根: ${roots} (想固定此设置, 运行 sweep-nm init)`);
|
|
2348
|
-
}
|
|
2349
|
-
const freshConfig = resolved.source === "wizard";
|
|
2350
|
-
if (freshConfig && options.yes) {
|
|
2351
|
-
notice("首次配置已生成; 本轮先预览, 复核后可再运行 --yes 执行");
|
|
2352
|
-
}
|
|
2353
|
-
return await sweep(resolved.config, freshConfig ? { ...options, yes: false } : options, color);
|
|
2354
|
-
} catch (error) {
|
|
2355
|
-
warn(error instanceof Error ? error.message : String(error), color);
|
|
2356
|
-
return 1;
|
|
2357
|
-
}
|
|
2358
|
-
}
|
|
2359
|
-
process.exitCode = await main();
|
|
1
|
+
import{readFileSync as readFileSync5}from"node:fs";import{lstat as lstat5,mkdir,writeFile}from"node:fs/promises";import{homedir as homedir8}from"node:os";import{dirname as dirname2}from"node:path";import{readFileSync as readFileSync4}from"node:fs";import{dirname,join as join2}from"node:path";import{fileURLToPath}from"node:url";import{existsSync,realpathSync}from"node:fs";import{posix,win32}from"node:path";var SUPPORTED_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn","volta"],LIB_NODE_MODULES_HEURISTIC_REASON="命中标准 <prefix>/lib/node_modules 全局目录";function normalizeSlashes(path){return path.replaceAll("\\","/").replace(/\/+$/,"")}function joinForPath(base,...parts){return/^(?:[A-Za-z]:[/\\]|\\\\)/.test(base)||base.includes("\\")?win32.join(base,...parts):posix.join(base,...parts)}function foldPath(path){return normalizeSlashes(path).toLowerCase()}function isWithinDir(child,parent){let normParent=foldPath(parent);if(normParent==="")return!1;let normChild=foldPath(child);return normChild===normParent||normChild.startsWith(`${normParent}/`)}function collectRawFoldedCandidates(foldedRoot,rawPaths){let seen=new Set([foldedRoot]),out=[];for(let raw of rawPaths??[]){if(typeof raw!=="string"||raw.trim()==="")continue;let folded=foldPath(raw);if(!seen.has(folded))seen.add(folded),out.push(folded)}return out}function expandRootVariants(root,realpath){let trimmed=root.trim();if(trimmed==="")return[];let out=[trimmed],resolved=realpath(trimmed);if(foldPath(resolved)!==foldPath(trimmed))out.push(resolved);return out}function detectEphemeral(candidates,packageRoot){for(let p of candidates){if(p.includes("/_npx/"))return{kind:"ephemeral",runner:"npx",reason:"位于 npx 临时缓存目录 (_npx)",packageRoot};if(p.includes("/bunx-"))return{kind:"ephemeral",runner:"bunx",reason:"位于 bunx 临时执行目录",packageRoot};if(p.includes("/pnpm/dlx/")||p.includes("/pnpm-cache/dlx/")||p.includes("/pnpm-dlx/"))return{kind:"ephemeral",runner:"pnpm-dlx",reason:"位于 pnpm dlx 临时缓存目录",packageRoot};if(p.includes("/xfs-")&&p.includes("/dlx-")||p.includes("/berry/cache/")&&p.includes("/dlx"))return{kind:"ephemeral",runner:"yarn-dlx",reason:"位于 yarn dlx 临时执行目录",packageRoot};if(p.includes("/deno/npm/"))return{kind:"ephemeral",runner:"deno",reason:"位于 Deno npm 缓存目录 (/deno/npm/)",packageRoot}}return null}function buildEnvRootRules(env,realpath){let rules=[],directSpecs=[["volta",env.VOLTA_HOME,"位于环境变量 VOLTA_HOME 目录内"],["bun",env.BUN_INSTALL,"位于环境变量 BUN_INSTALL 目录内"],["bun",env.BUN_INSTALL_GLOBAL_DIR,"位于环境变量 BUN_INSTALL_GLOBAL_DIR 目录内"],["pnpm",env.PNPM_HOME,"位于环境变量 PNPM_HOME 目录内"]];for(let[pm,rawRoot,reason]of directSpecs){if(rawRoot===void 0||rawRoot.trim()==="")continue;let roots=expandRootVariants(rawRoot,realpath);if(roots.length>0)rules.push({pm,roots,reason})}let npmPrefix=env.NPM_CONFIG_PREFIX??env.npm_config_prefix;if(npmPrefix!==void 0&&npmPrefix.trim()!==""){let npmRoots=[];for(let base of expandRootVariants(npmPrefix,realpath)){let norm=normalizeSlashes(base);if(norm==="")continue;npmRoots.push(`${norm}/lib/node_modules`,`${norm}/node_modules`)}if(npmRoots.length>0)rules.push({pm:"npm",roots:npmRoots,reason:"位于环境变量 NPM_CONFIG_PREFIX 目录内"})}return rules}function detectFromEnvRoots(candidates,env,packageRoot,realpath){if(candidates.length===0)return null;let rules=buildEnvRootRules(env,realpath);for(let candidate of candidates)for(let rule of rules)if(rule.roots.some((root)=>isWithinDir(candidate,root)))return{kind:"global",pm:rule.pm,reason:rule.reason,packageRoot};return null}var GLOBAL_PATH_SIGNATURES=[["volta",["/.volta/tools/","/volta/tools/","/.volta/bin/","/volta/bin/"],"命中 Volta 全局工具安装目录"],["bun",["/.bun/install/global/","/.bun/bin/"],"命中 Bun 全局安装目录 (~/.bun)"],["pnpm",["/pnpm/global/","/library/pnpm/global/","/.local/share/pnpm/global/","/appdata/local/pnpm/global/","/pnpm-global/"],"命中 pnpm 全局安装目录"],["yarn",["/.config/yarn/global/","/yarn/data/global/","/yarn/config/global/","/yarn/global/","/.yarn/global/"],"命中 Yarn 全局安装目录"],["npm",["/appdata/roaming/npm/node_modules/","/usr/local/lib/node_modules/","/usr/lib/node_modules/","/opt/homebrew/lib/node_modules/","/.nvm/versions/node/","/nvm4w/","/fnm/node-versions/","/.fnm/node-versions/","/fnm_multishells/","/.asdf/installs/nodejs/","/.local/share/mise/installs/node/","/.mise/installs/node/","/mise/installs/node/","/.nodenv/versions/","/.n/lib/node_modules/","/program files/nodejs/node_modules/","/scoop/apps/nodejs/"],"命中 npm 全局安装目录"]];function detectFromStandardPaths(candidates,packageRoot){for(let candidate of candidates)for(let[pm,markers,reason]of GLOBAL_PATH_SIGNATURES)if(markers.some((marker)=>candidate.includes(marker)))return{kind:"global",pm,reason,packageRoot};return null}function detectFromGlobalRoots(candidates,globalRoots,packageRoot,realpath){if(globalRoots===void 0||candidates.length===0)return null;for(let candidate of candidates)for(let pm of SUPPORTED_PACKAGE_MANAGERS){let root=globalRoots[pm];if(root===void 0||root.trim()==="")continue;if(expandRootVariants(root,realpath).some((v)=>isWithinDir(candidate,v)))return{kind:"global",pm,reason:`匹配 ${pm} 实查全局目录 (${root})`,packageRoot}}return null}function detectFromLibNodeModulesHeuristic(packageRoot,pathExists){let libIdx=packageRoot.toLowerCase().lastIndexOf("/lib/node_modules/");if(libIdx<=0)return null;let prefixDir=packageRoot.slice(0,libIdx);if(pathExists(joinForPath(prefixDir,"package.json")))return null;return{kind:"global",pm:"npm",reason:LIB_NODE_MODULES_HEURISTIC_REASON,packageRoot}}function detectProjectPm(projectDir,pathExists){if(pathExists(joinForPath(projectDir,"bun.lock"))||pathExists(joinForPath(projectDir,"bun.lockb")))return"bun";if(pathExists(joinForPath(projectDir,"pnpm-lock.yaml")))return"pnpm";if(pathExists(joinForPath(projectDir,"yarn.lock")))return"yarn";return"npm"}function detectGlobalForCandidates(candidates,input){if(candidates.length===0)return null;return detectFromEnvRoots(candidates,input.env,input.packageRoot,input.realpath)??detectFromStandardPaths(candidates,input.packageRoot)??detectFromGlobalRoots(candidates,input.globalRoots,input.packageRoot,input.realpath)}function detectInstallOriginFromPath(input){let env=input.env??process.env,pathExists=input.pathExists??existsSync,realpath=input.realpath??safeRealpath,packageRoot=normalizeSlashes(input.packageRoot),foldedRoot=packageRoot.toLowerCase(),rawCandidates=collectRawFoldedCandidates(foldedRoot,input.rawPaths);if(!foldedRoot.includes("/node_modules/")&&pathExists(joinForPath(input.packageRoot,"src","cli.ts")))return{kind:"source",reason:"包根目录位于本地源码工作树 (存在 src/cli.ts)",packageRoot};let ephemeral=detectEphemeral([foldedRoot,...rawCandidates],packageRoot);if(ephemeral!==null)return ephemeral;let fromRoot=detectGlobalForCandidates([foldedRoot],{env,globalRoots:input.globalRoots,packageRoot,realpath});if(fromRoot!==null)return fromRoot;let fromRaw=detectGlobalForCandidates(rawCandidates,{env,globalRoots:input.globalRoots,packageRoot,realpath});if(fromRaw!==null)return fromRaw;let fromHeuristic=detectFromLibNodeModulesHeuristic(packageRoot,pathExists);if(fromHeuristic!==null)return fromHeuristic;let nmIdx=foldedRoot.indexOf("/node_modules/");if(nmIdx>0){let projectDir=packageRoot.slice(0,nmIdx),probeDir=input.packageRoot.startsWith("\\\\")?`\\\\${projectDir.slice(2)}`:projectDir;if(pathExists(joinForPath(probeDir,"package.json")))return{kind:"local-project",projectDir,suggestedPm:detectProjectPm(probeDir,pathExists),reason:`位于项目本地 node_modules (${projectDir})`,packageRoot}}return{kind:"unknown",reason:"未匹配已知全局包管理器路径或本地源码工作树",packageRoot}}function safeRealpath(path){try{return(realpathSync.native??realpathSync)(path)}catch{return path}}var PACKAGE_NAME_RE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,SEMVER_RE=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/,TARGET_SPEC_RE=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;function isValidPackageName(name){return name.length>0&&name.length<=214&&PACKAGE_NAME_RE.test(name)}function isValidTargetSpec(spec){return TARGET_SPEC_RE.test(spec)}function isValidRegistryUrl(raw){if(raw.length===0||/[\s"'`$|;&<>\\?#\p{Cc}]/u.test(raw))return!1;try{let parsed=new URL(raw);if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return!1;if(parsed.username!==""||parsed.password!==""||parsed.search!==""||parsed.hash!=="")return!1;return parsed.hostname.length>0}catch{return!1}}function parseSemver(raw){let match=SEMVER_RE.exec(raw.trim());if(match===null)return null;let major=Number(match[1]),minor=Number(match[2]),patch=Number(match[3]);if(!Number.isSafeInteger(major)||!Number.isSafeInteger(minor)||!Number.isSafeInteger(patch))return null;let prerelease=match[4]===void 0?[]:match[4].split(".");return{major,minor,patch,prerelease}}function comparePrereleaseId(a,b){let aNum=/^\d+$/.test(a),bNum=/^\d+$/.test(b);if(aNum&&bNum)return Math.sign(Number(a)-Number(b));if(aNum&&!bNum)return-1;if(!aNum&&bNum)return 1;if(a===b)return 0;return a<b?-1:1}function compareSemver(a,b){let left=parseSemver(a),right=parseSemver(b);if(left===null||right===null)return null;if(left.major!==right.major)return left.major<right.major?-1:1;if(left.minor!==right.minor)return left.minor<right.minor?-1:1;if(left.patch!==right.patch)return left.patch<right.patch?-1:1;let lPre=left.prerelease,rPre=right.prerelease;if(lPre.length===0&&rPre.length===0)return 0;if(lPre.length===0)return 1;if(rPre.length===0)return-1;let limit=Math.min(lPre.length,rPre.length);for(let i=0;i<limit;i+=1){let diff=comparePrereleaseId(lPre[i],rPre[i]);if(diff!==0)return diff<0?-1:1}if(lPre.length===rPre.length)return 0;return lPre.length<rPre.length?-1:1}var PM_SET=new Set(SUPPORTED_PACKAGE_MANAGERS);function isPackageManager(value){return PM_SET.has(value)}function applyPm(options,value){let normalized=value.trim().toLowerCase();if(!isPackageManager(normalized))return`参数 --pm 不支持 "${value}" (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`;return options.pm=normalized,null}function applyRegistry(options,value){let trimmed=value.trim();if(!isValidRegistryUrl(trimmed))return`参数 --registry 不是合法的 http(s) URL: "${value}"`;return options.registry=trimmed,null}function nextValueToken(argv,index){let next=argv[index+1];if(next===void 0||next===""||next.startsWith("-"))return null;return next}function parseUpdateArgs(argv){let options={check:!1,force:!1,help:!1};for(let i=0;i<argv.length;i+=1){let arg=argv[i];if(arg==="--help"||arg==="-h"){options.help=!0;continue}if(arg==="--check"){options.check=!0;continue}if(arg==="--force"){options.force=!0;continue}if(arg==="--pm"){let val=nextValueToken(argv,i);if(val===null)return{ok:!1,message:`参数 --pm 缺少取值 (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`};let err=applyPm(options,val);if(err!==null)return{ok:!1,message:err};i+=1;continue}if(arg.startsWith("--pm=")){let val=arg.slice(5);if(val==="")return{ok:!1,message:`参数 --pm 缺少取值 (可选值: ${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`};let err=applyPm(options,val);if(err!==null)return{ok:!1,message:err};continue}if(arg==="--registry"){let val=nextValueToken(argv,i);if(val===null)return{ok:!1,message:"参数 --registry 缺少取值"};let err=applyRegistry(options,val);if(err!==null)return{ok:!1,message:err};i+=1;continue}if(arg.startsWith("--registry=")){let val=arg.slice(11);if(val==="")return{ok:!1,message:"参数 --registry 缺少取值"};let err=applyRegistry(options,val);if(err!==null)return{ok:!1,message:err};continue}return{ok:!1,message:`子命令 update 不支持参数: ${arg} (用 update --help 查看用法)`}}return{ok:!0,options}}function formatUpdateHelp(binName,packageName){return[`${binName} update: 自动识别当前安装方式 (bun / npm / pnpm / yarn / volta) 并更新 ${packageName}`,"",`用法: ${binName} update [选项]`,"","选项:"," --check 仅检查最新版本与当前安装方式, 不执行更新",` --pm <管理器> 手动指定更新所用的包管理器 (${SUPPORTED_PACKAGE_MANAGERS.join(" | ")})`," --registry <url> 临时指定本次查询与更新所用的 npm registry"," --force 即使已是最新版本仍强制重新安装"," -h, --help 显示本帮助","","说明:"," • 安装方式按当前包在磁盘上的真实落位路径判定, 不受运行时的 bun/node 切换影响"," • 通过 npx / bunx / pnpm dlx / yarn dlx 临时运行, 或处于本地源码开发态时不会盲目覆盖全局"," • 更新子进程在独立临时空目录执行, 隔绝当前工作目录的 .npmrc / bunfig.toml / package.json 干扰"].join(`
|
|
2
|
+
`)}import{spawnSync}from"node:child_process";import{existsSync as existsSync2,mkdtempSync,readFileSync as readFileSync2,rmSync,statSync}from"node:fs";import{homedir as homedir2,tmpdir}from"node:os";import{join,posix as posix2,win32 as win323}from"node:path";function normalizeRegistryUrl(url){return url.trim().replace(/\/+$/,"")}function extractScope(packageName){if(!packageName.startsWith("@"))return null;let slash=packageName.indexOf("/");return slash>1?packageName.slice(0,slash):null}function unquotePair(raw){let trimmed=raw.trim();if(trimmed.length>=2&&(trimmed.startsWith('"')&&trimmed.endsWith('"')||trimmed.startsWith("'")&&trimmed.endsWith("'")))return trimmed.slice(1,-1);return trimmed}function stripTomlComment(line){let inDouble=!1,inSingle=!1,escaped=!1;for(let i=0;i<line.length;i+=1){let ch=line[i];if(inDouble){if(escaped)escaped=!1;else if(ch==="\\")escaped=!0;else if(ch==='"')inDouble=!1;continue}if(inSingle){if(ch==="'")inSingle=!1;continue}if(ch==="#")return line.slice(0,i).trim();if(ch==='"')inDouble=!0;else if(ch==="'")inSingle=!0}return line.trim()}function parseTomlString(raw){let trimmed=raw.trim();if(trimmed.length<2)return null;let quote=trimmed[0];if(quote!=='"'&"e!=="'")return null;if(quote==="'"){let end=trimmed.indexOf("'",1);return end===trimmed.length-1?trimmed.slice(1,end):null}let out="",escaped=!1;for(let i=1;i<trimmed.length;i+=1){let ch=trimmed[i];if(escaped){out+=ch,escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"')return i===trimmed.length-1?out:null;out+=ch}return null}function extractInlineField(body,fieldName){let m=new RegExp(`(?:^|[,{])\\s*${fieldName}\\s*=\\s*("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|'[^']*')`).exec(body);return m===null?null:parseTomlString(m[1])}function normalizeUrlPath(pathname){let trimmed=pathname.replace(/\/+$/,"");return trimmed===""?"/":`${trimmed}/`}function expandEnvToken(raw,env,allowBareDollar){let missing=!1,expanded=raw.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(_m,name)=>{let val=env[name];if(typeof val!=="string"||val==="")return missing=!0,"";return val});if(missing||expanded.includes("${"))return null;if(allowBareDollar){if(expanded=expanded.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(_m,name)=>{let val=env[name];if(typeof val!=="string"||val==="")return missing=!0,"";return val}),missing)return null}let trimmed=expanded.trim();if(trimmed===""||/[\s\p{Cc}]/u.test(trimmed))return null;return trimmed}function parseRegistryFromNpmrc(content,packageName){let scope=extractScope(packageName),globalReg=null,scopedReg=null;for(let rawLine of content.split(/\r?\n/)){let line=rawLine.trim();if(line===""||line.startsWith("#")||line.startsWith(";"))continue;let eq=line.indexOf("=");if(eq<=0)continue;let key=line.slice(0,eq).trim(),value=unquotePair(line.slice(eq+1));if(!isValidRegistryUrl(value))continue;if(scope!==null&&key===`${scope}:registry`)scopedReg=value;else if(key==="registry")globalReg=value}return scopedReg??globalReg}function parseAuthTokenFromNpmrc(content,registryUrl,env=process.env){let target;try{target=new URL(normalizeRegistryUrl(registryUrl))}catch{return null}let targetHost=target.host.toLowerCase(),targetPath=normalizeUrlPath(target.pathname),matched=null;for(let rawLine of content.split(/\r?\n/)){let line=rawLine.trim();if(line===""||line.startsWith("#")||line.startsWith(";"))continue;let eq=line.indexOf("=");if(eq<=0)continue;let key=line.slice(0,eq).trim();if(!key.startsWith("//")||!key.endsWith(":_authToken"))continue;let hostPath=key.slice(2,-11);if(hostPath==="")continue;let entry;try{entry=new URL(`https://${hostPath}`)}catch{continue}if(entry.host.toLowerCase()!==targetHost||normalizeUrlPath(entry.pathname)!==targetPath)continue;let token=expandEnvToken(unquotePair(line.slice(eq+1)),env,!1);if(token!==null)matched=token}return matched}function parseScopedSubtableHeader(section){let m=/^install\.scopes\.(?:"([^"]+)"|'([^']+)'|([^\s.\]]+))$/.exec(section);if(m===null)return null;let scopeName=(m[1]??m[2]??m[3]??"").trim();return scopeName.startsWith("@")?scopeName:null}function applyBunfigKeyValue(target,key,rhs){let str=parseTomlString(rhs);if(str===null)return;if(key==="url"&&isValidRegistryUrl(str))target.url=str;else if(key==="token"&&str.trim()!=="")target.token=str}function applyBunfigRegistryRhs(target,rhs){let str=parseTomlString(rhs);if(str!==null){if(isValidRegistryUrl(str))target.url=str;return}if(!rhs.startsWith("{")||!rhs.endsWith("}"))return;let url=extractInlineField(rhs,"url");if(url!==null&&isValidRegistryUrl(url))target.url=url;let token=extractInlineField(rhs,"token");if(token!==null&&token.trim()!=="")target.token=token}function parseBunfigInstall(content){let result={globalEntry:{},scopes:new Map,globalDir:null},section="",getScopeEntry=(scopeName)=>{let existing=result.scopes.get(scopeName);if(existing!==void 0)return existing;let created={};return result.scopes.set(scopeName,created),created};for(let rawLine of content.split(/\r?\n/)){let line=stripTomlComment(rawLine);if(line==="")continue;let secMatch=/^\[([^\]]+)\]$/.exec(line);if(secMatch!==null){section=secMatch[1].trim();continue}let eq=line.indexOf("=");if(eq<=0)continue;let rawKey=line.slice(0,eq).trim(),rhs=line.slice(eq+1).trim();if(section==="install"){if(rawKey==="registry")applyBunfigRegistryRhs(result.globalEntry,rhs);else if(rawKey==="globalDir"){let dir=parseTomlString(rhs);if(dir!==null&&dir.trim()!=="")result.globalDir=dir.trim()}continue}if(section==="install.registry"){applyBunfigKeyValue(result.globalEntry,rawKey,rhs);continue}if(section==="install.scopes"){let scopeName=unquotePair(rawKey);if(scopeName.startsWith("@"))applyBunfigRegistryRhs(getScopeEntry(scopeName),rhs);continue}let subScope=parseScopedSubtableHeader(section);if(subScope!==null)applyBunfigKeyValue(getScopeEntry(subScope),rawKey,rhs)}return result}function parseRegistryFromBunfig(content,packageName){let parsed=parseBunfigInstall(content),scope=extractScope(packageName);return(scope!==null?parsed.scopes.get(scope)?.url:void 0)??parsed.globalEntry.url??null}function matchesRegistryOriginAndPath(targetUrl,entryUrl){try{let a=new URL(normalizeRegistryUrl(targetUrl)),b=new URL(normalizeRegistryUrl(entryUrl));return a.protocol===b.protocol&&a.host.toLowerCase()===b.host.toLowerCase()&&normalizeUrlPath(a.pathname)===normalizeUrlPath(b.pathname)}catch{return!1}}function parseAuthTokenFromBunfig(content,registryUrl,packageName,env=process.env){let parsed=parseBunfigInstall(content),scope=extractScope(packageName),ordered=[];if(scope!==null){let scoped=parsed.scopes.get(scope);if(scoped!==void 0)ordered.push(scoped)}ordered.push(parsed.globalEntry);for(let[k,entry]of parsed.scopes.entries())if(k!==scope)ordered.push(entry);for(let entry of ordered){if(entry.url===void 0||entry.token===void 0)continue;if(!matchesRegistryOriginAndPath(registryUrl,entry.url))continue;let expanded=expandEnvToken(entry.token,env,!0);if(expanded!==null)return expanded}return null}function parseGlobalDirFromBunfig(content){return parseBunfigInstall(content).globalDir}import{readFileSync}from"node:fs";import{homedir}from"node:os";var DEFAULT_REGISTRY="https://registry.npmjs.org",DEFAULT_FETCH_TIMEOUT_MS=1e4;function defaultReadText(path){try{return readFileSync(path,"utf8")}catch{return null}}function resolveRegistry(input){if(input.flagRegistry!==void 0&&isValidRegistryUrl(input.flagRegistry))return normalizeRegistryUrl(input.flagRegistry);let env=input.env??process.env,envReg=env.NPM_CONFIG_REGISTRY??env.npm_config_registry;if(typeof envReg==="string"&&isValidRegistryUrl(envReg))return normalizeRegistryUrl(envReg);let home=input.homeDir??homedir(),readText=input.readText??defaultReadText;if(input.pm==="bun"){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let found=parseRegistryFromBunfig(bunfig,input.packageName);if(found!==null)return normalizeRegistryUrl(found)}}let npmrc=readText(joinForPath(home,".npmrc"));if(npmrc!==null){let found=parseRegistryFromNpmrc(npmrc,input.packageName);if(found!==null)return normalizeRegistryUrl(found)}if(input.pm===void 0){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let found=parseRegistryFromBunfig(bunfig,input.packageName);if(found!==null)return normalizeRegistryUrl(found)}}return DEFAULT_REGISTRY}function resolveRegistryAuthToken(input){if(!isValidRegistryUrl(input.registry))return;let env=input.env??process.env,home=input.homeDir??homedir(),readText=input.readText??defaultReadText,base=normalizeRegistryUrl(input.registry);if(input.pm==="bun"){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let token=parseAuthTokenFromBunfig(bunfig,base,input.packageName,env);if(token!==null)return token}}let npmrc=readText(joinForPath(home,".npmrc"));if(npmrc!==null){let token=parseAuthTokenFromNpmrc(npmrc,base,env);if(token!==null)return token}if(input.pm===void 0){let bunfig=readText(joinForPath(home,".bunfig.toml"));if(bunfig!==null){let token=parseAuthTokenFromBunfig(bunfig,base,input.packageName,env);if(token!==null)return token}}return}function cleanMessage(raw,secret){return(secret!==void 0&&secret!==""?raw.replaceAll(secret,"[REDACTED]"):raw).replace(/\p{Cc}/gu," ").replace(/\s+/g," ").trim()}async function fetchLatestVersion(input){let tag=input.tag??"latest";if(!isValidPackageName(input.packageName))return{ok:!1,code:"invalid-response",message:`非法包名: ${cleanMessage(input.packageName)}`};if(!isValidTargetSpec(tag)||!isValidRegistryUrl(input.registry))return{ok:!1,code:"invalid-response",message:"非法的 registry 地址或版本标签"};let base=normalizeRegistryUrl(input.registry),url=`${base}/${encodeURIComponent(input.packageName)}/${encodeURIComponent(tag)}`,fetchFn=input.fetchFn??fetch,timeoutMs=input.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS,authToken=typeof input.authToken==="string"&&input.authToken.trim()!==""&&!/[\s\p{Cc}]/u.test(input.authToken)?input.authToken.trim():void 0,headers={accept:"application/vnd.npm.install-v1+json, application/json"};if(authToken!==void 0)headers.authorization=`Bearer ${authToken}`;let response;try{response=await fetchFn(url,{headers,signal:AbortSignal.timeout(timeoutMs)})}catch(error){let detail=error instanceof Error?cleanMessage(error.message,authToken):"";return{ok:!1,code:"network",message:detail===""?`无法连接包注册表 (${base})`:`无法连接包注册表 (${base}): ${detail}`}}if(response.status===401||response.status===403)return{ok:!1,code:"auth",status:response.status,message:`访问包注册表 ${base} 鉴权失败 (HTTP ${response.status}), 请检查 ~/.npmrc / ~/.bunfig.toml 认证凭据或登录状态`};if(response.status===404)return{ok:!1,code:"not-found",status:404,message:`${input.packageName} 尚未在 ${base} 发布 (HTTP 404)`};if(!response.ok)return{ok:!1,code:"http",status:response.status,message:`包注册表返回异常状态 HTTP ${response.status} (${base})`};let body;try{body=await response.json()}catch{return{ok:!1,code:"invalid-response",message:`包注册表返回的内容不是合法 JSON (${base})`}}let version=typeof body==="object"&&body!==null&&!Array.isArray(body)?body.version:void 0;if(typeof version!=="string"||!isValidTargetSpec(version))return{ok:!1,code:"invalid-response",message:`包注册表响应缺少合法 version 字段 (${base})`};return{ok:!0,version,registry:base}}import{win32 as win322}from"node:path";function isWin32AbsolutePath(dir){return/^(?:[A-Za-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/.test(dir)}var CMD_META_OR_SPACE_RE=/[\s&|<>^()%!]/,CMD_FORBIDDEN_RE=/[\r\n\0"]/;function wrapDoubleQuotes(segment){return`"${segment.replace(/(\\+)$/,"$1$1")}"`}function escapeBatchPath(batchPath){if(batchPath===""||CMD_FORBIDDEN_RE.test(batchPath))return null;if(!/[%!]/.test(batchPath))return wrapDoubleQuotes(batchPath);let out="",buf="";for(let ch of batchPath)if(ch==="%"||ch==="!"){if(buf!=="")out+=wrapDoubleQuotes(buf),buf="";out+=`^${ch}`}else buf+=ch;if(buf!=="")out+=wrapDoubleQuotes(buf);return out}function escapeBatchArg(arg){if(CMD_FORBIDDEN_RE.test(arg))return null;if(arg==="")return'""';if(!CMD_META_OR_SPACE_RE.test(arg))return arg;if(!/[%!]/.test(arg))return wrapDoubleQuotes(arg);let out="",buf="";for(let ch of arg)if(ch==="%"||ch==="!"){if(buf!=="")out+=wrapDoubleQuotes(buf),buf="";out+=`^^^${ch}`}else buf+=ch;if(buf!=="")out+=wrapDoubleQuotes(buf);return out}function buildWindowsBatchCommandLine(batchPath,pmArgs){let escapedPath=escapeBatchPath(batchPath);if(escapedPath===null)return null;let escapedArgs=[];for(let arg of pmArgs){let escaped=escapeBatchArg(arg);if(escaped===null)return null;escapedArgs.push(escaped)}return`"${escapedArgs.length===0?escapedPath:`${escapedPath} ${escapedArgs.join(" ")}`}"`}function resolveNodeExeForDir(dir,isFile,findNativeNode){let sibling=win322.join(dir,"node.exe");if(isFile(sibling))return sibling;return findNativeNode()}function resolveWindowsBatchDirectJs(pm,batchPath,args,isFile,findNativeNode){let dir=win322.dirname(batchPath),candidates=[];if(pm==="npm")candidates=[win322.join(dir,"node_modules","npm","bin","npm-cli.js")];else if(pm==="pnpm")candidates=[win322.join(dir,"node_modules","pnpm","bin","pnpm.cjs"),win322.join(dir,"node_modules","corepack","dist","pnpm.js")];else if(pm==="yarn")candidates=[win322.join(dir,"yarn.js"),win322.join(dir,"node_modules","yarn","bin","yarn.js"),win322.join(dir,"node_modules","corepack","dist","yarn.js")];else return null;for(let entryJs of candidates){if(!isFile(entryJs))continue;let nodeExe=resolveNodeExeForDir(dir,isFile,findNativeNode);if(nodeExe!==null)return{command:nodeExe,args:[entryJs,...args]}}return null}function resolveWindowsBatchInvocation(pm,batchPath,pmArgs,env,isFile,findNativeNode){let directJs=resolveWindowsBatchDirectJs(pm,batchPath,pmArgs,isFile,findNativeNode);if(directJs!==null)return directJs;let cmdLine=buildWindowsBatchCommandLine(batchPath,pmArgs);if(cmdLine===null)return null;return{command:env.ComSpec??env.COMSPEC??"cmd.exe",args:["/d","/s","/c",cmdLine],windowsVerbatimArguments:!0}}var WIN32_NATIVE_EXTS=[".exe",".com"],WIN32_BATCH_EXTS=[".cmd",".bat"],PROBE_ENV_OVERLAY={COREPACK_ENABLE_DOWNLOAD_PROMPT:"0"};function defaultIsFile(path){try{return statSync(path).isFile()}catch{return!1}}function defaultReadText2(path){try{return readFileSync2(path,"utf8")}catch{return null}}function parseAbsolutePathDirs(env,platform){let raw=platform==="win32"?env.PATH??env.Path??"":env.PATH??"",sep=platform==="win32"?";":":",out=[];for(let item of raw.split(sep)){let trimmed=item.trim(),cleaned=trimmed.length>1&&trimmed.startsWith('"')&&trimmed.endsWith('"')?trimmed.slice(1,-1):trimmed;if(cleaned==="")continue;if(platform==="win32"?isWin32AbsolutePath(cleaned):cleaned.startsWith("/"))out.push(cleaned)}return out}function resolveExecutableInPath(name,platform=process.platform,env=process.env,isFile=defaultIsFile){let dirs=parseAbsolutePathDirs(env,platform);if(platform!=="win32"){for(let dir of dirs){let candidate=posix2.join(dir,name);if(isFile(candidate))return{path:candidate,isBatch:!1}}return null}for(let dir of dirs){for(let ext of WIN32_NATIVE_EXTS){let candidate=win323.join(dir,`${name}${ext}`);if(isFile(candidate))return{path:candidate,isBatch:!1}}for(let ext of WIN32_BATCH_EXTS){let candidate=win323.join(dir,`${name}${ext}`);if(isFile(candidate))return{path:candidate,isBatch:!0}}}return null}function resolvePmInvocation(pm,pmArgs,platform=process.platform,env=process.env,isFile=defaultIsFile){let found=resolveExecutableInPath(pm,platform,env,isFile);if(found===null)return null;if(platform==="win32"&&found.isBatch){let findNativeNode=()=>{let nodeFound=resolveExecutableInPath("node","win32",env,isFile);return nodeFound!==null&&!nodeFound.isBatch?nodeFound.path:null};return resolveWindowsBatchInvocation(pm,found.path,pmArgs,env,isFile,findNativeNode)}return{command:found.path,args:[...pmArgs]}}function formatUpgradeDisplayCommand(pm,packageName,targetSpec="latest",explicitRegistry){let spec=`${packageName}@${targetSpec}`,reg=explicitRegistry!==void 0?normalizeRegistryUrl(explicitRegistry):void 0;switch(pm){case"bun":return reg===void 0?`bun add -g ${spec}`:`bun add -g ${spec} --registry=${reg}`;case"npm":return reg===void 0?`npm install -g ${spec}`:`npm install -g ${spec} --registry=${reg}`;case"pnpm":return reg===void 0?`pnpm add -g ${spec}`:`pnpm add -g ${spec} --registry=${reg}`;case"yarn":return reg===void 0?`yarn global add ${spec}`:`yarn global add ${spec} --registry ${reg}`;case"volta":return reg===void 0?`volta install ${spec}`:`NPM_CONFIG_REGISTRY=${reg} volta install ${spec}`}}function isYarnBerryVersion(versionText){if(versionText===null)return!1;let m=/^v?(\d+)\./.exec(versionText.trim());if(m===null)return!1;return Number(m[1])>=2}function buildPmUpgradeArgs(pm,spec,reg){if(pm==="volta")return["install",spec];if(pm==="yarn")return reg===void 0?["global","add",spec]:["global","add",spec,"--registry",reg];let base=pm==="npm"?["install","-g",spec]:["add","-g",spec];return reg===void 0?base:[...base,`--registry=${reg}`]}function buildUpgradePlan(input){let targetSpec=input.targetSpec??"latest";if(!isValidPackageName(input.packageName))return{ok:!1,reason:`非法包名: ${input.packageName}`};if(!isValidTargetSpec(targetSpec))return{ok:!1,reason:`非法目标版本标签: ${targetSpec}`};if(input.explicitRegistry!==void 0&&!isValidRegistryUrl(input.explicitRegistry))return{ok:!1,reason:`非法 registry 地址: ${input.explicitRegistry}`};let platform=input.platform??process.platform,env=input.env??process.env,isFile=input.isFile??defaultIsFile,reg=input.explicitRegistry!==void 0?normalizeRegistryUrl(input.explicitRegistry):void 0,displayCommand=formatUpgradeDisplayCommand(input.pm,input.packageName,targetSpec,reg);if(input.pm==="yarn"&&isYarnBerryVersion(input.yarnVersion??null))return{ok:!1,reason:`当前环境的 Yarn (${input.yarnVersion?.trim()}) 为 v2+ (Berry), 官方已移除 yarn global add 命令, `+"请改用 --pm bun / --pm npm / --pm pnpm 执行全局更新"};let spec=`${input.packageName}@${targetSpec}`,pmArgs=buildPmUpgradeArgs(input.pm,spec,reg),invocation=resolvePmInvocation(input.pm,pmArgs,platform,env,isFile);if(invocation===null)return{ok:!1,reason:`当前 PATH 中未找到 ${input.pm} 可执行文件, 无法自动执行更新`,fallbackCommand:displayCommand};let envOverlay=reg===void 0?void 0:{npm_config_registry:reg,NPM_CONFIG_REGISTRY:reg};return{ok:!0,plan:{command:invocation.command,args:invocation.args,displayCommand,envOverlay,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}}}function buildIsolatedEnv(baseEnv,overlay){let next={...baseEnv};if(delete next.npm_execpath,delete next.npm_lifecycle_event,delete next.npm_lifecycle_script,delete next.npm_package_json,delete next.INIT_CWD,overlay!==void 0)Object.assign(next,overlay);return next}function withIsolatedCwd(fn){let dir=mkdtempSync(join(tmpdir(),"cli-update-"));try{return fn(dir)}finally{try{rmSync(dir,{recursive:!0,force:!0,maxRetries:3,retryDelay:50})}catch{}}}function runIsolatedProbe(cwd,invocation,env,spawnFn){let res=spawnFn(invocation.command,invocation.args,{cwd,env:buildIsolatedEnv(env,PROBE_ENV_OVERLAY),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3000,...invocation.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}});if(res.status!==0||typeof res.stdout!=="string")return null;let text=res.stdout.trim();return text===""?null:text}function probeYarnVersion(platform=process.platform,env=process.env,spawnFn=spawnSync){let invocation=resolvePmInvocation("yarn",["--version"],platform,env);if(invocation===null)return null;return withIsolatedCwd((cwd)=>runIsolatedProbe(cwd,invocation,env,spawnFn))}var joinForPlatform=(p,...parts)=>p==="win32"?win323.join(...parts):posix2.join(...parts);function expandHomeDir(raw,home,p){if(raw==="~")return home;if(raw.startsWith("~/")||raw.startsWith("~\\"))return joinForPlatform(p,home,raw.slice(2));return raw}function resolveBunGlobalDirFromConfig(home,platform,readText,pathExists){let bunfig=readText(joinForPlatform(platform,home,".bunfig.toml"));if(bunfig===null)return null;let rawDir=parseGlobalDirFromBunfig(bunfig);if(rawDir===null)return null;let expanded=expandHomeDir(rawDir,home,platform);return pathExists(expanded)?safeRealpath(expanded):null}function probeGlobalRoots(platform=process.platform,env=process.env,spawnFn=spawnSync,options){let roots={},home=options?.homeDir??homedir2(),readText=options?.readText??defaultReadText2,pathExists=options?.pathExists??existsSync2,isFile=options?.isFile??defaultIsFile,bunDir=resolveBunGlobalDirFromConfig(home,platform,readText,pathExists);if(bunDir!==null)roots.bun=bunDir;return withIsolatedCwd((cwd)=>{let probeDir=(pm,args)=>{let invocation=resolvePmInvocation(pm,args,platform,env,isFile);if(invocation===null)return null;let stdout=runIsolatedProbe(cwd,invocation,env,spawnFn);if(stdout===null)return null;let line=stdout.split(/\r?\n/)[0]?.trim()??"";if(line===""||!pathExists(line))return null;return safeRealpath(line)},pnpmRoot=probeDir("pnpm",["root","-g"]);if(pnpmRoot!==null)roots.pnpm=pnpmRoot;let npmRoot=probeDir("npm",["root","-g"]);if(npmRoot!==null)roots.npm=npmRoot;let yarnVerInv=resolvePmInvocation("yarn",["--version"],platform,env,isFile),yarnVer=yarnVerInv!==null?runIsolatedProbe(cwd,yarnVerInv,env,spawnFn):null;if(yarnVer!==null&&!isYarnBerryVersion(yarnVer)){let yarnDir=probeDir("yarn",["global","dir"]);if(yarnDir!==null)roots.yarn=yarnDir}}),roots}function executeUpgradePlan(plan,env=process.env,spawnFn=spawnSync){return withIsolatedCwd((cwd)=>{let res=spawnFn(plan.command,plan.args,{cwd,env:buildIsolatedEnv(env,plan.envOverlay),stdio:"inherit",...plan.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}});return{status:res.status,signal:res.signal,error:res.error}})}import{existsSync as existsSync3,readFileSync as readFileSync3}from"node:fs";function sanitize(raw){return raw.replace(/\p{Cc}/gu," ").replace(/\s+/g," ").trim()}function formatVersionLabel(spec){return/^\d/.test(spec)?`v${spec}`:spec}function defaultReadText3(path){try{return readFileSync3(path,"utf8")}catch{return null}}function ephemeralHintCommand(runner,packageName){switch(runner){case"bunx":return`bunx ${packageName}@latest`;case"npx":return`npx ${packageName}@latest`;case"pnpm-dlx":return`pnpm dlx ${packageName}@latest`;case"yarn-dlx":return`yarn dlx ${packageName}@latest`;case"deno":return`deno run -A npm:${packageName}@latest`}}function localProjectHintCommand(pm,packageName){switch(pm){case"bun":return`bun add -D ${packageName}@latest`;case"pnpm":return`pnpm add -D ${packageName}@latest`;case"yarn":return`yarn add -D ${packageName}@latest`;case"npm":return`npm install -D ${packageName}@latest`}}function describeOrigin(origin){switch(origin.kind){case"global":return`${origin.pm} 全局安装 (${origin.reason})`;case"ephemeral":return`${origin.runner} 临时运行 (${origin.reason})`;case"source":return`本地源码开发态 (${origin.packageRoot})`;case"local-project":return`项目本地依赖 (${origin.projectDir})`;case"unknown":return`未知安装位置 (${origin.packageRoot})`}}function warnCrossPmOverride(origin,targetPm,io){if(origin.kind==="global"&&origin.pm!==targetPm){io.out(`注意: 当前命令实际由 ${origin.pm} 全局安装, 改用 ${targetPm} 安装会在磁盘产生双份副本, PATH 靠前的旧副本可能遮蔽新版本!`);return}if(origin.kind==="source"){io.out(`注意: 当前运行在本地源码工作树 (${origin.packageRoot}), 通过 ${targetPm} 全局安装会产生独立全局副本, 请核对 PATH 优先级避免版本阴影!`);return}if(origin.kind==="local-project")io.out(`注意: 当前运行在项目本地依赖 (${origin.projectDir}), 通过 ${targetPm} 全局安装不会更新项目本地依赖, 且可能被本地副本遮蔽!`)}function resolveOrigin(meta,deps){let env=deps.env??process.env,pathExists=deps.pathExists??existsSync3,platform=deps.platform??process.platform,rawPaths=[meta.rawPackageRoot],entryArg=deps.argvEntry??process.argv[1];if(typeof entryArg==="string"&&entryArg!=="")rawPaths.push(entryArg);let firstPass=detectInstallOriginFromPath({packageRoot:meta.packageRoot,rawPaths,env,pathExists});if(!(firstPass.kind==="unknown"||firstPass.kind==="local-project"||firstPass.kind==="global"&&firstPass.reason===LIB_NODE_MODULES_HEURISTIC_REASON))return firstPass;if(meta.packageRoot.replaceAll("\\","/").toLowerCase().includes("/node_modules/")){let globalRoots=deps.probeRoots!==void 0?deps.probeRoots():probeGlobalRoots(platform,env,deps.spawnFn,{homeDir:deps.homeDir,readText:deps.readText,pathExists,isFile:deps.isFile});if(Object.keys(globalRoots).length>0)return detectInstallOriginFromPath({packageRoot:meta.packageRoot,rawPaths,env,pathExists,globalRoots})}return firstPass}function verifyPostUpgrade(input){let pkgText=(input.readText??defaultReadText3)(joinForPath(input.meta.packageRoot,"package.json")),unchangedAtOldRoot=!1;if(pkgText!==null)try{let parsed=JSON.parse(pkgText),afterVersion=typeof parsed.version==="string"?parsed.version:void 0;if(input.targetSpec!=="latest"&&compareSemver(input.meta.version,input.targetSpec)===-1&&afterVersion!==void 0&&afterVersion===input.meta.version)unchangedAtOldRoot=!0,input.io.out(`提示: 原安装目录 (${input.meta.packageRoot}) 的版本仍为 ${formatVersionLabel(afterVersion)}, 新版本可能安装到了其他位置, 请运行 ${input.binName} --version 核查。`)}catch{}let resolvedBin=resolveExecutableInPath(input.binName,input.platform,input.env,input.isFile);if(resolvedBin===null)return;let resolvedReal=safeRealpath(resolvedBin.path),oldGlobalPm=input.origin.kind==="global"&&input.origin.pm!==input.targetPm?input.origin.pm:null,isCrossGlobal=oldGlobalPm!==null,pointsToOldRoot=isWithinDir(resolvedReal,input.meta.packageRoot),pointsToOldPm=!1;if(oldGlobalPm!==null){let binOrigin=detectInstallOriginFromPath({packageRoot:resolvedReal,rawPaths:[resolvedBin.path],env:input.env,pathExists:()=>!1});pointsToOldPm=binOrigin.kind==="global"&&binOrigin.pm===oldGlobalPm}if(pointsToOldPm||pointsToOldRoot&&(isCrossGlobal||input.origin.kind==="source"||unchangedAtOldRoot))input.io.out(`提示: 当前 PATH 中的 ${input.binName} 仍指向旧路径 (${resolvedBin.path}), 可能遮蔽 ${input.targetPm} 新安装的版本, 请检查 PATH 优先级。`)}async function handleNonGlobalOrigin(ctx){let{meta,origin,hasExplicitRegistry,io,fetchVersion,registry}=ctx;if(io.out(`当前版本: ${meta.name}@${meta.version}`),io.out(`安装方式: ${describeOrigin(origin)}`),meta.isPrivate!==!0||hasExplicitRegistry){let remote=await fetchVersion(registry);if(remote.ok){let cmp=compareSemver(meta.version,remote.version),status;if(cmp===-1)status=`发现新版本 ${remote.version} (源: ${remote.registry})`;else if(cmp===null)status=`远端版本为 ${remote.version} (无法按 SemVer 比较, 源: ${remote.registry})`;else status=`远端最新版为 ${remote.version} (源: ${remote.registry})`;io.out(`版本检查: ${status}`)}else if(remote.code!=="not-found")io.out(`版本检查: 暂未获取远端版本 (${sanitize(remote.message)})`)}if(origin.kind==="source")return io.out("更新方式: 当前运行在本地源码工作树, 不通过包管理器覆盖。"),io.out(" 请在仓库根目录运行: git pull && bun install && bun run build"),io.out(" 若要通过包管理器安装全局发布版, 可显式指定 --pm <bun|npm|pnpm|yarn|volta>"),0;if(origin.kind==="ephemeral")return io.out(`更新方式: 当前经 ${origin.runner} 临时运行, 无需原地升级。`),io.out(` 下次获取最新版请运行: ${ephemeralHintCommand(origin.runner,meta.name)}`),io.out(" 若希望改为全局安装, 可运行带 --pm <bun|npm|pnpm|yarn|volta> 的 update 或直接全局安装"),0;return io.out(`更新方式: 当前作为项目本地依赖运行 (${origin.projectDir}), 为避免静默改写项目锁文件, 不自动覆盖。`),io.out(` 请在项目目录执行: ${localProjectHintCommand(origin.suggestedPm,meta.name)}`),0}function readPackageMeta(entryMetaUrl){let entryPath=fileURLToPath(entryMetaUrl),rawPackageRoot=dirname(dirname(entryPath)),packageRoot=safeRealpath(rawPackageRoot),pkgPath=join2(packageRoot,"package.json"),parsed=JSON.parse(readFileSync4(pkgPath,"utf8"));if(typeof parsed.name!=="string"||parsed.name==="")throw Error(`无法从 ${pkgPath} 读取合法包名`);let version=typeof parsed.version==="string"&&parsed.version!==""?parsed.version:"0.0.0";return{name:parsed.name,version,isPrivate:parsed.private===!0,rawPackageRoot,packageRoot}}function performUpgrade(ctx){let{binName,meta,origin,targetPm,targetSpec,opts,io,deps}=ctx,platform=deps.platform??process.platform,env=deps.env??process.env,yarnVersion=null;if(targetPm==="yarn")yarnVersion=deps.probeYarn!==void 0?deps.probeYarn():probeYarnVersion(platform,env,deps.spawnFn);let built=buildUpgradePlan({pm:targetPm,packageName:meta.name,targetSpec,explicitRegistry:opts.registry,platform,env,isFile:deps.isFile,yarnVersion});if(!built.ok){if(io.err(`无法自动更新: ${built.reason}`),built.fallbackCommand!==void 0)io.err(` 手动更新命令: ${built.fallbackCommand}`);return 1}io.out(`即将执行: ${built.plan.displayCommand}`);let result=(deps.execPlan??executeUpgradePlan)(built.plan,env,deps.spawnFn);if(result.error!==void 0)return io.err(`更新命令启动失败: ${sanitize(result.error.message)}`),io.err(` 手动更新命令: ${built.plan.displayCommand}`),1;if(result.signal!==void 0&&result.signal!==null)return io.err(`更新进程被信号中断 (${result.signal})`),io.err(` 手动更新命令: ${built.plan.displayCommand}`),1;if(result.status!==0){if(io.err(`更新失败 (${targetPm} 退出码 ${String(result.status??1)})`),platform==="win32")io.err(` Windows 提示: 当前正在运行的 ${binName} 自身可执行/shim 文件可能被系统锁定 (EBUSY / EPERM), 请退出当前命令并关闭其他占用终端后直接执行下方命令:`);if(targetPm==="pnpm")io.err(" pnpm 提示: 若提示未配置全局 bin 目录, 请检查 PNPM_HOME 环境变量或先运行 pnpm setup。");return io.err(` 手动更新命令: ${built.plan.displayCommand}`),1}return io.out(`已通过 ${targetPm} 更新 ${meta.name} 至 ${formatVersionLabel(targetSpec)} ✓`),verifyPostUpgrade({binName,meta,origin,targetPm,targetSpec,platform,env,readText:deps.readText,isFile:deps.isFile,io}),0}function handleFetchFailure(ctx){let{binName,meta,origin,targetPm,registry,remote,opts,io,deps}=ctx;if(opts.force&&!opts.check&&targetPm!==void 0)return io.err(`警示: 远端版本查询失败 (${sanitize(remote.message)})`),io.out(`强制重装模式 (--force): 跳过远端版本校验, 将直接通过 ${targetPm} 安装 ${meta.name}@latest`),performUpgrade({binName,meta,origin,targetPm,targetSpec:"latest",opts,io,deps});if(remote.code==="not-found")return io.err(`${meta.name} 尚未在 ${registry} 发布 (HTTP 404), 无法在线更新`+(meta.isPrivate?" (当前包标记为 private)":"")),io.err(" 若已发布到私有源, 请加 --registry <url> 后重试"),1;if(remote.code==="auth")io.err(`检查最新版本失败: ${sanitize(remote.message)}`),io.err(" 请先完成源登录或在 ~/.npmrc / ~/.bunfig.toml 配置同源访问 token, 或加 --force 直接委托包管理器安装");else io.err(`检查最新版本失败: ${sanitize(remote.message)}`);if(targetPm!==void 0){let cmd=formatUpgradeDisplayCommand(targetPm,meta.name,"latest",opts.registry);io.err(` 可稍后重试或手动执行: ${cmd}`)}return 1}async function runSelfUpdate(options){let io=options.io??{out:(line)=>process.stdout.write(`${line}
|
|
3
|
+
`),err:(line)=>process.stderr.write(`${line}
|
|
4
|
+
`)},deps=options.deps??{},parsed=parseUpdateArgs(options.argv);if(!parsed.ok)return io.err(`参数错误: ${parsed.message}`),1;let opts=parsed.options,meta;try{if(options.meta!==void 0)meta=options.meta;else if(options.entryMetaUrl!==void 0)meta=readPackageMeta(options.entryMetaUrl);else throw Error("缺少 entryMetaUrl 或 meta, 无法定位当前包信息")}catch(error){let msg=error instanceof Error?error.message:String(error);return io.err(`读取当前包信息失败: ${sanitize(msg)}`),1}if(opts.help){for(let line of formatUpdateHelp(options.binName,meta.name).split(`
|
|
5
|
+
`))io.out(line);return 0}let origin=resolveOrigin(meta,deps),detectedPm=origin.kind==="global"?origin.pm:void 0,targetPm=opts.pm??detectedPm,registry=resolveRegistry({packageName:meta.name,flagRegistry:opts.registry,pm:targetPm,env:deps.env,homeDir:deps.homeDir,readText:deps.readText}),fetchVersion=(reg)=>{if(deps.fetchLatest!==void 0)return deps.fetchLatest(meta.name,reg);let authToken=resolveRegistryAuthToken({packageName:meta.name,registry:reg,pm:targetPm,env:deps.env,homeDir:deps.homeDir,readText:deps.readText});return fetchLatestVersion({packageName:meta.name,registry:reg,authToken})};if(opts.pm===void 0&&(origin.kind==="source"||origin.kind==="ephemeral"||origin.kind==="local-project"))return await handleNonGlobalOrigin({meta,origin,hasExplicitRegistry:opts.registry!==void 0,io,fetchVersion,registry});if(io.out(`当前版本: ${meta.name}@${meta.version}`),io.out(`安装方式: ${describeOrigin(origin)}`),opts.pm!==void 0&&opts.pm!==detectedPm)io.out(`目标安装器: ${opts.pm} (经 --pm 手动指定)`),warnCrossPmOverride(origin,opts.pm,io);let remote=await fetchVersion(registry);if(!remote.ok)return handleFetchFailure({binName:options.binName,meta,origin,targetPm,registry,remote,opts,io,deps});let cmp=compareSemver(meta.version,remote.version);if(cmp===null&&!opts.force)return io.out(`版本比较: 当前版本 (${meta.version}) 与远端版本 (${remote.version}, 源: ${remote.registry}) 无法按标准 SemVer 比较, 未自动覆盖。`),io.out(` 若确认需要安装远端版本, 请加 --force 重试 (例如: ${options.binName} update --force)`),0;let hasUpdate=cmp===-1;if(!hasUpdate&&!opts.force)return io.out(`已是最新版本: v${meta.version} (远端最新 v${remote.version}, 源: ${remote.registry}) ✓`),0;if(hasUpdate)io.out(`发现新版本: v${meta.version} → v${remote.version} (源: ${remote.registry})`);else io.out(`强制重装模式 (--force): 将重新安装 ${formatVersionLabel(remote.version)} (源: ${remote.registry})`);if(opts.check){if(targetPm!==void 0){let cmd=formatUpgradeDisplayCommand(targetPm,meta.name,remote.version,opts.registry);io.out(`运行 ${options.binName} update 即可升级 (将执行: ${cmd})`)}else io.out(`未能自动识别安装器, 升级请运行: ${options.binName} update --pm <bun|npm|pnpm|yarn|volta>`);return 0}if(targetPm===void 0)return io.err("未能自动确认安装本命令的包管理器, 为避免在 PATH 中装出重复版本已停止自动执行"),io.err(` 请使用 --pm 显式指定你的包管理器后重试, 例如: ${options.binName} update --pm bun`),1;return performUpgrade({binName:options.binName,meta,origin,targetPm,targetSpec:remote.version,opts,io,deps})}import{readFile}from"node:fs/promises";import{homedir as homedir3}from"node:os";import{posix as posix3,win32 as win324}from"node:path";var SWEEP_ERROR_CODES=new Set(["CONFIG_READ_FAILED","CONFIG_CORRUPT_JSON","CONFIG_CORRUPT_SHAPE","CONFIG_ABSENT","INVALID_ARGUMENT","CANCELLED"]);class SweepError extends Error{name="SweepError";code;details;constructor(code,message,details,options){super(message,options);this.code=code,this.details=details}}function isSweepError(value){if(typeof value!=="object"||value===null)return!1;let candidate=value;return candidate.name==="SweepError"&&typeof candidate.message==="string"&&typeof candidate.code==="string"&&SWEEP_ERROR_CODES.has(candidate.code)}var DEFAULT_EXCLUDE=Object.freeze([".bun",".npm",".pnpm-store",".yarn",".nvm","nvm",".fnm",".volta",".asdf",".n",".vscode",".vscode-insiders",".vscode-server",".cursor",".antigravity","Library",".local",".config",".cache",".claude"]);function platformDefaultPath(platform,env,home){if(platform==="win32"){let roaming=env.APPDATA||win324.join(env.USERPROFILE||home,"AppData","Roaming");return win324.join(roaming,"sweep-node-modules","config.json")}return posix3.join(home,".config","sweep-node-modules","config.json")}function resolveConfigPath(options){if(options.flag)return{path:options.flag,source:"flag"};let env=options.env??process.env;if(env.SWEEP_NM_CONFIG)return{path:env.SWEEP_NM_CONFIG,source:"env"};let platform=options.platform??process.platform,home=options.homedir??homedir3();return{path:platformDefaultPath(platform,env,home),source:"platform-default"}}function describeActual(value){if(value===void 0)return"缺失";if(value===null)return"null";if(Array.isArray(value))return"array";return typeof value}function fieldError(container,field,optional){let value=container[field];if(value===void 0)return optional?null:{field,message:`${field} 应为字符串数组 (实际: 缺失)`};if(!Array.isArray(value))return{field,message:`${field} 应为字符串数组 (实际: ${describeActual(value)})`};let badIndex=value.findIndex((item)=>typeof item!=="string");if(badIndex!==-1)return{field,message:`${field} 第 ${badIndex+1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`};if(field==="roots"){let emptyIndex=value.findIndex((item)=>item==="");if(emptyIndex!==-1)return{field,message:`${field} 第 ${emptyIndex+1} 项不能为空字符串`}}return null}function shapeError(value){if(typeof value!=="object"||value===null||Array.isArray(value))return{field:"顶层",message:`顶层应为对象 (实际: ${describeActual(value)})`};let candidate=value,rootsError=fieldError(candidate,"roots",!1);if(rootsError!==null)return rootsError;let excludeError=fieldError(candidate,"exclude",!0);if(excludeError!==null)return excludeError;return fieldError(candidate,"include",!0)}async function loadConfig(path){let text;try{text=await readFile(path,"utf8")}catch(error){if(error.code==="ENOENT")return{state:"absent"};throw new SweepError("CONFIG_READ_FAILED",`配置读取失败 (${path}): ${error.message}`,{path,errno:error.code},{cause:error})}let data;try{data=JSON.parse(text)}catch(error){throw new SweepError("CONFIG_CORRUPT_JSON",`配置损坏 (${path}): JSON 解析失败: ${error.message}`,{path},{cause:error})}let problem=shapeError(data);if(problem!==null)throw new SweepError("CONFIG_CORRUPT_SHAPE",`配置损坏 (${path}): ${problem.message}`,{path,field:problem.field});let raw=data;return{state:"ok",config:{roots:raw.roots,exclude:raw.exclude??[...DEFAULT_EXCLUDE],include:raw.include??[]}}}async function loadResolvedConfig(resolved){let result=await loadConfig(resolved.path);if(result.state==="absent"&&resolved.source!=="platform-default")throw new SweepError("CONFIG_ABSENT",`配置不存在 (${resolved.path}), 请检查路径`,{path:resolved.path,source:resolved.source});return result}function mergeNames(configNames,cliNames){return[...new Set([...configNames,...cliNames])].filter((name)=>name!=="node_modules"&&name!==".git")}function formatBytes(bytes){if(bytes<1024)return`${Math.round(bytes)} B`;let units=["KB","MB","GB","TB"],value=bytes,index=-1;do value/=1024,index+=1;while(value>=1024&&index<units.length-1);return`${Math.round(value*10)/10} ${units[index]}`}var sanitizeLine=(text)=>text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g,"").replace(/\s+/g," ").trim(),sanitizeOutputLine=(text)=>`${/^[ \t]*/.exec(text)?.[0]??""}${sanitizeLine(text)}`;import{lstat,realpath,stat}from"node:fs/promises";import{homedir as homedir4}from"node:os";import{posix as posix4,win32 as win325}from"node:path";var POSIX_STYLE=Object.freeze({name:"posix",ops:posix4,caseInsensitive:!1}),WIN32_STYLE=Object.freeze({name:"win32",ops:win325,caseInsensitive:!0});function nativeStyle(){return process.platform==="win32"?WIN32_STYLE:POSIX_STYLE}function fold(p,style){return style.caseInsensitive?p.toLowerCase():p}function dedupeKey(realPath,style){return fold(realPath,style)}function hasNodeModulesLeaf(target,style){return fold(style.ops.basename(target),style)==="node_modules"}function insideAnyRoot(realPath,roots,style){if(realPath==="")return!1;return roots.some((root)=>{if(root==="")return!1;let rel=style.ops.relative(fold(root,style),fold(realPath,style));if(rel===""||style.ops.isAbsolute(rel))return!1;return rel!==".."&&!rel.startsWith(`..${style.ops.sep}`)})}function isFilesystemRootBody(realPath,style){if(realPath==="")return!1;let normalized=style.ops.normalize(realPath),root=style.ops.parse(normalized).root;return root!==""&&fold(root,style)===fold(normalized,style)}function isHomeBody(realPath,home,style){if(home===null||home===""||realPath==="")return!1;return style.ops.relative(fold(home,style),fold(realPath,style))===""}function firstSymlinkOnAnchor(links){for(let link of links)if(link.symlink)return link.path;return null}function anchorChainPaths(root,style){let absolute=style.ops.isAbsolute(root)?style.ops.normalize(root):style.ops.resolve(root),prefix=style.ops.parse(absolute).root,tail=absolute.slice(prefix.length),parts=style.name==="win32"?tail.split(/[\\/]+/):tail.split(style.ops.sep),chain=[],cursor=prefix;for(let part of parts){if(part==="")continue;cursor=style.ops.join(cursor,part),chain.push(cursor)}return chain}async function tryRealpath(p){try{return await realpath(p)}catch{return null}}async function collectAnchorLinks(root,style){let links=[];for(let path of anchorChainPaths(root,style))try{links.push({path,symlink:(await lstat(path)).isSymbolicLink()})}catch{}return links}async function firstSymlinkOnTarget(target){return firstSymlinkOnAnchor(await collectAnchorLinks(target,nativeStyle()))}async function firstSymlinkOnRoot(root){return firstSymlinkOnTarget(root)}async function validateTargets(targets,options){if(options.signal?.aborted)throw new SweepError("CANCELLED","安全闸校验在逐目标检查点被取消",{phase:"validate"});let style=options.style??nativeStyle(),homeOption=options.home===void 0?homedir4():options.home,anchors=[];for(let root of options.roots)anchors.push({configured:root,real:await tryRealpath(root),link:firstSymlinkOnAnchor(await collectAnchorLinks(root,style))});let brokenAnchors=anchors.filter((anchor)=>anchor.real!==null&&anchor.link!==null),roots=[];for(let anchor of anchors)if(anchor.real!==null)roots.push(anchor.real);let home=homeOption===null?null:await tryRealpath(homeOption)??homeOption,accepted=[],rejected=[],mappings=[],seen=new Set;for(let target of targets){if(options.signal?.aborted)throw new SweepError("CANCELLED","安全闸校验在逐目标检查点被取消",{phase:"validate"});if(!hasNodeModulesLeaf(target,style)){rejected.push({target,code:"GUARD_LEAF_NOT_NODE_MODULES",message:"路径末段不是 node_modules"});continue}let real=null,realpathErrno;try{real=await realpath(target)}catch(error){realpathErrno=error.code}if(real===null){let code="GUARD_REALPATH_FAILED";if(realpathErrno==="ENOENT")code="GUARD_TARGET_MISSING";else if(realpathErrno==="EACCES"||realpathErrno==="EPERM")code="GUARD_TARGET_UNREADABLE";rejected.push({target,code,message:"realpath 失败 (目标不存在或不可读)",details:{errno:realpathErrno}});continue}let brokenAnchor=brokenAnchors.find((anchor)=>insideAnyRoot(real,[anchor.real],style));if(brokenAnchor!==void 0){rejected.push({target,code:"GUARD_ROOT_ANCHOR_SYMLINK",message:`根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`,details:{root:brokenAnchor.configured,symlink:brokenAnchor.link}});continue}if(isFilesystemRootBody(real,style)){rejected.push({target,code:"GUARD_FILESYSTEM_ROOT_BODY",message:"目标是文件系统根本体"});continue}if(isHomeBody(real,home,style)){rejected.push({target,code:"GUARD_HOME_BODY",message:"目标是 home 本体"});continue}if(!hasNodeModulesLeaf(real,style)){rejected.push({target,code:"GUARD_REAL_LEAF_NOT_NODE_MODULES",message:"realpath 后的末段不是 node_modules"});continue}if(!insideAnyRoot(real,roots,style)){rejected.push({target,code:"GUARD_OUTSIDE_ROOTS",message:"realpath 后不在任何 root 之下"});continue}let key=dedupeKey(real,style);if(seen.has(key)){rejected.push({target,code:"GUARD_DUPLICATE_TARGET",message:"重复目标 (realpath 去重)"});continue}seen.add(key),accepted.push(real),mappings.push({original:target,real})}return{accepted,rejected,mappings}}var fsDeviceProbe=async(path,follow)=>{try{return(await(follow?stat:lstat)(path)).dev}catch{return null}};function owningRoot(target,roots,style){let best=null;for(let root of roots){if(!insideAnyRoot(target,[root],style))continue;if(best===null||insideAnyRoot(root,[best],style))best=root}return best}async function findCrossDeviceTargets(targets,options){let style=options.style??nativeStyle(),probe=options.probe??fsDeviceProbe,devices=new Map,found=new Map;for(let target of targets){let root=owningRoot(target,options.roots,style);if(root===null)continue;let rootDev=devices.get(root);if(rootDev===void 0)rootDev=await probe(root,!0),devices.set(root,rootDev);if(rootDev===null)continue;let targetDev=await probe(target,!1);if(targetDev===null||targetDev===rootDev)continue;let parentDev=await probe(style.ops.dirname(target),!0);found.set(target,parentDev!==null&&parentDev!==targetDev?"target-itself":"on-path")}return[...found.entries()].map(([target,kind])=>({target,kind}))}function crossDeviceIndex(entries){return new Map(entries.map((entry)=>[entry.target,entry.kind]))}import{homedir as homedir5}from"node:os";var fold2=(text,style)=>style.caseInsensitive?text.toLowerCase():text,INSTALL_TREE_SEGMENTS=new Set([...DEFAULT_EXCLUDE,"extensions","_npx"].map((name)=>name.toLowerCase()));function classifyTarget(target,options={}){let style=options.style??nativeStyle(),homeOption=options.home===void 0?homedir5():options.home,normalizedTarget=style.ops.normalize(target),ancestors=(style.name==="win32"?normalizedTarget.split(/[\\/]+/):normalizedTarget.split(style.ops.sep)).filter((part)=>part!=="").slice(0,-1);for(let segment of ancestors)if(INSTALL_TREE_SEGMENTS.has(segment.toLowerCase()))return{kind:"suspect-install-tree",reason:`位于 ${segment} 安装树目录`};let parent=ancestors[ancestors.length-1];if(parent!==void 0&&parent.toLowerCase()==="lib")return{kind:"suspect-install-tree",reason:"父目录为 lib, 形如版本管理器的 node 安装树"};if(homeOption!==null&&homeOption!==""){let relative=style.ops.relative(fold2(homeOption,style),fold2(normalizedTarget,style)),[first]=style.name==="win32"?relative.split(/[\\/]+/):relative.split(style.ops.sep);if(first!==void 0&&first!==".."&&first!=="."&&first.startsWith(".")&&!style.ops.isAbsolute(relative))return{kind:"suspect-install-tree",reason:`位于 ${first} (家目录下的隐藏目录)`}}return{kind:"project"}}var SUSPECT_HINT="已跳过 (加 --force 一并清理)",CROSS_DEVICE_NOTES={"on-path":"跨设备: 根与目标之间有挂载点","target-itself":"跨设备: 目标本体即挂载点"},CROSS_DEVICE_HINTS={"on-path":"已跳过 (把该挂载点声明为独立根即可清理)","target-itself":"已跳过 (挂载点无法删除, 需先卸载该卷)"},CROSS_DEVICE_TRAILER_ACTIONS={"on-path":"把根与目标之间的挂载点声明为独立根即可清理","target-itself":"目标本体即挂载点, 需先卸载该卷"};function crossDeviceNote(kind){return CROSS_DEVICE_NOTES[kind]}function skipReasonOf(entry,crossDevice,policy){let deviceKind=crossDevice.get(entry.target);if(deviceKind!==void 0)return deviceKind==="on-path"?"cross-device:on-path":"cross-device:target-itself";if(entry.bytes===void 0)return"unmeasured";if(entry.suspect&&!policy.releaseSuspects)return"suspect-install-tree";return null}function skipsBatch(entry,crossDevice,policy){return skipReasonOf(entry,crossDevice,policy)!==null}function deletionBatch(entries,crossDevice,policy){return entries.filter((entry)=>!skipsBatch(entry,crossDevice,policy)).map((entry)=>entry.target)}function noteOf(entry,reason){if(reason==="suspect-install-tree")return SUSPECT_HINT;if(reason==="unmeasured")return`体积统计失败: ${entry.unmeasuredReason??"原因未知"}`;return CROSS_DEVICE_HINTS[reason==="cross-device:on-path"?"on-path":"target-itself"]}function collectSkips(entries,crossDevice,policy){let suspectSkipped=policy.releaseSuspects?[]:entries.filter((entry)=>entry.suspect),deviceSkipped=entries.filter((entry)=>crossDevice.has(entry.target)),trailer=[...suspectSkipped.length>0?[`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`]:[],...["on-path","target-itself"].flatMap((kind)=>{let count=deviceSkipped.filter((entry)=>crossDevice.get(entry.target)===kind).length;return count===0?[]:[`跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`]})],hints=new Map;for(let entry of suspectSkipped)if(entry.bytes!==void 0)hints.set(entry.target,SUSPECT_HINT);for(let entry of deviceSkipped){let kind=crossDevice.get(entry.target);if(entry.bytes!==void 0&&kind!==void 0)hints.set(entry.target,CROSS_DEVICE_HINTS[kind])}let book=[];for(let entry of entries){let reason=skipReasonOf(entry,crossDevice,policy);if(reason===null)continue;book.push({target:entry.target,reason,note:noteOf(entry,reason)})}return{entries:book,trailer,hints}}var SUCCESS_KINDS=new Set(["removed","missing","stale"]);function isSuccessOutcome(outcome){return SUCCESS_KINDS.has(outcome.kind)}function summarizeReport(report){let counts={removed:0,missing:0,stale:0,failed:0,rejected:0,"not-attempted":0,"not-expected":0,skipped:0};for(let entry of report.entries)counts[entry.outcome.kind]+=1;return{counts,succeeded:counts.removed+counts.missing+counts.stale,unprocessed:counts.skipped+counts.rejected+counts["not-attempted"]+counts["not-expected"],failed:counts.failed,aborted:report.removal?.aborted!==void 0}}import{homedir as homedir6}from"node:os";import{lstat as lstat3,realpath as realpath2,rm}from"node:fs/promises";import{lstat as lstat2}from"node:fs/promises";var ERROR_HINTS={EACCES:"权限不足, 拒绝删除",EPERM:"操作不被允许",EBUSY:"目标被占用",ENOTEMPTY:"目录非空",EROFS:"目标位于只读文件系统"};function describeCode(error){let fsError=error,code=fsError?.code;if(typeof code!=="string"||code==="")return`未知错误: ${fsError?.message??String(error)}`;return`${code}: ${ERROR_HINTS[code]??"删除未成功"}`}function describeReviewError(target,path,error){return`安全复核未完成 (${describeCode(error)}) (目标: ${target}; 组件: ${path}; 未执行删除)`}function describeVanishedReview(target,path){return`安全复核未完成 (ENOENT: 路径组件消失) (目标: ${target}; 组件: ${path}; 请复查目标是否仍存在; 未执行删除; 若目标确已不存在, 可忽略此条)`}function componentChain(root,target,style){let fold=(p)=>style.caseInsensitive?p.toLowerCase():p,rel=style.ops.relative(fold(root),fold(target)),chain=[root],cursor=root;for(let part of rel.split(style.ops.sep).slice(0,-1))cursor=style.ops.join(cursor,part),chain.push(cursor);return chain}function targetShapeViolation(target,style){if(target.endsWith("/")||target.endsWith("\\"))return`安全复核失败 (目标路径不得含尾分隔符): ${target}`;if((style.name==="win32"?target.split(/[\\/]+/):target.split("/")).some((segment)=>segment==="."||segment===".."))return`安全复核失败 (目标路径不得含相对段 . 或 ..): ${target}`;if(!hasNodeModulesLeaf(target,style))return`安全复核失败 (路径末段不是 node_modules): ${target}`;return null}function rootAncestorChain(root,style){let chain=[],seen=new Set,append=(raw)=>{for(let step of anchorChainPaths(raw,style)){let key=dedupeKey(step,style);if(seen.has(key))continue;seen.add(key),chain.push(step)}};return append(root.configured),append(root.real),chain}async function reviewComponents(chain){for(let path of chain)try{if(!(await lstat2(path)).isDirectory())return{kind:"unsafe",path}}catch(error){if(error?.code==="ENOENT")return{kind:"vanished",path};return{kind:"unverified",path,error}}return null}function toReviewFailure(target,finding){if(finding.kind==="vanished")return{target,code:"REVIEW_COMPONENT_VANISHED",errno:"ENOENT",message:describeVanishedReview(target,finding.path),partialRisk:!1};return{target,code:"REVIEW_UNVERIFIED",errno:finding.error?.code,message:describeReviewError(target,finding.path,finding.error),partialRisk:!1}}function resolveTargetRootSync(target,roots,style){let violation=targetShapeViolation(target,style);if(violation!==null)return{kind:"aborted",aborted:{target,code:"REVIEW_NOT_UNDER_ANY_ROOT",message:violation,path:target}};let root=roots.find((candidate)=>insideAnyRoot(target,[candidate.real],style));if(root===void 0)return{kind:"aborted",aborted:{target,code:"REVIEW_NOT_UNDER_ANY_ROOT",message:`安全复核失败 (目标不在任何 roots 之下): ${target}`,path:target}};return{kind:"ok",root}}async function reviewPathOnDisk(target,root,style){let headFinding=await reviewComponents(rootAncestorChain(root,style));if(headFinding!==null){if(headFinding.kind==="unsafe"){let location=headFinding.path===root.configured?root.configured:`${headFinding.path} (根: ${root.configured})`;return{kind:"aborted",aborted:{target,code:"REVIEW_HEAD_SYMLINK",message:`安全复核失败 (根被替换为符号链接): ${location}`,path:headFinding.path}}}return{kind:"failed",failure:toReviewFailure(target,headFinding)}}let finding=await reviewComponents(componentChain(root.real,target,style));if(finding!==null){if(finding.kind==="unsafe")return{kind:"aborted",aborted:{target,code:"REVIEW_COMPONENT_REPLACED",message:`安全复核失败 (路径组件被替换): ${finding.path}`,path:finding.path}};return{kind:"failed",failure:toReviewFailure(target,finding)}}return{kind:"ok"}}function splitStaleRejections(rejected,staleTargets){if(staleTargets!=="missing")return{rejected,stale:[]};let rest=[],stale=[];for(let item of rejected)if(item.code==="GUARD_TARGET_MISSING")stale.push(item.target);else rest.push(item);return{rejected:rest,stale}}var PARTIAL_DELETION_HINT="注意: 目录内容可能已被部分或全部删除, 请复查";function describeRemovalError(target,error){return`${describeCode(error)} (目标: ${target}; ${PARTIAL_DELETION_HINT})`}async function checkGone(path){try{return await lstat3(path),"present"}catch(error){return error?.code==="ENOENT"?"gone":"unknown"}}function describeSurvivor(target,state){return`ENOENT: 删除中途失败 (${state==="present"?"复核确认目标仍存在":"目标是否仍存在未能核验"}) (目标: ${target}; ${PARTIAL_DELETION_HINT})`}var REMOVAL_CONCURRENCY=4;async function executeRm(target){try{return await rm(target,{recursive:!0,force:!1}),{kind:"removed",target}}catch(error){if(error?.code==="ENOENT"){let state=await checkGone(target);if(state==="gone")return{kind:"missing",target};return{kind:"failed",failure:{target,code:"REMOVE_ENOENT_SURVIVOR",errno:"ENOENT",message:describeSurvivor(target,state),partialRisk:!0}}}return{kind:"failed",failure:{target,code:"REMOVE_FAILED",errno:error?.code,message:describeRemovalError(target,error),partialRisk:!0}}}}function assembleRemovalResult(slots,aborted){let result={removed:[],missing:[],failed:[]};for(let slot of slots){if(slot===void 0)continue;switch(slot.kind){case"removed":result.removed.push(slot.target);break;case"missing":result.missing.push(slot.target);break;case"failed":result.failed.push(slot.failure);break;case"aborted":break}}if(aborted!==void 0)result.aborted=aborted;return result}async function removeTargets(targets,options){if(options?.signal?.aborted)throw new SweepError("CANCELLED","删除在条目间检查点被取消",{phase:"remove",partial:{removed:[],missing:[],failed:[]}});let roots=options?.roots??[],style=options?.style??nativeStyle(),signal=options?.signal,emit=options?.onProgress,slots=Array.from({length:targets.length}),aborted,abortedIndex=Number.POSITIVE_INFINITY,recordAbort=(index,info)=>{if(index>=abortedIndex)return;aborted=info,abortedIndex=index},cancelled=!1,failures=[],next=0,active=0,resolveDrained=null,drained=new Promise((resolve)=>{resolveDrained=resolve}),halted=()=>cancelled||aborted!==void 0||failures.length>0;function pump(){while(active<REMOVAL_CONCURRENCY&&next<targets.length&&!halted()){let index=next;next+=1,active+=1,removeOne(index)}if(active===0&&resolveDrained!==null){let resolve=resolveDrained;resolveDrained=null,resolve()}}async function removeOne(index){try{let target=targets[index];if(target===void 0)return;if(signal?.aborted){cancelled=!0;return}let syncCheck=resolveTargetRootSync(target,roots,style);if(syncCheck.kind==="aborted"){recordAbort(index,syncCheck.aborted),slots[index]={kind:"aborted"};return}let review=await reviewPathOnDisk(target,syncCheck.root,style);if(review.kind==="aborted"){recordAbort(index,review.aborted),slots[index]={kind:"aborted"};return}if(review.kind==="failed"){slots[index]={kind:"failed",failure:review.failure},emit?.({kind:"failed",failure:review.failure});return}let outcome=await executeRm(target);slots[index]=outcome,emit?.(outcome)}catch(error){if(failures.length===0)failures.push(error)}finally{if(signal?.aborted)cancelled=!0;active-=1,pump()}}if(pump(),await drained,failures.length>0)throw failures[0];let result=assembleRemovalResult(slots,aborted);if(aborted!==void 0)emit?.({kind:"aborted",aborted});if(cancelled)throw new SweepError("CANCELLED","删除在条目间检查点被取消",{phase:"remove",partial:result});return result}async function toTrustRoots(roots){return Promise.all(roots.map(async(root)=>({configured:root,real:await realpath2(root).catch(()=>null)??root})))}import{readdir,realpath as realpath3,stat as stat2}from"node:fs/promises";import{join as join3}from"node:path";var NODE_MODULES="node_modules",GIT_DIR=".git",CONCURRENCY=32;function compareTarget(a,b){if(a.target<b.target)return-1;if(a.target>b.target)return 1;return 0}function rootFailureWarning(error,root){let{code}=error;switch(code){case"ENOENT":return{code:"SCAN_ROOT_MISSING",message:`根不存在, 已跳过: ${root}`,path:root};case"EACCES":case"EPERM":return{code:"SCAN_ROOT_UNREADABLE",message:`根不可读 (权限不足), 已跳过: ${root}`,path:root,errno:code};case"ENOTDIR":return{code:"SCAN_ROOT_NOT_DIR",message:`根不是目录, 已跳过: ${root}`,path:root};default:return{code:"SCAN_ROOT_UNAVAILABLE",message:`根不可用 (${code??"UNKNOWN"}), 已跳过: ${root}`,path:root,errno:code}}}async function walkRoot(root,ctx){let{style,exclude,excludeCounts,include,includeCounts,hits,warnings,signal,onProgress}=ctx,stack=[{dir:root,included:include.size===0}],active=0,failures=[],resolveDrained=null,drained=new Promise((resolve)=>{resolveDrained=resolve});function pump(){while(active<CONCURRENCY&&stack.length>0&&failures.length===0&&!signal?.aborted){let next=stack.pop();active+=1,visit(next.dir,next.included)}let stopped=failures.length>0||signal?.aborted===!0;if(active===0&&(stack.length===0||stopped)&&resolveDrained!==null){let resolve=resolveDrained;resolveDrained=null,resolve()}}async function visit(dir,included){try{if(signal?.aborted)throw new SweepError("CANCELLED","扫描在遍历任务检查点被取消",{phase:"scan"});let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch(error){let errno=error?.code;warnings.push({code:"SCAN_DIR_UNREADABLE",message:`目录不可读, 已跳过: ${dir}`,path:dir,...typeof errno==="string"?{errno}:{}});return}for(let entry of entries){if(!entry.isDirectory())continue;let name=entry.name;if(name===NODE_MODULES){if(!included)continue;let target=join3(dir,name),key=dedupeKey(await realpath3(target).catch(()=>target),style);if(!hits.has(key)){let hit={project:dir,target,root};hits.set(key,hit),onProgress?.({kind:"hit",hit})}continue}if(name===GIT_DIR)continue;let childIncluded=included||include.has(name);if(!included&&include.has(name))includeCounts.set(name,(includeCounts.get(name)??0)+1);if(exclude.has(name)){excludeCounts.set(name,(excludeCounts.get(name)??0)+1);continue}stack.push({dir:join3(dir,name),included:childIncluded})}}catch(error){if(failures.length===0)failures.push(error)}finally{active-=1,pump()}}if(pump(),await drained,failures.length>0)throw failures[0];if(signal?.aborted)throw new SweepError("CANCELLED","扫描在遍历任务检查点被取消",{phase:"scan"})}function createParallelScanner(){return{name:"parallel",async scan(options){if(options.signal?.aborted)throw new SweepError("CANCELLED","扫描在根预检阶段被取消",{phase:"scan"});let warnings=[],exclude=new Set(options.exclude),excludeCounts=new Map;for(let name of options.exclude)if(!excludeCounts.has(name))excludeCounts.set(name,0);let include=new Set(options.include),includeCounts=new Map;for(let name of options.include)if(!includeCounts.has(name))includeCounts.set(name,0);let hitsByRealTarget=new Map,style=nativeStyle(),seenRoots=new Set,roots=[];for(let root of options.roots){if(options.signal?.aborted)throw new SweepError("CANCELLED","扫描在根预检阶段被取消",{phase:"scan"});let key;try{let resolved=await realpath3(root);if(!(await stat2(resolved)).isDirectory()){warnings.push({code:"SCAN_ROOT_NOT_DIR",message:`根不是目录, 已跳过: ${root}`,path:root});continue}key=dedupeKey(resolved,style)}catch(error){warnings.push(rootFailureWarning(error,root));continue}if(seenRoots.has(key))continue;seenRoots.add(key),roots.push(root)}let context={style,exclude,excludeCounts,include,includeCounts,hits:hitsByRealTarget,warnings,signal:options.signal,onProgress:options.onProgress};for(let root of roots)await walkRoot(root,context);let hits=[...hitsByRealTarget.values()].sort(compareTarget),excludeMatches=options.exclude.map((name)=>({name,hits:excludeCounts.get(name)??0})),includeMatches=options.include.map((name)=>({name,hits:includeCounts.get(name)??0}));return{hits,warnings,excludeMatches,includeMatches}}}}function createScanner(){return createParallelScanner()}import{spawn}from"node:child_process";import{accessSync,constants}from"node:fs";var PROG_PREFIX_RE=/^(?:\/[^\s:]*)?[a-z][a-z0-9_-]*:\s+/;function describeDuFailure(detail){if(/no such file or directory/i.test(detail))return{missing:!0,reason:"不存在"};if(/permission denied/i.test(detail))return{missing:!1,code:"SIZE_UNMEASURED_PERMISSION",reason:"权限不足, 无法读取"};if(/not a directory/i.test(detail))return{missing:!1,code:"SIZE_UNMEASURED_NOT_DIR",reason:"不是目录"};if(/too many levels of symbolic links/i.test(detail))return{missing:!1,code:"SIZE_UNMEASURED_LOOP",reason:"符号链接层级过深"};return{missing:!1,code:"SIZE_UNMEASURED_OTHER",reason:`读取失败 (${detail})`}}var ANSI_C_ESCAPES={"\\":92,"'":39,'"':34,a:7,b:8,f:12,n:10,r:13,t:9,v:11,e:27,E:27};function pushUtf8(bytes,text){for(let byte of Buffer.from(text,"utf8"))bytes.push(byte)}function decodeAnsiCEscape(raw,index,bytes){let ch=raw[index];if(ch===void 0)return index;let mapped=ANSI_C_ESCAPES[ch];if(mapped!==void 0)return bytes.push(mapped),index+1;let oct=/^[0-7]{1,3}/.exec(raw.slice(index));if(oct!==null)return bytes.push(Number.parseInt(oct[0],8)%256),index+oct[0].length;if(ch==="x"){let hex=/^[0-9a-fA-F]{1,2}/.exec(raw.slice(index+1));if(hex!==null)return bytes.push(Number.parseInt(hex[0],16)),index+1+hex[0].length}return pushUtf8(bytes,ch),index+1}function consumeAnsiCSegment(raw,start,bytes){let index=start;while(index<raw.length){let inner=raw[index];if(inner==="'")return index+1;if(inner==="\\"){index=decodeAnsiCEscape(raw,index+1,bytes);continue}pushUtf8(bytes,inner??""),index+=1}return-1}function consumeDoubleQuoted(raw,start,bytes){let index=start;while(index<raw.length){let inner=raw[index];if(inner==='"')return index+1;if(inner==="\\"&&index+1<raw.length&&'"\\$`'.includes(raw[index+1]??"")){pushUtf8(bytes,raw[index+1]??""),index+=2;continue}pushUtf8(bytes,inner??""),index+=1}return-1}function unescapeGnuShellQuoted(raw){let bytes=[],index=0;while(index<raw.length){let ch=raw[index];if(ch==="$"&&raw[index+1]==="'"){if(index=consumeAnsiCSegment(raw,index+2,bytes),index===-1)return raw;continue}if(ch==="'"){let end=raw.indexOf("'",index+1);if(end===-1)return raw;pushUtf8(bytes,raw.slice(index+1,end)),index=end+1;continue}if(ch==='"'){if(index=consumeDoubleQuoted(raw,index+1,bytes),index===-1)return raw;continue}if(ch==="\\"&&index+1<raw.length){pushUtf8(bytes,raw[index+1]??""),index+=2;continue}pushUtf8(bytes,ch??""),index+=1}return Buffer.from(bytes).toString("utf8")}function parseDuErrorLine(line){let body=line.replace(PROG_PREFIX_RE,""),gnu=/^cannot\s+(?:access|read directory|stat|open)\s+(.+):\s+(.+)$/.exec(body);if(gnu!==null){let rawPath=gnu[1],detail=gnu[2];if(rawPath!==void 0&&detail!==void 0)return{path:rawPath.startsWith("'")||rawPath.startsWith('"')||rawPath.startsWith("$'")?unescapeGnuShellQuoted(rawPath):rawPath,detail}}let match=/^(.+):\s+(.+)$/.exec(body);if(match===null)return null;let path=match[1],detail=match[2];if(path===void 0||detail===void 0)return null;return{path,detail}}var DU_PROBES=["/usr/bin/du","/bin/du"],hasControlChar=(target)=>target.includes(`
|
|
6
|
+
`)||target.includes("\r");function findDu(platform=process.platform){if(platform==="win32")return null;for(let probe of DU_PROBES)try{return accessSync(probe,constants.X_OK),probe}catch{}return null}var DU_BATCH_MAX_BYTES=131072;function chunkTargetsByBytes(targets,maxBytes=DU_BATCH_MAX_BYTES){let batches=[],current=[],currentBytes=0;for(let target of targets){let size=Buffer.byteLength(target,"utf8")+1;if(current.length>0&¤tBytes+size>maxBytes)batches.push(current),current=[],currentBytes=0;current.push(target),currentBytes+=size}if(current.length>0)batches.push(current);return batches}function runDu(bin,targets){return new Promise((resolve)=>{let env={...process.env,LC_ALL:"C",LANG:"C"};delete env.QUOTING_STYLE,delete env.LANGUAGE;let child=spawn(bin,["-sk","--",...targets],{stdio:["ignore","pipe","pipe"],env});child.stdout.setEncoding("utf8"),child.stderr.setEncoding("utf8");let stdout="",stderr="",settled=!1,finish=(result)=>{if(settled)return;settled=!0,resolve(result)};child.stdout.on("data",(chunk)=>{stdout+=chunk}),child.stderr.on("data",(chunk)=>{stderr+=chunk}),child.on("error",(error)=>{finish({stdout,stderr,exitCode:null,signal:null,spawnError:error})}),child.on("close",(exitCode,signal)=>{finish({stdout,stderr,exitCode,signal,spawnError:null})})})}function parseDuSizes(stdout){let sizes=new Map,duplicated=!1;for(let line of stdout.split(`
|
|
7
|
+
`)){let match=/^(\d+)\t(.+)$/.exec(line);if(match===null)continue;let sizeKiB=match[1],path=match[2];if(sizeKiB===void 0||path===void 0)continue;if(sizes.has(path))duplicated=!0;sizes.set(path,Number(sizeKiB)*1024)}return{sizes,duplicated}}function assessDuOutput(stdout,safeTargets){let safeSet=new Set(safeTargets),parsed=parseDuSizes(stdout),unexpected=!1;for(let path of parsed.sizes.keys())if(!safeSet.has(path))unexpected=!0;let intact=!parsed.duplicated&&parsed.sizes.size<=safeTargets.length&&!unexpected;return{sizes:parsed.sizes,intact,duplicated:parsed.duplicated,unexpected}}function describeAnomaly(assessment){let shapes=[];if(assessment.duplicated)shapes.push("同一路径多行");if(assessment.unexpected)shapes.push("含输入之外的路径");if(shapes.length===0)shapes.push("行数与输入不符");return shapes.join(" / ")}async function measureDuBatches(bin,safeTargets,maxBatchBytes,signal){let sizes=new Map,failures=new Map,degraded=new Set,warnings=[];for(let batch of chunkTargetsByBytes(safeTargets,maxBatchBytes)){if(signal?.aborted)throw new SweepError("CANCELLED","体积统计在批量统计前被取消",{phase:"measure"});let run=await runDu(bin,batch);if(run.spawnError!==null||run.signal!==null){for(let target of batch)degraded.add(target);let errno=run.spawnError?.code,reason=run.spawnError!==null?`du 执行失败 (${run.spawnError.message})`:`du 被信号 ${run.signal} 中止`;warnings.push({code:"SIZE_DU_UNAVAILABLE",message:`${reason}: 本批 ${batch.length} 个目标的体积均未采信`,...typeof errno==="string"?{errno}:{}});continue}let{stdout,stderr}=run,batchSet=new Set(batch),assessment=assessDuOutput(stdout,batch);if(!assessment.intact){for(let target of batch)degraded.add(target);warnings.push({code:"SIZE_DU_OUTPUT_MISMATCH",message:`du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${batch.length} 个目标的体积均未采信`})}else for(let[path,bytes]of assessment.sizes)sizes.set(path,bytes);for(let line of stderr.split(`
|
|
8
|
+
`)){if(line.trim()==="")continue;let errorLine=parseDuErrorLine(line);if(errorLine===null){warnings.push({code:"SIZE_DU_LINE_UNATTRIBUTED",message:`体积统计失败 (未归因): ${line.replace(PROG_PREFIX_RE,"").trim()}`});continue}let failure=describeDuFailure(errorLine.detail);if(!batchSet.has(errorLine.path)){warnings.push({code:"SIZE_SUBPATH_FAILED",message:`体积统计失败 (${failure.reason}): ${errorLine.path}`,path:errorLine.path});continue}failures.set(errorLine.path,failure)}}for(let path of failures.keys())sizes.delete(path);return{sizes,failures,degraded,warnings}}function createDuSizer(bin=findDu(),maxBatchBytes=DU_BATCH_MAX_BYTES){return{name:"du",basis:"disk-usage",async measure(targets,options){if(options?.signal?.aborted)throw new SweepError("CANCELLED","体积统计在批量统计前被取消",{phase:"measure"});let sorted=[...new Set(targets)].sort(),emit=options?.onProgress;if(bin===null){let unmeasured=[],reason="du 候选不可用";for(let target of sorted){if(options?.signal?.aborted)throw new SweepError("CANCELLED","体积统计在逐目标检查点被取消",{phase:"measure"});unmeasured.push({target,code:"SIZE_UNMEASURED_OTHER",reason:"du 候选不可用"}),emit?.({kind:"unmeasured",target,code:"SIZE_UNMEASURED_OTHER",reason:"du 候选不可用"})}return{entries:[],basis:"disk-usage",warnings:[{code:"SIZE_DU_UNAVAILABLE",message:"du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"}],unmeasured,gone:[]}}if(sorted.length===0)return{entries:[],basis:"disk-usage",warnings:[],unmeasured:[],gone:[]};let entries=[],unmeasured=[],gone=[],safeTargets=sorted.filter((target)=>!hasControlChar(target)),{sizes,failures,degraded,warnings}=safeTargets.length>0?await measureDuBatches(bin,safeTargets,maxBatchBytes,options?.signal):{sizes:new Map,failures:new Map,degraded:new Set,warnings:[]},pushUnmeasured=(target,code,reason)=>{unmeasured.push({target,code,reason}),emit?.({kind:"unmeasured",target,code,reason})};for(let target of sorted){if(options?.signal?.aborted)throw new SweepError("CANCELLED","体积统计在逐目标检查点被取消",{phase:"measure"});if(hasControlChar(target)){pushUnmeasured(target,"SIZE_UNMEASURED_CONTROL_CHAR","路径含控制字符");continue}if(degraded.has(target)){pushUnmeasured(target,"SIZE_UNMEASURED_UNPARSEABLE","输出不可解析");continue}let bytes=sizes.get(target);if(bytes!==void 0){entries.push({target,bytes}),emit?.({kind:"measured",target,bytes,basis:"disk-usage"});continue}let failure=failures.get(target);if(failure===void 0){pushUnmeasured(target,"SIZE_UNMEASURED_UNPARSEABLE","输出不可解析");continue}if(failure.missing){gone.push(target),warnings.push({code:"SIZE_TARGET_VANISHED",message:`体积统计失败 (不存在): ${target}`,path:target}),emit?.({kind:"gone",target});continue}pushUnmeasured(target,failure.code,failure.reason)}return{entries,basis:"disk-usage",warnings,unmeasured,gone}}}}import{lstat as lstat4,readdir as readdir2}from"node:fs/promises";import{join as join4}from"node:path";function describeFailure(code){switch(code){case"ENOENT":return{missing:!0,reason:"不存在"};case"EACCES":case"EPERM":return{missing:!1,code:"SIZE_UNMEASURED_PERMISSION",reason:"权限不足, 无法读取"};case"ENOTDIR":return{missing:!1,code:"SIZE_UNMEASURED_NOT_DIR",reason:"不是目录"};case"ELOOP":return{missing:!1,code:"SIZE_UNMEASURED_LOOP",reason:"符号链接层级过深"};default:return{missing:!1,code:"SIZE_UNMEASURED_OTHER",reason:code===void 0?"读取失败":`读取失败 (${code})`}}}function errorCode(error){return error?.code}var SIZE_CONCURRENCY=32;function pushSubpathWarning(warnings,path,error){let errno=errorCode(error);warnings.push({code:"SIZE_SUBPATH_FAILED",message:`体积统计失败 (${describeFailure(errno).reason}): ${path}`,path,...errno!==void 0?{errno}:{}})}function enqueueDirents(stack,dir,dirents){for(let dirent of dirents){if(dirent.isSymbolicLink())continue;let path=join4(dir,dirent.name);if(dirent.isDirectory())stack.push({kind:"dir",path});else if(dirent.isFile())stack.push({kind:"file",path})}}async function sumEntries(dirents,dir,warnings,signal){let stack=[];enqueueDirents(stack,dir,dirents);let total=0,active=0,failures=[],resolveDrained=null,drained=new Promise((resolve)=>{resolveDrained=resolve});function pump(){while(active<SIZE_CONCURRENCY&&stack.length>0&&failures.length===0&&!signal?.aborted){let item=stack.pop();active+=1,processItem(item)}let stopped=failures.length>0||signal?.aborted===!0;if(active===0&&(stack.length===0||stopped)&&resolveDrained!==null){let resolve=resolveDrained;resolveDrained=null,resolve()}}async function processItem(item){try{if(signal?.aborted)throw new SweepError("CANCELLED","体积统计在目录遍历检查点被取消",{phase:"measure"});if(item.kind==="dir"){try{let children=await readdir2(item.path,{withFileTypes:!0});enqueueDirents(stack,item.path,children)}catch(error){pushSubpathWarning(warnings,item.path,error)}return}try{let stats=await lstat4(item.path);if(stats.isFile())total+=stats.size}catch(error){pushSubpathWarning(warnings,item.path,error)}}catch(error){if(failures.length===0)failures.push(error)}finally{active-=1,pump()}}if(pump(),await drained,failures.length>0)throw failures[0];if(signal?.aborted)throw new SweepError("CANCELLED","体积统计在目录遍历检查点被取消",{phase:"measure"});return total}function createJsSizer(){return{name:"js",basis:"logical-bytes",async measure(targets,options){if(options?.signal?.aborted)throw new SweepError("CANCELLED","体积统计在逐目标检查点被取消",{phase:"measure"});let warnings=[],entries=[],unmeasured=[],gone=[],emit=options?.onProgress,pushUnmeasured=(target,code,reason)=>{unmeasured.push({target,code,reason}),emit?.({kind:"unmeasured",target,code,reason})};for(let target of[...new Set(targets)].sort()){if(options?.signal?.aborted)throw new SweepError("CANCELLED","体积统计在逐目标检查点被取消",{phase:"measure"});let dirents;try{if((await lstat4(target)).isSymbolicLink()){pushUnmeasured(target,"SIZE_UNMEASURED_NOT_DIR","不是目录");continue}dirents=await readdir2(target,{withFileTypes:!0})}catch(error){let failure=describeFailure(errorCode(error));if(failure.missing)gone.push(target),warnings.push({code:"SIZE_TARGET_VANISHED",message:`体积统计失败 (${failure.reason}): ${target}`,path:target}),emit?.({kind:"gone",target});else pushUnmeasured(target,failure.code,failure.reason);continue}let bytes=await sumEntries(dirents,target,warnings,options?.signal);entries.push({target,bytes}),emit?.({kind:"measured",target,bytes,basis:"logical-bytes"})}return{entries,basis:"logical-bytes",warnings,unmeasured,gone}}}}function createSizer(){let bin=findDu();return bin!==null?createDuSizer(bin):createJsSizer()}var invalidArgument=(field,message)=>new SweepError("INVALID_ARGUMENT",`${message} (字段: ${field})`,{field});function assertNameArray(value,field,required){if(value===void 0){if(required)throw invalidArgument(field,"为必填项");return}if(!Array.isArray(value)||value.some((item)=>typeof item!=="string"||item===""))throw invalidArgument(field,"必须是非空字符串数组");if(required&&value.length===0)throw invalidArgument(field,"不能为空数组")}var WIN32_ABS_ROOT_RE=/^(?:[A-Za-z]:[/\\]|[/\\]{2}[^/\\]+[/\\][^/\\]+)/;function isAbsoluteRoot(root,style){return style.name==="win32"?WIN32_ABS_ROOT_RE.test(root):style.ops.isAbsolute(root)}function assertShape(options){if(typeof options!=="object"||options===null)throw invalidArgument("options","构造选项必须是对象");assertNameArray(options.roots,"roots",!0);let style=options.style??nativeStyle();if(options.roots.some((root)=>!isAbsoluteRoot(root,style)))throw invalidArgument("roots","必须是绝对路径");if(assertNameArray(options.exclude,"exclude",!1),assertNameArray(options.include,"include",!1),options.home!==void 0&&options.home!==null&&(typeof options.home!=="string"||options.home===""))throw invalidArgument("home","必须是非空字符串或 null");if(options.policy!==void 0&&(typeof options.policy!=="object"||options.policy===null||typeof options.policy.releaseSuspects!=="boolean"))throw invalidArgument("policy","releaseSuspects 必须是布尔值")}function resolveOptions(options){return assertShape(options),Object.freeze({roots:Object.freeze([...options.roots]),exclude:Object.freeze(mergeNames(options.exclude??[...DEFAULT_EXCLUDE],[])),include:Object.freeze(mergeNames(options.include??[],[])),home:options.home===void 0?homedir6():options.home,style:options.style??nativeStyle(),policy:Object.freeze({releaseSuspects:options.policy?.releaseSuspects??!1})})}var cancelledAt=(phase)=>new SweepError("CANCELLED",`清理在 ${phase} 阶段被取消`,{phase});async function withPhase(phase,emit,signal,work){if(signal?.aborted)throw cancelledAt(phase);let startedAt=Date.now();emit?.({kind:"phase",phase,status:"start"});let value=await work();return emit?.({kind:"phase",phase,status:"done",elapsedMs:Date.now()-startedAt}),value}async function executePlan(resolved,options,signal){let emit=options?.onProgress,roots=[...resolved.roots],scanResult=await withPhase("scan",emit,signal,async()=>{let result=await createScanner().scan({roots:[...roots],exclude:[...resolved.exclude],include:[...resolved.include],signal,onProgress:(event)=>emit?.(event)});for(let warning of result.warnings)emit?.({kind:"warning",warning});return result}),targets=scanResult.hits.map((hit)=>hit.target),sizeResult=await withPhase("measure",emit,signal,async()=>{let result=await createSizer().measure(targets,{signal,onProgress:(event)=>{if(event.kind==="gone")return;emit?.(event)}});for(let warning of result.warnings)emit?.({kind:"warning",warning});return result}),classifications=await withPhase("classify",emit,signal,()=>scanResult.hits.map((hit)=>classifyTarget(hit.target,{home:resolved.home,style:resolved.style}))),crossDevice=await withPhase("device",emit,signal,async()=>crossDeviceIndex(await findCrossDeviceTargets(targets,{roots,style:resolved.style})));return withPhase("plan",emit,signal,()=>{let policy=resolved.policy,bytesOf=new Map(sizeResult.entries.map((entry)=>[entry.target,entry.bytes])),unmeasuredOf=new Map(sizeResult.unmeasured.map((item)=>[item.target,item])),goneSet=new Set(sizeResult.gone),prepared=[];for(let index=0;index<scanResult.hits.length;index+=1){let hit=scanResult.hits[index],classification=classifications[index];if(hit===void 0||classification===void 0)continue;if(goneSet.has(hit.target))continue;let bytes=bytesOf.get(hit.target);prepared.push({hit,classification,candidate:{target:hit.target,bytes,unmeasuredReason:bytes===void 0?unmeasuredOf.get(hit.target)?.reason:void 0,suspect:classification.kind==="suspect-install-tree"}})}let candidates=prepared.map((item)=>item.candidate),batch=deletionBatch(candidates,crossDevice,policy),book=collectSkips(candidates,crossDevice,policy),noteOf=new Map(book.entries.map((item)=>[item.target,item.note])),entries=[];for(let{hit,classification,candidate}of prepared){let reason=skipReasonOf(candidate,crossDevice,policy),deviceKind=crossDevice.get(hit.target),unmeasured=unmeasuredOf.get(hit.target);if(entries.push({target:hit.target,project:hit.project,root:hit.root,bytes:candidate.bytes,basis:candidate.bytes===void 0?void 0:sizeResult.basis,kind:classification.kind,kindReason:classification.reason,crossDevice:deviceKind,unmeasuredCode:unmeasured?.code,unmeasuredReason:unmeasured?.reason,inBatch:reason===null,skipReason:reason??void 0,skipNote:reason===null?void 0:noteOf.get(hit.target)}),reason!==null)emit?.({kind:"skipped",target:hit.target,reason})}return{roots:[...resolved.roots],exclude:[...resolved.exclude],include:[...resolved.include],policy:{releaseSuspects:policy.releaseSuspects},basis:entries.length>0?sizeResult.basis:void 0,entries,batch,skipped:[...book.entries],trailer:[...book.trailer],warnings:[...scanResult.warnings,...sizeResult.warnings],nameMatches:{exclude:scanResult.excludeMatches,include:scanResult.includeMatches}}})}function buildOutcomeEntries(plan,expectedSet,stale,rejected,mappings,removal){let staleSet=new Set(stale),rejectedMap;if(rejected.length>0){rejectedMap=new Map;for(let item of rejected)if(!rejectedMap.has(item.target))rejectedMap.set(item.target,item)}let realOf=new Map(mappings.map((item)=>[item.original,item.real])),removedSet=new Set(removal?.removed??[]),missingSet=new Set(removal?.missing??[]),failedMap=new Map((removal?.failed??[]).map((item)=>[item.target,item])),outcomeOf=(entry)=>{if(!entry.inBatch)return{kind:"skipped",reason:entry.skipReason};if(expectedSet!==void 0&&!expectedSet.has(entry.target))return{kind:"not-expected"};if(staleSet.has(entry.target))return{kind:"stale"};if(rejectedMap!==void 0){let rejection=rejectedMap.get(entry.target);return rejection!==void 0?{kind:"rejected",rejection}:{kind:"not-attempted",code:"BATCH_REJECTED"}}let realTarget=realOf.get(entry.target)??entry.target;if(removedSet.has(realTarget))return{kind:"removed"};if(missingSet.has(realTarget))return{kind:"missing"};let failure=failedMap.get(realTarget);if(failure!==void 0)return{kind:"failed",failure};return{kind:"not-attempted",code:removal.aborted.code}};return plan.entries.map((entry)=>({...entry,outcome:outcomeOf(entry)}))}async function executeRun(resolved,options,signal){let emit=options?.onProgress,startedAt=Date.now(),plan=await executePlan(resolved,options,signal),expected=options?.expectedBatch,expectedSet=expected===void 0?void 0:new Set(expected),face=expectedSet===void 0?plan.batch:plan.batch.filter((target)=>expectedSet.has(target)),liveSet=new Set(plan.batch),drift=expected===void 0||expectedSet===void 0?void 0:{added:plan.batch.filter((target)=>!expectedSet.has(target)),removed:expected.filter((target)=>!liveSet.has(target))},validation,removal,stale=[],rejected=[];if(face.length>0){let raw=await withPhase("validate",emit,signal,()=>validateTargets(face,{roots:[...resolved.roots],home:resolved.home,style:resolved.style,signal})),split=splitStaleRejections(raw.rejected,options?.staleTargets);if(stale=split.stale,rejected=split.rejected,validation={accepted:raw.accepted,rejected,mappings:raw.mappings},rejected.length===0)removal=await withPhase("remove",emit,signal,async()=>removeTargets(raw.accepted,{roots:await toTrustRoots([...resolved.roots]),style:resolved.style,signal,onProgress:(event)=>{if(event.kind==="removed"||event.kind==="missing"){emit?.({kind:"removed",target:event.target,outcome:event.kind});return}emit?.(event)}}))}let status;if(face.length===0)status="nothing-to-do";else if(rejected.length>0)status="rejected";else status="executed";let entries=buildOutcomeEntries(plan,expectedSet,stale,rejected,validation?.mappings??[],removal),releasedBytes=entries.reduce((sum,entry)=>isSuccessOutcome(entry.outcome)?sum+(entry.bytes??0):sum,0),report={status,plan,validation,removal,entries,stale,releasedBytes,drift};return emit?.({kind:"done",status,elapsedMs:Date.now()-startedAt}),report}function createSweeper(options){let resolved=resolveOptions(options);return{options:resolved,async plan(planOptions){let startedAt=Date.now(),plan=await executePlan(resolved,planOptions,planOptions?.signal);return planOptions?.onProgress?.({kind:"plan-done",plan,elapsedMs:Date.now()-startedAt}),plan},run(runOptions){return executeRun(resolved,runOptions,runOptions?.signal)}}}var VALUE_FLAGS=new Set(["--exclude","--include","--config"]);function applyValueFlag(options,flag,value){if(flag==="--exclude")return options.exclude.push(value),null;if(flag==="--include")return options.include.push(value),null;if(options.config!==void 0)return"参数 --config 不能重复指定";return options.config=value,null}function splitEqualsFlag(arg){let eqIndex=arg.indexOf("=");if(eqIndex<=0)return null;let flag=arg.slice(0,eqIndex);if(!VALUE_FLAGS.has(flag))return null;return{flag,value:arg.slice(eqIndex+1)}}function parseArgs(argv){if(argv[0]==="update")return{ok:!0,options:{command:"update",yes:!1,force:!1,exclude:[],include:[],updateArgs:argv.slice(1),help:!1,version:!1}};let options={command:"sweep",yes:!1,force:!1,exclude:[],include:[],help:!1,version:!1},positionals=[];for(let index=0;index<argv.length;index+=1){let arg=argv[index];if(arg===void 0)continue;if(arg==="--yes"){options.yes=!0;continue}if(arg==="--force"){options.force=!0;continue}if(arg==="--help"||arg==="-h"){options.help=!0;continue}if(arg==="--version"||arg==="-V"){options.version=!0;continue}if(VALUE_FLAGS.has(arg)){let value=argv[index+1];if(value===void 0||value===""||value.startsWith("-"))return{ok:!1,message:`参数 ${arg} 缺少取值`};let err=applyValueFlag(options,arg,value);if(err!==null)return{ok:!1,message:err};index+=1;continue}let eq=splitEqualsFlag(arg);if(eq!==null){if(eq.value==="")return{ok:!1,message:`参数 ${eq.flag} 缺少取值`};let err=applyValueFlag(options,eq.flag,eq.value);if(err!==null)return{ok:!1,message:err};continue}if(arg.startsWith("-"))return{ok:!1,message:`未知参数: ${arg}`};positionals.push(arg)}let[only]=positionals;if(positionals.includes("update"))return{ok:!1,message:"子命令 update 必须位于参数首位 (用法: sweep-nm update [选项])"};if(positionals.length>1||only!==void 0&&only!=="init"&&only!=="config")return{ok:!1,message:`未知参数: ${positionals.join(" ")}`};if(only==="init"||only==="config"){options.command=only;let disallowed=[];if(options.yes)disallowed.push("--yes");if(options.force)disallowed.push("--force");if(options.exclude.length>0)disallowed.push("--exclude");if(options.include.length>0)disallowed.push("--include");if(disallowed.length>0)return{ok:!1,message:`子命令 ${options.command} 不支持参数: ${disallowed.join(", ")}`}}return{ok:!0,options}}var BANNER="SWEEP-NM",BAR_BLOCK="▍",TOTAL_BLOCK="█",NEUTRAL_BLOCK="░",PLATFORM_STYLE=nativeStyle(),NEUTRAL_TIER={block:NEUTRAL_BLOCK,sgr:"2"},ROOT_LIST_LIMIT=3,bannerLine=(suffix,color)=>paint(`${BAR_BLOCK} ${BANNER} ${suffix}`,"1;7",color),neutralLine=(text,color)=>` ${paint(`${NEUTRAL_BLOCK} ${text}`,"2",color)}`,TIER_BIG=536870912,TIER_MID=104857600;function render(options){let{mode,roots,entries,color,home,releasedBytes,pathStyle}=options,style=pathStyle??PLATFORM_STYLE,scope=roots.length>0&&roots.length<=ROOT_LIST_LIMIT?`${roots.length} 个根: ${roots.map((root)=>sanitizeLine(shortenPath(root,style,home))).join(" · ")}`:`${roots.length} 个根`,runtime=options.runtime?` · ${sanitizeLine(options.runtime)}`:"",head=bannerLine(`${mode==="execute"?"执行":"预览"} · ${scope}${runtime}`,color),notes=(options.notes??[]).map((note)=>neutralLine(sanitizeLine(note),color)),trailer=(options.trailer??[]).map((line)=>neutralLine(sanitizeLine(line),color));if(entries.length===0)return[head,...notes,` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`,"2",color)}`,...trailer].join(`
|
|
9
|
+
`);let rows=[...entries].sort((a,b)=>(b.bytes??-1)-(a.bytes??-1)),volumeWidth=rows.reduce((max,row)=>Math.max(max,displayWidth(volumeOf(row))),0),nameWidth=rows.reduce((max,row)=>Math.max(max,displayWidth(sanitizeLine(row.project))),0),body=rows.map((row)=>{let fail=mode==="execute"&&row.ok===!1,tier=row.bytes===void 0?NEUTRAL_TIER:tierOf(row.bytes),mark=mode==="execute"?paint(fail?"✗":"✓",fail?"31":"32",color):paint(tier.block,tier.sgr,color),volume=padStart(volumeOf(row),volumeWidth),name=sanitizeLine(row.project),rawPath=displayPath(row.target,style,home,row.suspect===!0),path=sanitizeLine(rawPath),rewritten=name!==row.project||path!==rawPath,tail=tailsOf(row,fail,rewritten),shown=`${paint(padEnd(name,nameWidth),"1",color)} ${paint(path,"2",color)}`;return` ${mark} ${volume} ${shown}${tail?` ${paint(tail,"2",color)}`:""}`}),hint=[paint("加","2",color),paint("--yes","1",color),paint("执行删除","2",color)].join(" "),foot=mode==="execute"?footExecute(rows,color,releasedBytes):` ${paint(TOTAL_BLOCK,"7",color)} ${paint(`合计 ${rows.length} 处 · ${formatBytes(sum(rows))}`,"1",color)} ${hint}`;return[head,...notes,...body,foot,...trailer].join(`
|
|
10
|
+
`)}function footExecute(rows,color,releasedBytes){let failed=rows.filter((row)=>row.ok===!1).length,released=releasedBytes===void 0?"":` · 释放 ${formatBytes(releasedBytes)}`;return` ${paint(TOTAL_BLOCK,"7",color)} ${paint(`汇总 成功 ${rows.length-failed} 处${released} · 失败 ${failed} 处`,"1",color)}`}var volumeOf=(row)=>row.bytes===void 0?"?":formatBytes(row.bytes),SANITIZED_NOTE="名字已净化显示";function tailsOf(row,fail,rewritten){let parts=[];if(rewritten)parts.push(SANITIZED_NOTE);if(row.note)parts.push(sanitizeLine(row.note));if(fail&&row.error)parts.push(sanitizeLine(row.error));return parts.join(" ")}function tierOf(bytes){if(bytes>=TIER_BIG)return{block:"█",sgr:"31"};if(bytes>=TIER_MID)return{block:"▓",sgr:"33"};return{block:"▒",sgr:"36"}}var paint=(text,sgr,color)=>color?`\x1B[${sgr}m${text}\x1B[0m`:text,sum=(rows)=>rows.reduce((total,row)=>total+(row.bytes??0),0),fold3=(text,style)=>style.caseInsensitive?text.toLowerCase():text;function shortenPath(path,style,home){if(!home)return path;let sep=style.ops.sep,fsRoot=style.ops.parse(home).root,normalizedHome=home;while(normalizedHome.length>fsRoot.length&&normalizedHome.endsWith(sep))normalizedHome=normalizedHome.slice(0,-sep.length);if(fold3(path,style)===fold3(normalizedHome,style))return"~";let prefix=normalizedHome.endsWith(sep)?normalizedHome:`${normalizedHome}${sep}`;return fold3(path,style).startsWith(fold3(prefix,style))?`~${sep}${path.slice(prefix.length)}`:path}function shortenHome(path,home,style=PLATFORM_STYLE){return shortenPath(path,style,home)}function displayPath(target,style,home,keepSuffix=!1){let suffix=`${style.ops.sep}node_modules`,dir=target;if(!keepSuffix&&fold3(target,style).endsWith(fold3(suffix,style))){let stripped=target.slice(0,-suffix.length);dir=stripped===""?style.ops.sep:stripped}return shortenPath(dir,style,home)}var padEnd=(text,width)=>text+" ".repeat(Math.max(0,width-displayWidth(text))),padStart=(text,width)=>" ".repeat(Math.max(0,width-displayWidth(text)))+text,ZERO_WIDTH_MARK_RE=/[\p{Mn}\p{Me}]/u;function displayWidth(text){let width=0;for(let char of text){let code=char.codePointAt(0)??0;if(code===8205||code===65038||code===65039||ZERO_WIDTH_MARK_RE.test(char))continue;width+=isFullWidth(code)?2:1}return width}function isFullWidth(code){return code>=4352&&code<=4447||code>=11904&&code<=42191||code>=44032&&code<=55203||code>=63744&&code<=64255||code>=65072&&code<=65135||code>=65280&&code<=65376||code>=65504&&code<=65510||code>=127744&&code<=128591||code>=128640&&code<=128767||code>=129280&&code<=129791||code>=131072&&code<=262141}var COMMANDS=[["sweep-nm","预览: 清单 + 体积 + 合计, 零副作用"],["sweep-nm --yes","执行删除"],["sweep-nm --force","连同疑似安装树一并删除 (默认跳过)"],["sweep-nm --exclude <name>","临时追加排除 (可重复, 与配置合并)"],["sweep-nm --include <name>","只清理命中名单的目录 (可重复, 与配置合并)"],["sweep-nm --config <path>","指定配置文件 (优先于 SWEEP_NM_CONFIG)"],["sweep-nm config","查看实际生效的配置: 来源 + 路径 + 文件状态"],["sweep-nm init","初始化向导: 交互生成配置文件"],["sweep-nm update","自更新: 自动识别安装器升级到最新版 (--check 仅检查)"],["sweep-nm --version","显示版本号"],["sweep-nm -V","--version 的别名"],["sweep-nm --help","帮助"],["sweep-nm -h","--help 的别名"]],COMMAND_COLUMN=COMMANDS.reduce((max,[command])=>Math.max(max,command.length),0);function defaultConfigPath(){return resolveConfigPath({env:{}}).path}function helpText(color){let rows=COMMANDS.map(([command,desc])=>` ${command.padEnd(COMMAND_COLUMN)} ${desc}`);return[bannerLine("工作区 node_modules 清理",color),"",...rows,"","说明:"," --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过"," --include 同款匹配口径, 命中才纳入; 同时命中 exclude 的照旧跳过"," 配置未写 exclude 字段时使用内置默认名单 (包管理器 / 版本管理器 / 编辑器扩展等安装树目录)"," --force 只放行「疑似安装树」(安装树形态的目标), 不放宽删除安全闸"," 删除侧要求扫描根为真实路径 (根及其祖先链不含符号链接): 命中 (如 /tmp、/var 形态) 则 --yes 整批拒绝, 改写为真实路径形态 (如 /private/tmp/x) 即放行"," 设置 NO_COLOR (任意非空值) 或非 TTY 输出时自动降级为无颜色纯文本",` 默认配置位置 (平台自适应; 用了 --config 或 SWEEP_NM_CONFIG 时实际读的不是它): ${sanitizeLine(defaultConfigPath())}`," 查实际生效的路径: sweep-nm config","","退出码: 0 成功 (含预览、空结果、config、update 与 --help); 1 删除失败、跳过、整批拒绝或中止 / 无配置 --yes / 配置损坏 / 参数错误"].join(`
|
|
11
|
+
`)}import{homedir as homedir7}from"node:os";import{join as join5,resolve}from"node:path";import{createInterface}from"node:readline/promises";var WHITESPACE=/\s/;function expandHome(token,home){if(token==="~")return home;if(token.startsWith("~/")||token.startsWith("~\\"))return join5(home,token.slice(2));return token}function splitAnswer(answer){let items=[],current="",openQuote=null;for(let index=0;index<answer.length;index+=1){let char=answer[index];if(openQuote!==null){if(char===openQuote){openQuote=null;continue}current+=char;continue}if(char==='"'||char==="'"){if(answer.indexOf(char,index+1)!==-1){openQuote=char;continue}current+=char;continue}if(char===","||char===","||WHITESPACE.test(char)){if(current.length>0)items.push(current);current="";continue}current+=char}if(current.length>0)items.push(current);return items}function parsePathList(answer,fallback,home=homedir7()){if(answer===null)return[...fallback];let items=[...new Set(splitAnswer(answer).map((token)=>resolve(expandHome(token,home))))];return items.length>0?items:[...fallback]}function parseNameList(answer,fallback){if(answer===null)return[...fallback];let items=splitAnswer(answer);return items.length>0?items:[...fallback]}var hasPathSeparator=(name)=>name.includes("/")||name.includes("\\");async function checkRoots(roots,deps){let missing=[],notDir=[],symlinked=[];for(let root of roots){if(deps.rootExists!==void 0&&!await deps.rootExists(root)){missing.push(root);continue}let link=await deps.firstSymlinkOnRoot(root);if(link!==null){symlinked.push({root,link});continue}if(!await deps.rootIsDirectory(root))if(deps.rootExists!==void 0)notDir.push(root);else missing.push(root)}return{missing,notDir,symlinked}}async function runInit(deps){let{configPath,configExists,firstSymlinkOnTarget,writeFile,io}=deps,{color}=io,home=deps.home??homedir7();function cancelled(){return io.print("已取消, 未写入配置"),{state:"cancelled"}}async function checkConfigTarget(){if(deps.configIsDirectory!==void 0&&await deps.configIsDirectory(configPath))return io.print(` ${paint("✗","31",color)} 配置路径是既有目录, 无法写入文件: ${sanitizeLine(configPath)}; 请用 --config 指定文件路径或先移走该目录`),!1;let link=await firstSymlinkOnTarget(configPath);if(link!==null)return io.print(` ${paint("✗","31",color)} 配置路径锚点链上有符号链接: ${sanitizeLine(link)} (配置: ${sanitizeLine(configPath)}); 写入会跟随符号链接改写其目标, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`),!1;return!0}try{if(io.print(bannerLine("初始化向导",color)),!await checkConfigTarget())return cancelled();if(await configExists(configPath)){if(!await io.confirm(`配置已存在 (${sanitizeLine(configPath)}), 是否覆盖?`,!1))return{state:"declined-overwrite"}}io.print(neutralLine("首次使用, 先确定扫描范围",color));let roots=[];for(;;){let rootsAnswer=await io.ask("扫描根 (逗号或空白分隔多个)",`默认: ${sanitizeLine(shortenHome(home,home))}`);if(rootsAnswer===null)return cancelled();roots=parsePathList(rootsAnswer,[home],home);let{missing,notDir,symlinked}=await checkRoots(roots,deps);if(missing.length===0&¬Dir.length===0&&symlinked.length===0)break;for(let path of missing)io.print(` ${paint("✗","31",color)} 根不存在: ${sanitizeLine(path)}`);for(let path of notDir)io.print(` ${paint("✗","31",color)} 根不是目录: ${sanitizeLine(path)}`);for(let item of symlinked)io.print(` ${paint("✗","31",color)} 根锚点链上有符号链接: ${sanitizeLine(item.link)} (根: ${sanitizeLine(item.root)}); 删除侧要求真实路径, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`)}let excludeAnswer=await io.ask("排除名单 (目录名)",`回车采用默认名单 (${DEFAULT_EXCLUDE.length} 条)`);if(excludeAnswer===null)return cancelled();let exclude=parseNameList(excludeAnswer,[...DEFAULT_EXCLUDE]);for(let bad of exclude.filter(hasPathSeparator))io.print(` ${paint("!","33",color)} 排除名含路径分隔符, 不会命中任何目录 (请填写单级目录名): ${sanitizeLine(bad)}`);let includeAnswer=await io.ask("包含名单 (目录名, 可留空)","回车跳过");if(includeAnswer===null)return cancelled();let include=parseNameList(includeAnswer,[]);for(let bad of include.filter(hasPathSeparator))io.print(` ${paint("!","33",color)} 包含名含路径分隔符, 不会命中任何目录 (请填写单级目录名): ${sanitizeLine(bad)}`);io.print(neutralLine(`将写入 ${roots.length} 个扫描根 · 排除 ${exclude.length} 条 · 包含 ${include.length} 条`,color));let confirmDefault=!0;for(;;){if(!await io.confirm("确认写入?",confirmDefault))return cancelled();if(await checkConfigTarget())break;confirmDefault=!1}let config={roots,exclude,include},text=`${JSON.stringify(config,null,2)}
|
|
12
|
+
`;return await writeFile(configPath,text),io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath,home))} ${paint("✓","32",color)}`),io.print(""),io.print(text.trimEnd().split(`
|
|
13
|
+
`).map((line)=>` ${line}`).join(`
|
|
14
|
+
`)),io.print(""),{state:"written",config}}finally{io.close?.()}}function setStdinRef(shouldRef){let fn=shouldRef?process.stdin.ref:process.stdin.unref;if(typeof fn==="function")fn.call(process.stdin)}function createReadlineIO(color){let buffered=[],rl=null,ended=!1,aborted=!1,pending=null,onSigint=()=>{if(aborted=!0,buffered.length=0,process.stdout.isTTY===!0)process.stdout.write(`
|
|
15
|
+
`);rl?.close()};function ensure(){if(rl!==null)return rl;let created=createInterface({input:process.stdin,output:process.stdout});return created.on("line",(line)=>{if(pending===null){buffered.push(line);return}let resolve=pending;pending=null,setStdinRef(!1),resolve(line)}),created.on("close",()=>{if(ended=!0,pending===null)return;let resolve=pending;pending=null,setStdinRef(!1),resolve(null)}),created.on("SIGINT",onSigint),rl=created,created}function readLine(prompt){if(aborted)return Promise.resolve(null);if(ended){let bufferedLine=buffered.shift();if(bufferedLine===void 0)return Promise.resolve(null);return process.stdout.write(`${prompt}
|
|
16
|
+
`),Promise.resolve(bufferedLine)}let created=ensure();created.setPrompt(prompt),created.prompt();let ready=buffered.shift();if(ready!==void 0)return process.stdout.write(`
|
|
17
|
+
`),Promise.resolve(ready);return setStdinRef(!0),new Promise((resolve)=>{pending=resolve})}return{color,ask(question,hint){let prompt=hint===void 0?` ${question} `:` ${question} [${paint(hint,"2",color)}] `;return readLine(prompt)},async confirm(question,defaultYes){let mark=paint(defaultYes?"(Y/n)":"(y/N)","2",color),answer=await readLine(` ${question} ${mark} `);if(answer===null)return!1;let normalized=answer.trim().toLowerCase();if(normalized==="")return defaultYes;return normalized==="y"||normalized==="yes"},print(line){process.stdout.write(`${line}
|
|
18
|
+
`)},close(){if(rl===null)return;let current=rl;rl=null,current.off("SIGINT",onSigint),current.close(),setStdinRef(!1)}}}import{basename}from"node:path";var ABORTED_HINT="整批中止, 未执行删除";function toRenderEntry(entry){let notes=[];if(entry.kind==="suspect-install-tree")notes.push(`疑似安装树: ${entry.kindReason}`);if(entry.crossDevice!==void 0)notes.push(crossDeviceNote(entry.crossDevice));if(entry.bytes===void 0&&entry.unmeasuredReason!==void 0)notes.push(`体积统计失败: ${entry.unmeasuredReason}`);return{target:entry.target,bytes:entry.bytes,project:basename(entry.project)||entry.project,suspect:entry.kind==="suspect-install-tree",...notes.length>0?{note:notes.join(" ")}:{}}}function outcomeResult(entry){let{outcome}=entry;switch(outcome.kind){case"removed":case"missing":case"stale":return{ok:!0};case"failed":return{ok:!1,error:outcome.failure.message};case"skipped":return outcome.reason==="unmeasured"?{ok:!1}:{ok:!1,error:entry.skipNote};case"not-attempted":return{ok:!1,error:ABORTED_HINT};case"rejected":case"not-expected":return{ok:!1}}}var toExecuteEntry=(entry)=>({...toRenderEntry(entry),...outcomeResult(entry)});function abortedUnattemptedCount(report,summary=summarizeReport(report)){return summary.counts["not-attempted"]}var RUNTIME_NAME=typeof Bun>"u"?"node":"bun",runtimeLabel=`${RUNTIME_NAME} ${process.versions[RUNTIME_NAME]??"unknown"}`;function colorChannels(){let allowed=!process.env.NO_COLOR&&process.env.TERM?.toLowerCase()!=="dumb";return{stdout:allowed&&process.stdout.isTTY===!0,stderr:allowed&&process.stderr.isTTY===!0}}function interactive(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function print(line){process.stdout.write(`${line}
|
|
19
|
+
`)}function warn(line,stderrColor){let text=sanitizeOutputLine(line);process.stderr.write(stderrColor?`${paint("✗","31",stderrColor)} ${text}
|
|
20
|
+
`:`${text}
|
|
21
|
+
`)}function notice(line){process.stderr.write(`${sanitizeOutputLine(line)}
|
|
22
|
+
`)}var UPDATE_CONTROL_RE=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g;function sanitizeUpdateLines(text){return text.split(/\r?\n/).map((line)=>line.replace(UPDATE_CONTROL_RE,""))}function readCliVersion(){try{let raw=readFileSync5(new URL("../package.json",import.meta.url),"utf8"),parsed=JSON.parse(raw);return typeof parsed.version==="string"?parsed.version:"unknown"}catch{return"unknown"}}async function pathExists(path){try{return await lstat5(path),!0}catch{return!1}}async function rootIsDirectory(path){try{return(await lstat5(path)).isDirectory()}catch{return!1}}function runWizard(configPath,stdoutColor,home){return runInit({configPath,configExists:pathExists,configIsDirectory:rootIsDirectory,rootExists:pathExists,rootIsDirectory,firstSymlinkOnRoot,firstSymlinkOnTarget,async writeFile(path,text){await mkdir(dirname2(path),{recursive:!0}),await writeFile(path,text,"utf8")},home,io:createReadlineIO(stdoutColor)})}var SOURCE_LABELS={flag:"--config 指定",env:"环境变量 SWEEP_NM_CONFIG","platform-default":"平台默认"};async function reportConfig(resolved,stdoutColor){let exists=await pathExists(resolved.path);return print(bannerLine(`配置 · 来源: ${SOURCE_LABELS[resolved.source]}`,stdoutColor)),print(neutralLine(`配置路径: ${sanitizeLine(resolved.path)}`,stdoutColor)),print(neutralLine(`文件状态: ${exists?"存在":"不存在"}`,stdoutColor)),0}async function resolveConfig(resolved,stdoutColor,home){let loaded=await loadResolvedConfig(resolved);if(loaded.state==="ok")return{config:loaded.config,source:"file"};if(!interactive())return{config:{roots:[process.cwd()],exclude:[...DEFAULT_EXCLUDE],include:[]},source:"fallback"};let result=await runWizard(resolved.path,stdoutColor,home);if(result.state==="written"&&result.config!==void 0)return{config:result.config,source:"wizard"};return print("配置未写入, 本次未执行清理"),null}var BUILTIN_EXCLUDE_NAMES=new Set(DEFAULT_EXCLUDE);function collectNameNotes(excludeMatches,includeMatches,stderrColor){let notes=[],tty=process.stdout.isTTY===!0;for(let item of excludeMatches??[])if(item.hits===0){if(BUILTIN_EXCLUDE_NAMES.has(item.name))continue;warn(`排除名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`,stderrColor)}else if(tty)notes.push(`排除生效: ${item.name} (${item.hits} 处)`);let includes=includeMatches??[];for(let item of includes)if(item.hits===0)warn(`包含名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`,stderrColor);else if(tty)notes.push(`包含命中: ${item.name} (${item.hits} 处)`);if(includes.length>0&&includes.every((item)=>item.hits===0))warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)",stderrColor);return notes}async function sweep(config,options,colors,home){let sweeper=createSweeper({roots:config.roots,exclude:mergeNames(config.exclude,options.exclude),include:mergeNames(config.include,options.include),home,policy:{releaseSuspects:options.force}}),runtime=process.stdout.isTTY===!0?runtimeLabel:void 0,onProgress=(event)=>{if(event.kind==="warning")warn(event.warning.message,colors.stderr)},nameNotesOf=(plan)=>collectNameNotes(plan.nameMatches.exclude,plan.nameMatches.include,colors.stderr);if(!options.yes){let plan=await sweeper.plan({onProgress});return print(render({mode:"preview",roots:plan.roots,entries:plan.entries.map(toRenderEntry),color:colors.stdout,home,notes:nameNotesOf(plan),runtime,trailer:plan.trailer})),0}let report=await sweeper.run({onProgress});if(report.status==="rejected"){let rejected=report.validation?.rejected??[];warn(`整批拒绝: ${rejected.length} 个目标未通过安全闸, 未执行任何删除`,colors.stderr);for(let item of rejected)notice(` ${item.target} (${item.message})`);return 1}print(render({mode:"execute",roots:report.plan.roots,entries:report.entries.map(toExecuteEntry),color:colors.stdout,home,releasedBytes:report.releasedBytes,notes:nameNotesOf(report.plan),runtime,trailer:report.plan.trailer}));let summary=summarizeReport(report);if(report.removal?.aborted!==void 0)warn(`整批中止: ${report.removal.aborted.message}`,colors.stderr),notice(` 本轮未执行删除: ${abortedUnattemptedCount(report,summary)} 处`);return summary.failed===0&&summary.unprocessed===0&&!summary.aborted?0:1}async function main(){let colors=colorChannels(),parsed=parseArgs(process.argv.slice(2));if(!parsed.ok)return warn(`参数错误: ${parsed.message} (用 --help 查看用法)`,colors.stderr),1;let{options}=parsed;if(options.version)return print(readCliVersion()),0;if(options.help)return print(helpText(colors.stdout)),0;let home=homedir8(),activeConfigPath;try{if(options.command==="update")return await runSelfUpdate({binName:"sweep-nm",entryMetaUrl:import.meta.url,argv:options.updateArgs??[],io:{out:(text)=>{for(let line of sanitizeUpdateLines(text))print(line)},err:(text)=>{for(let line of sanitizeUpdateLines(text))if(line.startsWith(" "))notice(line);else warn(line,colors.stderr)}}});let resolvedPath=resolveConfigPath({flag:options.config,homedir:home});if(activeConfigPath=resolvedPath.path,options.command==="init"){if(!interactive())return warn("init 需要交互终端 (请在终端直接运行, 不要重定向或经管道)",colors.stderr),1;let result=await runWizard(resolvedPath.path,colors.stdout,home);if(result.state==="written")print(neutralLine("运行 sweep-nm 查看预览",colors.stdout));else if(result.state==="declined-overwrite")print("配置未变更");return 0}if(options.command==="config")return await reportConfig(resolvedPath,colors.stdout);let resolved=await resolveConfig(resolvedPath,colors.stdout,home);if(resolved===null)return 0;if(resolved.source==="fallback"){let roots=resolved.config.roots.join(", ");if(options.yes)return warn("拒绝执行: 当前无配置文件, --yes 不可用",colors.stderr),notice(` 将扫的根: ${roots}`),notice(" 先 sweep-nm init 生成配置, 或用 --config 指定配置文件"),1;notice(`未找到配置文件, 本次以当前目录为根: ${roots} (想固定此设置, 运行 sweep-nm init)`)}let freshConfig=resolved.source==="wizard";if(freshConfig&&options.yes)notice("首次配置已生成; 本轮先预览, 复核后可再运行 --yes 执行");return await sweep(resolved.config,freshConfig?{...options,yes:!1}:options,colors,home)}catch(error){let baseMessage=error instanceof Error?error.message:String(error),message=isSweepError(error)&&error.code==="INVALID_ARGUMENT"&&activeConfigPath!==void 0?`${baseMessage} (配置: ${activeConfigPath})`:baseMessage;return warn(message,colors.stderr),1}}process.exitCode=await main();
|