@iyowei/sweep-node-modules-cli 0.2.0 → 0.3.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 CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  **English** | [中文](README.zh-CN.md)
10
10
 
11
- A workspace-level cleaner for `node_modules`: scan several root directories in one pass, list every `node_modules` directory across your projects along with its size, and bulk-delete them after you confirm, reclaiming disk space.
11
+ A workspace-level cleaner for `node_modules`: scan several root directories in one pass, list every `node_modules` directory across your projects along with its size, and bulk-delete them after you confirm, reclaiming disk space. The CLI is a thin shell over the API package it is built on, [`@iyowei/sweep-node-modules`](https://www.npmjs.com/package/@iyowei/sweep-node-modules). For programmatic use from your own scripts and tools, reach for that package (its usage is documented there).
12
12
 
13
13
  > Where this sits: single-project cleaners handle "go into one project and clean its own artifacts"; this tool handles "stand at the workspace level and clean many projects in one pass". The two layers coexist; see [ADR 0001](../../docs/adrs/0001-workspace-level-cleaner.md).
14
14
 
@@ -17,7 +17,7 @@ A workspace-level cleaner for `node_modules`: scan several root directories in o
17
17
  - **Dual runtime** for the actual work: bun when available, node otherwise (identical behavior; bun starts faster).
18
18
  - Modern runtime APIs only: any recent bun; for node, a version that runs TypeScript natively (the same version floor applies to the source install and the package install; version snapshot and test records in [ADR 0006](../../docs/adrs/0006-dual-runtime-bun-first.md)).
19
19
  - Zero third-party runtime dependencies (built-in runtime capabilities only).
20
- - Runs on Windows, macOS, and Linux (see [ADR 0007](../../docs/adrs/0007-platform-portability.md)).
20
+ - Runs on macOS and Linux today; Windows launchers are shipped but not yet verified on a real Windows machine (see the evidence gap in [ADR 0007](../../docs/adrs/0007-platform-portability.md)).
21
21
 
22
22
  ## Installation
23
23
 
@@ -80,11 +80,9 @@ $bin = "$env:USERPROFILE\tools\sweep-node-modules\packages\sweep-node-modules-cl
80
80
 
81
81
  > Or skip the command line: add the `bin` directory to your user `Path` under System Properties → Environment Variables.
82
82
 
83
- - **Requires**: bun or node, either works (the launcher is a shell / cmd script run by the OS; it does not depend on node)
83
+ - **Requires**: bun or node, either works (the launcher is a shell / cmd script run by the OS; it does not depend on node); **node-only runtime**: the checkout must be built first, and building needs bun (`bun install && bun run build`) — node does not read the repo's path mappings, so an uncovered checkout cannot resolve the API package's artifacts
84
84
  - The most direct entry point; afterwards just run `sweep-nm` (on Windows via `packages\sweep-node-modules-cli\bin\sweep-nm.cmd`)
85
85
 
86
- > The tool also ships an API package, [`@iyowei/sweep-node-modules`](https://www.npmjs.com/package/@iyowei/sweep-node-modules), for use in your own programs or scripts (usage is documented in that package).
87
-
88
86
  ## Usage
89
87
 
90
88
  ```shell
@@ -94,7 +92,7 @@ sweep-nm
94
92
  # once the list checks out, delete for real
95
93
  sweep-nm --yes
96
94
 
97
- # also delete "suspected install trees" (package manager / version manager / editor extension trees; skipped by default)
95
+ # also delete "suspected install trees" (package manager / version manager / editor trees, hidden home-dir dirs, system-data-root names; skipped by default)
98
96
  sweep-nm --yes --force
99
97
 
100
98
  # add exclusions on the fly (repeatable)
@@ -108,20 +106,24 @@ sweep-nm config
108
106
 
109
107
  # init wizard: generate a config file interactively
110
108
  sweep-nm init
109
+
110
+ # full option list (also -h)
111
+ sweep-nm --help
111
112
  ```
112
113
 
113
114
  The end of the header line reports the runtime actually in use for this run (e.g. `bun 1.4.2`); it appears on interactive terminals only, keeping non-TTY output noise-free.
114
115
 
116
+ ## Exit codes
117
+
118
+ `0` means success (preview and empty results included); `1` means anything else (deletion failure / batch abort / unattempted targets / broken or missing config / bad arguments / a run refused for lack of a config).
119
+
115
120
  ## Configuration
116
121
 
117
122
  The config file lives at a platform-appropriate path: `%APPDATA%\sweep-node-modules\config.json` on Windows, `~/.config/sweep-node-modules/config.json` everywhere else. Override it with `--config` or the `SWEEP_NM_CONFIG` environment variable; `sweep-nm config` reports the path and file status actually in effect for the current run. **The write side requires real paths**: if the config path or any of its ancestors involves a symlink (system links such as `/tmp` and `/var` included), `sweep-nm init` refuses to write before touching disk and points at the link; follow the prompt to rewrite the path in real form (e.g. `/private/tmp/x`) and it goes through.
118
123
 
119
124
  ```json
120
125
  {
121
- "roots": [
122
- "/Users/iyowei/workspace/development",
123
- "/Users/iyowei/self/development"
124
- ],
126
+ "roots": ["/Users/you/workspace", "/Users/you/projects"],
125
127
  "exclude": ["my-kits"],
126
128
  "include": []
127
129
  }
@@ -129,7 +131,7 @@ The config file lives at a platform-appropriate path: `%APPDATA%\sweep-node-modu
129
131
 
130
132
  - `roots`: the scan roots, any number of them; duplicate or nested roots are deduplicated by real path. **The delete side requires real paths**: no symlink may sit on a root or any of its ancestors (system links such as `/tmp` and `/var` included); if one is hit, `--yes` rejects the whole batch and tells you to rewrite the path in real form (e.g. `/private/tmp/x`), which clears it. Scanning is not subject to this: a root that is itself a symlink still gets scanned.
131
133
  - `exclude`: the exclusion list; a name match at any directory level between a root and a `node_modules` skips it (more exclusions, less deletion: the safe direction). **Omit this field and a built-in default list applies** (package manager / version manager install trees, editor extension directories, system and application data roots; the list and its rationale are in the [design doc](../../docs/designs/config-and-initialization.md), section "Default exclusions"). These names never warn when they match nothing, since they vary by platform. Write the field explicitly (an empty array counts) and your own list takes over completely.
132
- - **Suspected install trees stay out of the delete batch by default**: targets that look like install trees (e.g. `~/.bun/install/global/node_modules`, `<version dir>/lib/node_modules`, editor extension directories) are flagged in the list as `疑似安装树: <reason>` (suspected install tree, plus the reason) and keep their `node_modules` suffix; `--yes` does not delete them (reported as a failure, with an explanation of the skip). Cleaning them takes an explicit `--force`, which releases only this batch of targets and relaxes no deletion guard.
134
+ - **Suspected install trees stay out of the delete batch by default**: targets that look like install trees (e.g. `~/.bun/install/global/node_modules`, `<version dir>/lib/node_modules`, editor extension directories, any `node_modules` under a hidden directory in the home dir, or under a system-data-root name such as `Library` / `.local` / `.config` / `.cache`) are flagged in the list as `疑似安装树: <reason>` (suspected install tree, plus the reason) and keep their `node_modules` suffix; `--yes` does not delete them (reported as a failure, with an explanation of the skip). Cleaning them takes an explicit `--force`, which releases only this batch of targets and relaxes no deletion guard.
133
135
  - **Cross-device targets stay out of the delete batch by default**: when a target and its owning root are not on the same filesystem (a cloud drive, network share, or container volume is mounted under the root and the entry lands on that volume), it is likewise not deleted; the list line notes the form at its end, `跨设备: 根与目标之间有挂载点` (a mount point lies between root and target) or `跨设备: 目标本体即挂载点` (the target itself is the mount point). For the first form, add that mount point as its own root and it cleans as usual; for the second, unmount the volume first; `--force` does not release this category.
134
136
  - `include`: the inclusion list (a whitelist); only matches are included, matched the same way as `exclude`. Omitted or empty means no filtering (more inclusions, more deletion); when a name matches both lists, `exclude` wins. A misspelled name would leave the result empty, so unmatched names warn on stderr.
135
137
  - `node_modules` and `.git` are always stripped from either list: the former is the tool's very target (under `exclude` it would rule out the only thing this tool does, under `include` it can never match), the latter is a directory the scan always skips. If stripping leaves `include` empty, that means no filtering, not "scan only `node_modules`".
@@ -145,9 +147,9 @@ Deletion is the only irreversible action this tool performs, and a whole discipl
145
147
 
146
148
  **Nothing happens by default.** Preview is the default mode, and deletion requires an explicit `--yes`. With no config file, `--yes` is hard-rejected and nothing is deleted. On the run right after the wizard writes a config, preview is forced even if `--yes` was passed. `--force` releases only suspected install trees; it relaxes no deletion guard.
147
149
 
148
- **What gets deleted is decided by both name and location.** Only directories named exactly `node_modules` are eligible, and only under the roots you declared; whether a target sits under a root is judged by path hierarchy rather than string prefixes, so `..` traversal and lookalike paths are rejected outright. Targets whose size cannot be measured are never deleted: keep rather than guess. Two categories are held back by default: suspected install trees (reinstalling them is painful or impossible; released only by an explicit `--force`) and cross-device targets that live on a different filesystem (`--force` does not release these either). A built-in default exclusion list (install-tree and system-data-root names from package managers, version managers, and editors) keeps the scan away from those trees.
150
+ **What gets deleted is decided by both name and location.** Only directories named exactly `node_modules` are eligible, and only under the roots you declared; whether a target sits under a root is judged by path hierarchy rather than string prefixes, so `..` traversal and lookalike paths are rejected outright. Targets whose size cannot be measured are never deleted: keep rather than guess. Two categories are held back by default: suspected install trees (reinstalling them is painful or impossible; released only by an explicit `--force`) and cross-device targets that live on a different filesystem (`--force` does not release these either). A built-in default exclusion list (install-tree and system-data-root names from package managers, version managers, and editors, plus data-root names such as `Library` / `.local` / `.config` / `.cache` / `.claude`) keeps the scan away from those trees.
149
151
 
150
- **One failure stops the whole batch, and every path is re-checked first.** If a single target fails a check, the entire batch is abandoned with zero deletions, rather than letting the rest through; right before removal, the path from the root down to the target's parent is re-verified component by component, and a swap mid-way stops the batch. If a configured root, or any of its ancestors, has been swapped for a symlink, the delete batch is rejected with rewrite instructions; system links such as `/tmp` and `/var` count too, and rewriting to the real path clears it.
152
+ **One failure stops the whole batch, and every path is re-checked first.** If a single target fails the pre-flight check, the entire batch is abandoned with zero deletions, rather than letting the rest through; right before removal, the path from the root down to the target's parent is re-verified component by component; a mid-way swap then stops the batch from dispatching further deletions (targets already dispatched run to completion and are reported as they are). If a configured root, or any of its ancestors, has been swapped for a symlink, the delete batch is rejected with rewrite instructions; system links such as `/tmp` and `/var` count too, and rewriting to the real path clears it.
151
153
 
152
154
  **Symlinks: the threshold follows reversibility.** For the same config, the read-only scan follows a symlinked root and still lists results, the irreversible delete rejects the batch, and `init` refuses to write a single byte through a link. The split is deliberate: a link's origin cannot be judged, so the irreversible step does not get the benefit of the doubt.
153
155
 
package/README.zh-CN.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  [English](README.md) | **中文**
10
10
 
11
- 工作区级 `node_modules` 清理工具: 一次扫描多个根目录, 跨项目列出各处 `node_modules` 与体积, 确认后批量删除, 回收磁盘空间。
11
+ 工作区级 `node_modules` 清理工具: 一次扫描多个根目录, 跨项目列出各处 `node_modules` 与体积, 确认后批量删除, 回收磁盘空间。本 CLI 是 API 包 [`@iyowei/sweep-node-modules`](https://www.npmjs.com/package/@iyowei/sweep-node-modules) 之上的一层薄壳。要在你自己的脚本与工具里做程序化调用, 请用该包 (用法见该包文档)。
12
12
 
13
13
  > 分层说明: 单项目清理工具管「进入某个项目, 清它自己的产物」; 本工具管「站在工作区层面, 一次清理很多个项目」。两者分层共存, 见 [ADR 0001](../../docs/adrs/0001-workspace-level-cleaner.md)。
14
14
 
@@ -17,7 +17,7 @@
17
17
  - 业务逻辑**双运行时**: 有 bun 走 bun, 否则 node (功能一致, bun 启动更快)。
18
18
  - 取最新一代运行时 API: bun 任意近期版本; node 需原生支持 TypeScript 直跑的版本 (源码方式与包方式取同一版本下限; 版本快照与实测记录见 [ADR 0006](../../docs/adrs/0006-dual-runtime-bun-first.md))。
19
19
  - 零第三方运行时依赖 (只用运行时内置能力)。
20
- - 平台: Windows / macOS / Linux 三平台均可运行 (见 [ADR 0007](../../docs/adrs/0007-platform-portability.md))。
20
+ - 平台: 当前实际验证于 macOS 与 Linux; Windows 启动器已随包分发, 但未经真机验证 (证据缺口见 [ADR 0007](../../docs/adrs/0007-platform-portability.md))。
21
21
 
22
22
  ## 安装
23
23
 
@@ -80,11 +80,9 @@ $bin = "$env:USERPROFILE\tools\sweep-node-modules\packages\sweep-node-modules-cl
80
80
 
81
81
  > 也可以不经命令行: 在「系统属性 → 环境变量」里把该 `bin` 目录加到用户变量 `Path` 中。
82
82
 
83
- - **需要**: bun 或 node 任一 (启动器是 shell / cmd 脚本, 由系统执行, 不依赖 node)
83
+ - **需要**: bun 或 node 任一 (启动器是 shell / cmd 脚本, 由系统执行, 不依赖 node); **仅 node 运行时**: 检出态须先构建一次, 且构建本身需要 bun (`bun install && bun run build`): node 不解析仓库内的路径映射, 未经构建的检出态会找不到 API 包产物
84
84
  - 特点: 入口最直接; 之后直接敲 `sweep-nm` (Windows 经 `packages\sweep-node-modules-cli\bin\sweep-nm.cmd`)
85
85
 
86
- > 本工具同时提供可编程 API 包 [`@iyowei/sweep-node-modules`](https://www.npmjs.com/package/@iyowei/sweep-node-modules), 供在程序或脚本中调用 (用法见该包文档)。
87
-
88
86
  ## 使用
89
87
 
90
88
  ```shell
@@ -94,7 +92,7 @@ sweep-nm
94
92
  # 复核无误后执行删除
95
93
  sweep-nm --yes
96
94
 
97
- # 连同「疑似安装树」一并删除 (包管理器 / 版本管理器 / 编辑器扩展等安装树, 默认跳过)
95
+ # 连同「疑似安装树」一并删除 (包管理器 / 版本管理器 / 编辑器扩展、家目录隐藏目录、系统数据根名; 默认跳过)
98
96
  sweep-nm --yes --force
99
97
 
100
98
  # 临时追加排除(可重复)
@@ -108,20 +106,24 @@ sweep-nm config
108
106
 
109
107
  # 初始化向导: 交互式生成配置文件
110
108
  sweep-nm init
109
+
110
+ # 完整选项表 (亦可 -h)
111
+ sweep-nm --help
111
112
  ```
112
113
 
113
114
  清单顶栏尾部会标注本次实际使用的运行时 (如 `bun 1.4.2`), 仅交互终端显示 (非 TTY 不增噪音)。
114
115
 
116
+ ## 退出码
117
+
118
+ `0` 表示成功 (含预览与空结果); 其余一律 `1` (删除失败 / 整批中止 / 未处理目标 / 配置损坏或不存在 / 参数错误 / 无配置下的执行拒绝)。
119
+
115
120
  ## 配置
116
121
 
117
122
  配置文件位置 (平台自适应): Windows 为 `%APPDATA%\sweep-node-modules\config.json`, 其余为 `~/.config/sweep-node-modules/config.json`; 可用 `--config` 或环境变量 `SWEEP_NM_CONFIG` 覆盖, 本次实际生效的路径与文件状态用 `sweep-nm config` 查看。**写入侧须为真实路径形态**: 配置路径及其祖先链有符号链接介入 (系统链接 `/tmp`、`/var` 也在内) 时, `sweep-nm init` 落盘前会拒写并给出链接定位, 按提示改写成真实路径形态 (如 `/private/tmp/x`) 即放行。
118
123
 
119
124
  ```json
120
125
  {
121
- "roots": [
122
- "/Users/iyowei/workspace/development",
123
- "/Users/iyowei/self/development"
124
- ],
126
+ "roots": ["/Users/you/workspace", "/Users/you/projects"],
125
127
  "exclude": ["my-kits"],
126
128
  "include": []
127
129
  }
@@ -129,7 +131,7 @@ sweep-nm init
129
131
 
130
132
  - `roots`: 扫描根目录, 任意多个; 重复或嵌套的根按真实路径去重。**删除侧须为真实路径形态**: 根及其祖先链不得有符号链接介入 (系统链接 `/tmp`、`/var` 也在内), 命中则 `--yes` 整批拒绝并按提示改写成真实路径 (如 `/private/tmp/x`) 即放行; 扫描侧不受此限 (根为符号链接照常扫描)。
131
133
  - `exclude`: 排除名单; 从根到 `node_modules` 的任意一级目录名命中即跳过 (多排除 = 少删, 安全方向)。**不写该字段时取内置默认名单** (包管理器 / 版本管理器的安装树、编辑器扩展目录、系统与应用数据根, 词表与理由见[设计文档](../../docs/designs/config-and-initialization.md)「默认排除名单」; 这批名字零命中不告警, 它们依平台而异); 显式写出该字段 (含写空数组) 即以你自己的名单为准。
132
- - **疑似安装树默认不进删除批**: 安装树形态的目标 (如 `~/.bun/install/global/node_modules`、`<版本目录>/lib/node_modules`、编辑器扩展目录) 在清单里带 `疑似安装树: <理由>` 标记且保留 `node_modules` 后缀, `--yes` 不删它们 (计失败并给跳过说明); 要清理须显式加 `--force`, 它只放行这一批目标, 不放宽删除安全闸。
134
+ - **疑似安装树默认不进删除批**: 安装树形态的目标 (如 `~/.bun/install/global/node_modules`、`<版本目录>/lib/node_modules`、编辑器扩展目录、家目录任意隐藏目录下的 `node_modules`, 或 `Library` / `.local` / `.config` / `.cache` 等系统数据根名下的) 在清单里带 `疑似安装树: <理由>` 标记且保留 `node_modules` 后缀, `--yes` 不删它们 (计失败并给跳过说明); 要清理须显式加 `--force`, 它只放行这一批目标, 不放宽删除安全闸。
133
135
  - **跨设备目标默认不进删除批**: 目标与所属根不在同一文件系统时 (根之下挂了云盘 / 网络盘 / 容器卷, 条目落在那一卷上) 同样不删, 清单行尾标注 `跨设备: 根与目标之间有挂载点` 或 `跨设备: 目标本体即挂载点`; 前者把该挂载点加进 `roots` 即可照常清理, 后者 (目标本体就是挂载点) 只能先卸载该卷; `--force` 不放行这一类。
134
136
  - `include`: 包含名单 (白名单); 命中才纳入, 口径与 `exclude` 同款; 缺省或空数组 = 不过滤 (多包含 = 多删); 与 `exclude` 同时命中时 `exclude` 优先。写错名字会让结果直接为空, 故未命中的名字会在 stderr 警示。
135
137
  - 两份名单里的 `node_modules` 与 `.git` 一律被剔除: 前者是本工具的目标 (列入排除等于排掉唯一目标, 列入包含则永久零命中), 后者是扫描恒定跳过的目录; 剔除后 `include` 为空数组 = 不过滤 (不是「只扫 node_modules」)。
@@ -145,9 +147,9 @@ sweep-nm init
145
147
 
146
148
  **默认什么都不做。** 预览是默认态, 删除要显式加 `--yes`; 没有配置文件时 `--yes` 被硬拒绝, 零删除; 向导刚写入配置的那一轮强制预览, 即便带了 `--yes` 也只预览。`--force` 只放行「疑似安装树」这一批目标, 不放宽任何删除安全闸。
147
149
 
148
- **删什么, 由名字与归属双重判定。** 只认名字恰为 `node_modules` 的目录, 且必须落在声明的扫描根之下; 归属按路径层级判定, 不是字符串前缀, 上溯与冒名路径一概拒绝。体积测不到的目标一律不删: 宁可留着, 不猜。两类目标默认拦下: 删了装不回来的「疑似安装树」 (要清理须显式加 `--force`), 与落在另一文件系统上的跨设备目标 (`--force` 同样不放行); 另有一份缺省排除名单 (包管理器 / 版本管理器 / 编辑器扩展与系统数据根的名字) 挨着就不扫。
150
+ **删什么, 由名字与归属双重判定。** 只认名字恰为 `node_modules` 的目录, 且必须落在声明的扫描根之下; 归属按路径层级判定, 不是字符串前缀, 上溯与冒名路径一概拒绝。体积测不到的目标一律不删: 宁可留着, 不猜。两类目标默认拦下: 删了装不回来的「疑似安装树」 (要清理须显式加 `--force`), 与落在另一文件系统上的跨设备目标 (`--force` 同样不放行); 另有一份缺省排除名单 (包管理器 / 版本管理器 / 编辑器扩展与 `Library` / `.local` / `.config` / `.cache` / `.claude` 等系统数据根的名字) 挨着就不扫。
149
151
 
150
- **一处不过, 整批不删; 动手前逐级复核。** 任一目标没通过检查, 整批一个都不删, 而不是逐条放行; 删除前自根至目标父目录逐级复核, 半路被掉包就整批停手。配置根或其祖先被换成符号链接时, 删除整批拒绝, 拒绝文案自带改写方向; 系统固有链接 (`/tmp`、`/var` 这类) 同样命中, 改写成真实路径形态即放行。
152
+ **一处不过, 整批不删; 动手前逐级复核。** 任一目标未通过预检, 整批一个都不删, 而不是逐条放行; 删除前自根至目标父目录逐级复核, 半路被掉包则停止派发新条 (已在飞的条目跑完并如实报告)。配置根或其祖先被换成符号链接时, 删除整批拒绝, 拒绝文案自带改写方向; 系统固有链接 (`/tmp`、`/var` 这类) 同样命中, 改写成真实路径形态即放行。
151
153
 
152
154
  **符号链接: 门槛跟着可逆性走。** 同一份配置, 只读的扫描面照常跟进 (根为符号链接照常出清单), 不可逆的删除面整批拒绝, 写入面 (`init` 落盘) 有链接介入就一个字节不落。这个分叉是有意的: 链接的来路判不了, 就不放行不可逆的那一步。
153
155
 
package/bin/sweep-nm.mjs CHANGED
@@ -13,7 +13,8 @@
13
13
  * 先试 cwd 再扫 PATH), 而本工具的调用现场恰是「在被扫目录里执行」, 目录内放一个同名
14
14
  * bun.exe / bun.com 即可顶替真实运行时进入执行链。故 win32 下先按 PATH 解析出绝对路径
15
15
  * (空条目与相对条目都会把解析引回当前目录, 一并跳过) 再探测与执行, 解析面与执行面都不再
16
- * 触发任何搜索序; POSIX 侧 Node 走 execvp 只搜 PATH, 维持裸名原样。
16
+ * 触发任何搜索序; POSIX 侧同法收紧 (空与相对条目在 POSIX 下同样意为当前目录), 并保持
17
+ * execvp「首候选不可执行时继续搜索」的语义 (逐候选探测)。
17
18
  *
18
19
  * 产物自证 (审计项「发行面 dist/cli.js 与源码和提交无身份绑定」的运行时防线): 决定跑
19
20
  * dist/cli.js 之前必须与随附的 dist/manifest.json 对账 (形状版本受支持, 且清单记的 cliSha256
@@ -28,7 +29,7 @@
28
29
  import { spawnSync } from 'node:child_process';
29
30
  import { createHash } from 'node:crypto';
30
31
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
31
- import { dirname, join, win32 } from 'node:path';
32
+ import { dirname, join, posix, win32 } from 'node:path';
32
33
  import { fileURLToPath } from 'node:url';
33
34
 
34
35
  /** 产物与清单的文件名 (与 scripts/release-artifact.ts 的 CLI_FILE / MANIFEST_FILE 同值) */
@@ -77,10 +78,28 @@ export const resolveWin32Executable = (name, pathEnv, fileProbe) => {
77
78
  return null;
78
79
  };
79
80
 
81
+ /**
82
+ * 在 PATH 中解析命令的全部候选绝对路径 (POSIX 语义, 保持 PATH 顺序), 跳过空条目与相对
83
+ * 条目 (两者在 POSIX 下都按当前目录解析, 属本工具要摘掉的解析面; 与 win32 分支同一理由,
84
+ * 见文件头「运行时解析防劫持」)。返回数组而非首命中: 同名文件可能不可执行, execvp 在
85
+ * 该情形会继续搜索, 候选交由调用方逐个探测以保持同一语义。注入 pathEnv / fileProbe 供
86
+ * 测试在任意宿主上覆盖本函数。
87
+ */
88
+ export const resolvePosixExecutables = (name, pathEnv, fileProbe) => {
89
+ const found = [];
90
+ for (const dir of pathEnv.split(':')) {
91
+ if (dir === '' || !dir.startsWith('/')) continue;
92
+ const candidate = posix.join(dir, name);
93
+ if (fileProbe(candidate)) found.push(candidate);
94
+ }
95
+ return found;
96
+ };
97
+
80
98
  /**
81
99
  * 挑选运行时: Bun 优先, 其次 Node; 皆无则 null (由调用处报错退出)。
82
- * win32 下先按 PATH 解析绝对路径再探测 (理由见文件头「运行时解析防劫持」), POSIX 下维持
83
- * 裸名 (execvp 只搜 PATH); 各参数显式传入供测试注入, 生产调用不传。
100
+ * 两个平台都先按 PATH 解析绝对路径再探测 (理由见文件头「运行时解析防劫持」): win32 取
101
+ * 首个解析命中, POSIX 按 PATH 顺序逐个候选探测 (保持 execvp 的继续搜索语义); 各参数
102
+ * 显式传入供测试注入, 生产调用不传。
84
103
  */
85
104
  export const pickRuntime = ({
86
105
  platform = process.platform,
@@ -89,11 +108,14 @@ export const pickRuntime = ({
89
108
  probe = available,
90
109
  } = {}) => {
91
110
  for (const name of ['bun', 'node']) {
92
- const resolved =
93
- platform === 'win32'
94
- ? resolveWin32Executable(name, pathEnv, fileProbe)
95
- : name;
96
- if (resolved !== null && probe(resolved)) return resolved;
111
+ if (platform === 'win32') {
112
+ const resolved = resolveWin32Executable(name, pathEnv, fileProbe);
113
+ if (resolved !== null && probe(resolved)) return resolved;
114
+ continue;
115
+ }
116
+ for (const candidate of resolvePosixExecutables(name, pathEnv, fileProbe)) {
117
+ if (probe(candidate)) return candidate;
118
+ }
97
119
  }
98
120
  return null;
99
121
  };
@@ -163,7 +185,7 @@ const main = () => {
163
185
  // 处置指引按宿主分流: 仓库检出态 (有源码) 可走源码入口或重构建; 包态 (无源码) 只能重装本包
164
186
  const advice = existsSync(join(root, 'src', 'cli.ts'))
165
187
  ? '用源码入口跑 (bun src/cli.ts 或 node src/cli.ts), 或重新构建 (bun run build)'
166
- : '重装本包换一份完好分发 (npm install -g @iyowei/sweep-node-modules); 重装无效则说明该版本包有缺陷, 需发布者重新构建后再发';
188
+ : '重装本包换一份完好分发 (npm install -g @iyowei/sweep-node-modules-cli); 重装无效则说明该版本包有缺陷, 需发布者重新构建后再发';
167
189
  process.stderr.write(
168
190
  `sweep-nm: ${problem}, 已拒绝执行该产物 (无法证明它与构建清单同源)。\n` +
169
191
  ` 处置: ${advice}。\n`,
package/dist/cli.js CHANGED
@@ -1,15 +1,34 @@
1
1
  // src/cli.ts
2
- import { lstat as lstat3, mkdir } from "node:fs/promises";
2
+ import { lstat as lstat3, mkdir, writeFile } from "node:fs/promises";
3
3
  import { homedir as homedir6 } from "node:os";
4
4
  import { basename, dirname } from "node:path";
5
-
6
- // ../sweep-node-modules/src/classify.ts
7
- import { homedir as homedir3 } from "node:os";
8
-
9
5
  // ../sweep-node-modules/src/config.ts
10
6
  import { readFile } from "node:fs/promises";
11
7
  import { homedir } from "node:os";
12
8
  import { posix, win32 } from "node:path";
9
+
10
+ // ../sweep-node-modules/src/errors.ts
11
+ var SWEEP_ERROR_CODES = new Set([
12
+ "CONFIG_READ_FAILED",
13
+ "CONFIG_CORRUPT_JSON",
14
+ "CONFIG_CORRUPT_SHAPE",
15
+ "CONFIG_ABSENT",
16
+ "INVALID_ARGUMENT",
17
+ "CANCELLED"
18
+ ]);
19
+
20
+ class SweepError extends Error {
21
+ name = "SweepError";
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
13
32
  var DEFAULT_EXCLUDE = [
14
33
  ".bun",
15
34
  ".npm",
@@ -66,20 +85,29 @@ function describeActual(value) {
66
85
  function fieldError(container, field, optional) {
67
86
  const value = container[field];
68
87
  if (value === undefined) {
69
- return optional ? null : `${field} 应为字符串数组 (实际: 缺失)`;
88
+ return optional ? null : { field, message: `${field} 应为字符串数组 (实际: 缺失)` };
70
89
  }
71
90
  if (!Array.isArray(value)) {
72
- return `${field} 应为字符串数组 (实际: ${describeActual(value)})`;
91
+ return {
92
+ field,
93
+ message: `${field} 应为字符串数组 (实际: ${describeActual(value)})`
94
+ };
73
95
  }
74
96
  const badIndex = value.findIndex((item) => typeof item !== "string");
75
97
  if (badIndex !== -1) {
76
- return `${field} 第 ${badIndex + 1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`;
98
+ return {
99
+ field,
100
+ message: `${field} 第 ${badIndex + 1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`
101
+ };
77
102
  }
78
103
  return null;
79
104
  }
80
105
  function shapeError(value) {
81
106
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
82
- return `顶层应为对象 (实际: ${describeActual(value)})`;
107
+ return {
108
+ field: "顶层",
109
+ message: `顶层应为对象 (实际: ${describeActual(value)})`
110
+ };
83
111
  }
84
112
  const candidate = value;
85
113
  const rootsError = fieldError(candidate, "roots", false);
@@ -97,17 +125,17 @@ async function loadConfig(path) {
97
125
  } catch (error) {
98
126
  if (error.code === "ENOENT")
99
127
  return { state: "absent" };
100
- throw new Error(`配置读取失败 (${path}): ${error.message}`);
128
+ throw new SweepError("CONFIG_READ_FAILED", `配置读取失败 (${path}): ${error.message}`, { path, errno: error.code });
101
129
  }
102
130
  let data;
103
131
  try {
104
132
  data = JSON.parse(text);
105
133
  } catch (error) {
106
- throw new Error(`配置损坏 (${path}): JSON 解析失败: ${error.message}`);
134
+ throw new SweepError("CONFIG_CORRUPT_JSON", `配置损坏 (${path}): JSON 解析失败: ${error.message}`, { path });
107
135
  }
108
- const error = shapeError(data);
109
- if (error !== null) {
110
- throw new Error(`配置损坏 (${path}): ${error}`);
136
+ const problem = shapeError(data);
137
+ if (problem !== null) {
138
+ throw new SweepError("CONFIG_CORRUPT_SHAPE", `配置损坏 (${path}): ${problem.message}`, { path, field: problem.field });
111
139
  }
112
140
  const raw = data;
113
141
  return {
@@ -122,41 +150,35 @@ async function loadConfig(path) {
122
150
  async function loadResolvedConfig(resolved) {
123
151
  const result = await loadConfig(resolved.path);
124
152
  if (result.state === "absent" && resolved.source !== "platform-default") {
125
- throw new Error(`配置不存在 (${resolved.path}), 请检查路径`);
153
+ throw new SweepError("CONFIG_ABSENT", `配置不存在 (${resolved.path}), 请检查路径`, { path: resolved.path, source: resolved.source });
126
154
  }
127
155
  return result;
128
156
  }
129
157
  function mergeNames(configNames, cliNames) {
130
158
  return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
131
159
  }
132
-
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
+ };
133
178
  // ../sweep-node-modules/src/guard.ts
134
179
  import { lstat, realpath, stat } from "node:fs/promises";
135
180
  import { homedir as homedir2 } from "node:os";
136
181
  import { posix as posix2, win32 as win322 } from "node:path";
137
-
138
- // ../sweep-node-modules/src/errors.ts
139
- var SWEEP_ERROR_CODES = new Set([
140
- "CONFIG_READ_FAILED",
141
- "CONFIG_CORRUPT_JSON",
142
- "CONFIG_CORRUPT_SHAPE",
143
- "CONFIG_ABSENT",
144
- "INVALID_ARGUMENT",
145
- "CANCELLED"
146
- ]);
147
-
148
- class SweepError extends Error {
149
- name = "SweepError";
150
- code;
151
- details;
152
- constructor(code, message, details) {
153
- super(message);
154
- this.code = code;
155
- this.details = details;
156
- }
157
- }
158
-
159
- // ../sweep-node-modules/src/guard.ts
160
182
  var POSIX_STYLE = {
161
183
  name: "posix",
162
184
  ops: posix2,
@@ -394,8 +416,8 @@ async function findCrossDeviceTargets(targets, options) {
394
416
  function crossDeviceIndex(entries) {
395
417
  return new Map(entries.map((entry) => [entry.target, entry.kind]));
396
418
  }
397
-
398
419
  // ../sweep-node-modules/src/classify.ts
420
+ import { homedir as homedir3 } from "node:os";
399
421
  var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
400
422
  var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
401
423
  function classifyTarget(target, options = {}) {
@@ -427,6 +449,114 @@ function classifyTarget(target, options = {}) {
427
449
  }
428
450
  return { kind: "project" };
429
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
+
430
560
  // ../sweep-node-modules/src/delete.ts
431
561
  import { lstat as lstat2, realpath as realpath2, rm } from "node:fs/promises";
432
562
  import { isAbsolute, join, relative, sep } from "node:path";
@@ -504,105 +634,185 @@ async function reviewComponents(chain) {
504
634
  }
505
635
  return null;
506
636
  }
637
+ var REMOVAL_CONCURRENCY = 4;
507
638
  async function removeTargets(targets, options) {
508
- const result = { removed: [], missing: [], failed: [] };
509
639
  const roots = options?.roots ?? [];
510
640
  const signal = options?.signal;
511
641
  const emit = options?.onProgress;
512
- for (const target of targets) {
513
- if (signal?.aborted) {
514
- throw new SweepError("CANCELLED", "删除在条目间检查点被取消", {
515
- phase: "remove",
516
- partial: result
517
- });
518
- }
519
- const root = roots.find((candidate) => isUnder(candidate.real, target));
520
- if (root === undefined) {
521
- result.aborted = {
522
- target,
523
- code: "REVIEW_NOT_UNDER_ANY_ROOT",
524
- message: `安全复核失败 (目标不在任何 roots 之下): ${target}`,
525
- path: target
526
- };
527
- emit?.({ kind: "aborted", aborted: result.aborted });
528
- break;
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);
529
668
  }
530
- if (await isSymlinkHead(root.configured)) {
531
- result.aborted = {
532
- target,
533
- code: "REVIEW_HEAD_SYMLINK",
534
- message: `安全复核失败 (根被替换为符号链接): ${root.configured}`,
535
- path: root.configured
536
- };
537
- emit?.({ kind: "aborted", aborted: result.aborted });
538
- break;
669
+ if (active === 0 && resolveDrained !== null) {
670
+ const resolve = resolveDrained;
671
+ resolveDrained = null;
672
+ resolve();
539
673
  }
540
- const finding = await reviewComponents(componentChain(root.real, target));
541
- if (finding !== null) {
542
- if (finding.kind === "vanished") {
543
- const vanished = {
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 = {
544
687
  target,
545
- code: "REVIEW_COMPONENT_VANISHED",
546
- message: describeVanishedReview(target, finding.path),
547
- partialRisk: false
688
+ code: "REVIEW_NOT_UNDER_ANY_ROOT",
689
+ message: `安全复核失败 (目标不在任何 roots 之下): ${target}`,
690
+ path: target
548
691
  };
549
- result.failed.push(vanished);
550
- emit?.({ kind: "failed", failure: vanished });
551
- continue;
692
+ recordAbort(index, info);
693
+ slots[index] = { kind: "aborted" };
694
+ emit?.({ kind: "aborted", aborted: info });
695
+ return;
552
696
  }
553
- if (finding.kind === "unsafe") {
554
- result.aborted = {
697
+ if (await isSymlinkHead(root.configured)) {
698
+ const info = {
555
699
  target,
556
- code: "REVIEW_COMPONENT_REPLACED",
557
- message: `安全复核失败 (路径组件被替换): ${finding.path}`,
558
- path: finding.path
700
+ code: "REVIEW_HEAD_SYMLINK",
701
+ message: `安全复核失败 (根被替换为符号链接): ${root.configured}`,
702
+ path: root.configured
559
703
  };
560
- emit?.({ kind: "aborted", aborted: result.aborted });
561
- break;
704
+ recordAbort(index, info);
705
+ slots[index] = { kind: "aborted" };
706
+ emit?.({ kind: "aborted", aborted: info });
707
+ return;
562
708
  }
563
- const unverified = {
564
- target,
565
- code: "REVIEW_UNVERIFIED",
566
- message: describeReviewError(target, finding.path, finding.error),
567
- partialRisk: false
568
- };
569
- result.failed.push(unverified);
570
- emit?.({ kind: "failed", failure: unverified });
571
- continue;
572
- }
573
- try {
574
- await rm(target, { recursive: true, force: false });
575
- result.removed.push(target);
576
- emit?.({ kind: "removed", target });
577
- } catch (error) {
578
- if (error?.code === "ENOENT") {
579
- const state = await checkGone(target);
580
- if (state === "gone") {
581
- result.missing.push(target);
582
- emit?.({ kind: "missing", target });
583
- continue;
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;
584
765
  }
585
- const survivor = {
766
+ const failure = {
586
767
  target,
587
- code: "REMOVE_ENOENT_SURVIVOR",
588
- message: describeSurvivor(target, state),
768
+ code: "REMOVE_FAILED",
769
+ errno: error?.code,
770
+ message: describeRemovalError(target, error),
589
771
  partialRisk: true
590
772
  };
591
- result.failed.push(survivor);
592
- emit?.({ kind: "failed", failure: survivor });
593
- continue;
773
+ slots[index] = { kind: "failed", failure };
774
+ emit?.({ kind: "failed", failure });
594
775
  }
595
- const failure = {
596
- target,
597
- code: "REMOVE_FAILED",
598
- errno: error?.code,
599
- message: describeRemovalError(target, error),
600
- partialRisk: true
601
- };
602
- result.failed.push(failure);
603
- emit?.({ kind: "failed", failure });
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();
604
784
  }
605
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
+ }
606
816
  return result;
607
817
  }
608
818
  async function toTrustRoots(roots) {
@@ -624,19 +834,7 @@ function splitStaleRejections(rejected, staleTargets) {
624
834
  }
625
835
  return { rejected: rest, stale };
626
836
  }
627
- // ../sweep-node-modules/src/runtime.ts
628
- import { readFile as readFile2, writeFile } from "node:fs/promises";
629
- var isBun = typeof Bun !== "undefined";
630
- var versions = process.versions;
631
- var runtimeName = isBun ? "bun" : "node";
632
- var runtimeLabel = `${runtimeName} ${versions[runtimeName] ?? "unknown"}`;
633
- async function writeTextFile(path, text) {
634
- if (isBun) {
635
- await Bun.write(path, text);
636
- return;
637
- }
638
- await writeFile(path, text, "utf8");
639
- }
837
+
640
838
  // ../sweep-node-modules/src/scan-parallel.ts
641
839
  import { readdir, realpath as realpath3, stat as stat2 } from "node:fs/promises";
642
840
  import { join as join2 } from "node:path";
@@ -1012,6 +1210,11 @@ function createDuSizer(bin = findDu()) {
1012
1210
  const failures = new Map;
1013
1211
  let intact = true;
1014
1212
  if (safeTargets.length > 0) {
1213
+ if (options?.signal?.aborted) {
1214
+ throw new SweepError("CANCELLED", "体积统计在批量统计前被取消", {
1215
+ phase: "measure"
1216
+ });
1217
+ }
1015
1218
  const { stdout, stderr } = await runDu(bin, safeTargets);
1016
1219
  const assessment = assessDuOutput(stdout, safeTargets);
1017
1220
  intact = assessment.intact;
@@ -1213,112 +1416,8 @@ function createJsSizer() {
1213
1416
  function createSizer() {
1214
1417
  return findDu() !== null ? createDuSizer() : createJsSizer();
1215
1418
  }
1216
- // ../sweep-node-modules/src/skip.ts
1217
- var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
1218
- var CROSS_DEVICE_NOTES = {
1219
- "on-path": "跨设备: 根与目标之间有挂载点",
1220
- "target-itself": "跨设备: 目标本体即挂载点"
1221
- };
1222
- var CROSS_DEVICE_HINTS = {
1223
- "on-path": "已跳过 (把该挂载点声明为独立根即可清理)",
1224
- "target-itself": "已跳过 (挂载点无法删除, 需先卸载该卷)"
1225
- };
1226
- var CROSS_DEVICE_TRAILER_ACTIONS = {
1227
- "on-path": "把根与目标之间的挂载点声明为独立根即可清理",
1228
- "target-itself": "目标本体即挂载点, 需先卸载该卷"
1229
- };
1230
- function crossDeviceNote(kind) {
1231
- return CROSS_DEVICE_NOTES[kind];
1232
- }
1233
- function skipReasonOf(entry, crossDevice, policy) {
1234
- const deviceKind = crossDevice.get(entry.target);
1235
- if (deviceKind !== undefined) {
1236
- return deviceKind === "on-path" ? "cross-device:on-path" : "cross-device:target-itself";
1237
- }
1238
- if (entry.bytes === undefined)
1239
- return "unmeasured";
1240
- if (entry.suspect && !policy.releaseSuspects)
1241
- return "suspect-install-tree";
1242
- return null;
1243
- }
1244
- function skipsBatch(entry, crossDevice, policy) {
1245
- return skipReasonOf(entry, crossDevice, policy) !== null;
1246
- }
1247
- function deletionBatch(entries, crossDevice, policy) {
1248
- return entries.filter((entry) => !skipsBatch(entry, crossDevice, policy)).map((entry) => entry.target);
1249
- }
1250
- function noteOf(entry, reason) {
1251
- if (reason === "suspect-install-tree")
1252
- return SUSPECT_HINT;
1253
- if (reason === "unmeasured") {
1254
- return `体积统计失败: ${entry.unmeasuredReason ?? "原因未知"}`;
1255
- }
1256
- return CROSS_DEVICE_HINTS[reason === "cross-device:on-path" ? "on-path" : "target-itself"];
1257
- }
1258
- function collectSkips(entries, crossDevice, policy) {
1259
- const suspectSkipped = policy.releaseSuspects ? [] : entries.filter((entry) => entry.suspect);
1260
- const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
1261
- const trailer = [
1262
- ...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
1263
- ...["on-path", "target-itself"].flatMap((kind) => {
1264
- const count = deviceSkipped.filter((entry) => crossDevice.get(entry.target) === kind).length;
1265
- return count === 0 ? [] : [
1266
- `跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`
1267
- ];
1268
- })
1269
- ];
1270
- const hints = new Map;
1271
- for (const entry of suspectSkipped) {
1272
- if (entry.bytes !== undefined)
1273
- hints.set(entry.target, SUSPECT_HINT);
1274
- }
1275
- for (const entry of deviceSkipped) {
1276
- const kind = crossDevice.get(entry.target);
1277
- if (entry.bytes !== undefined && kind !== undefined) {
1278
- hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
1279
- }
1280
- }
1281
- const book = [];
1282
- for (const entry of entries) {
1283
- const reason = skipReasonOf(entry, crossDevice, policy);
1284
- if (reason === null)
1285
- continue;
1286
- book.push({ target: entry.target, reason, note: noteOf(entry, reason) });
1287
- }
1288
- return { entries: book, trailer, hints };
1289
- }
1290
- // ../sweep-node-modules/src/summary.ts
1291
- var SUCCESS_KINDS = new Set([
1292
- "removed",
1293
- "missing",
1294
- "stale"
1295
- ]);
1296
- function isSuccessOutcome(outcome) {
1297
- return SUCCESS_KINDS.has(outcome.kind);
1298
- }
1299
- function summarizeReport(report) {
1300
- const counts = {
1301
- removed: 0,
1302
- missing: 0,
1303
- stale: 0,
1304
- failed: 0,
1305
- rejected: 0,
1306
- "not-attempted": 0,
1307
- "not-expected": 0,
1308
- skipped: 0
1309
- };
1310
- for (const entry of report.entries)
1311
- counts[entry.outcome.kind] += 1;
1312
- return {
1313
- counts,
1314
- succeeded: counts.removed + counts.missing + counts.stale,
1315
- unprocessed: counts.skipped + counts.rejected + counts["not-attempted"] + counts["not-expected"],
1316
- failed: counts.failed,
1317
- aborted: report.removal?.aborted !== undefined
1318
- };
1319
- }
1419
+
1320
1420
  // ../sweep-node-modules/src/sweep.ts
1321
- import { homedir as homedir4 } from "node:os";
1322
1421
  var invalidArgument = (field, message) => new SweepError("INVALID_ARGUMENT", `${message} (字段: ${field})`, { field });
1323
1422
  function assertNameArray(value, field, required) {
1324
1423
  if (value === undefined) {
@@ -1610,18 +1709,6 @@ var bannerLine = (suffix, color) => paint(`${BAR_BLOCK} ${BANNER} ${suffix}`, "
1610
1709
  var neutralLine = (text, color) => ` ${paint(`${NEUTRAL_BLOCK} ${text}`, "2", color)}`;
1611
1710
  var TIER_BIG = 512 * 1024 ** 2;
1612
1711
  var TIER_MID = 100 * 1024 ** 2;
1613
- function formatBytes(bytes) {
1614
- if (bytes < 1024)
1615
- return `${Math.round(bytes)} B`;
1616
- const units = ["KB", "MB", "GB", "TB"];
1617
- let value = bytes;
1618
- let index = -1;
1619
- do {
1620
- value /= 1024;
1621
- index += 1;
1622
- } while (value >= 1024 && index < units.length - 1);
1623
- return `${Math.round(value * 10) / 10} ${units[index]}`;
1624
- }
1625
1712
  function render(options) {
1626
1713
  const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
1627
1714
  const style = pathStyle ?? PLATFORM_STYLE;
@@ -1707,11 +1794,6 @@ function displayPath(target, style, home, keepSuffix = false) {
1707
1794
  const dir = keepSuffix || !fold3(target, style).endsWith(fold3(suffix, style)) ? target : target.slice(0, -suffix.length);
1708
1795
  return shortenPath(dir, style, home);
1709
1796
  }
1710
- var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
1711
- var sanitizeOutputLine = (text) => {
1712
- const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
1713
- return `${indent}${sanitizeLine(text)}`;
1714
- };
1715
1797
  var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
1716
1798
  var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
1717
1799
  function displayWidth(text) {
@@ -1745,6 +1827,7 @@ function helpText(color) {
1745
1827
  row("sweep-nm config", "查看实际生效的配置: 来源 + 路径 + 文件状态"),
1746
1828
  row("sweep-nm init", "初始化向导: 交互生成配置文件"),
1747
1829
  row("sweep-nm --help", "帮助"),
1830
+ row("sweep-nm -h", "--help 的别名"),
1748
1831
  "",
1749
1832
  "说明:",
1750
1833
  " --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过",
@@ -2022,6 +2105,8 @@ function parseArgs(argv) {
2022
2105
  options.command = only;
2023
2106
  return { ok: true, options };
2024
2107
  }
2108
+ var RUNTIME_NAME = typeof Bun === "undefined" ? "node" : "bun";
2109
+ var runtimeLabel = `${RUNTIME_NAME} ${process.versions[RUNTIME_NAME] ?? "unknown"}`;
2025
2110
  function colorEnabled() {
2026
2111
  return process.stdout.isTTY === true && !process.env.NO_COLOR;
2027
2112
  }
@@ -2058,7 +2143,7 @@ function runWizard(configPath, color) {
2058
2143
  firstSymlinkOnTarget,
2059
2144
  async writeFile(path, text) {
2060
2145
  await mkdir(dirname(path), { recursive: true });
2061
- await writeTextFile(path, text);
2146
+ await writeFile(path, text, "utf8");
2062
2147
  },
2063
2148
  io: createReadlineIO(color)
2064
2149
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "commit": "51697b26b3f7ee20202b75989613c7b9191201eb",
3
+ "commit": "3218787a30a10755c1440ffc9954d4d253506da0",
4
4
  "dirty": false,
5
- "cliSha256": "0b05cb4ddae1d28b646c0b9aa3271ae662abdddbe5014df3bacaaf8a81a0e32d",
6
- "builtAt": "2026-09-29T09:48:56.737Z"
5
+ "cliSha256": "a1c13d3aa735d1f4cab2cd7475d88e7f7fa6acd662fa08466c18f690e34c0a48",
6
+ "builtAt": "2026-09-30T07:09:11.780Z"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iyowei/sweep-node-modules-cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "CLI to find and delete node_modules across projects: scan multiple workspace roots (monorepo friendly), bulk-remove them to free up disk space, preview first and delete after confirmation. 工作区级 node_modules 批量清理工具。",
5
5
  "keywords": [
6
6
  "cli",
@@ -57,7 +57,7 @@
57
57
  "registry": "https://registry.npmjs.org/"
58
58
  },
59
59
  "devDependencies": {
60
- "@iyowei/sweep-node-modules": "*"
60
+ "@iyowei/sweep-node-modules": "0.5.1"
61
61
  },
62
62
  "scripts": {
63
63
  "build": "bun build src/cli.ts --target=node --outfile=dist/cli.js && bun scripts/write-dist-manifest.ts",