dsh-cookie-cleaner 0.6.4 → 0.7.1

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/src/cli.js CHANGED
@@ -1,236 +1,281 @@
1
- #!/usr/bin/env node
2
- /**
3
- * dsh-cookie-cleaner — 独立清理脚本(可在 npm 全局/任意 shell 下直接执行)。
4
- *
5
- * 为什么独立成脚本:cookie 库在客户端运行期间被 Chromium 独占(实测写入必须等退出),
6
- * 所以清理只能发生在「客户端已完全退出」的时刻——那时宿主插件根本不存在,
7
- * 执行体必须是这个包里的脚本。
8
- *
9
- * 包是 ESM(宿主装载与 npm bin 都走 ESM),core 只有一份实现,两边共用。
10
- * 输出语言:--lang > DSH_COOKIE_LANG/DSH_LANG > LC_ALL/LANG > 系统 locale > zh。
11
- */
12
- import os from 'node:os'
13
- import path from 'node:path'
14
- import process from 'node:process'
15
- import { readFileSync } from 'node:fs'
16
- import { fileURLToPath } from 'node:url'
17
- import * as core from './core.js'
18
- import { LANGS, detectLang, normalize, translator } from './i18n.js'
19
- import { offlineCheck } from './patch-guard.js'
20
- import { renderPlanBlock } from './patch-model.js'
21
- import { findOverrideRow, readPatchFile } from './patch-read.js'
22
- import { cookieLiveText, patchReportText } from './report.js'
23
-
24
- const HERE = path.dirname(fileURLToPath(import.meta.url))
25
-
26
- function usage() {
27
- return `dsh-cookie-cleaner — 清理 DSH 客户端留在 cookie 库里的本地登录凭据(dsh-auth-*)
28
-
29
- 用法(务必先${core.exitInstruction()}):
30
- dsh-cookie-cleaner 查看现状:库在哪、多少条 dsh-auth-*、多少已过期
31
- dsh-cookie-cleaner --clean 删除回环域(127.0.0.1/localhost/[::1])下全部 dsh-auth-*
32
- dsh-cookie-cleaner --clean --expired-only 保守档:只删已过期的
33
- dsh-cookie-cleaner --clean --older-than=24 只删创建超过 24 小时的(可小数,如 0.5=30 分钟)
34
- dsh-cookie-cleaner --clean --dry-run 只看会删几条,不写盘
35
- dsh-cookie-cleaner --db=<完整路径> 手动指定 cookie 库(非默认安装/flatpak/snap 用)
36
-
37
- 库位置默认按平台惯例推导(也可用 DSH_USER_DATA / DSH_COOKIE_DB 覆盖):
38
- Windows %APPDATA%\\@deepseek-ai\\dsh-desktop\\Network\\Cookies
39
- macOS ~/Library/Application Support/@deepseek-ai/dsh-desktop/Network/Cookies
40
- Linux ~/.config/@deepseek-ai/dsh-desktop/Network/Cookies
41
-
42
- 其它:--no-backup 不产出 .bak 副本;--no-vacuum 不做 VACUUM 收缩;
43
- --lang <${LANGS.join('|')}> 指定输出语言(缺省跟随系统 locale);--version 只报包名与版本
44
-
45
- patch 体检(profile 的 cordis.patch.yml 结构,不碰 cookie 库):
46
- dsh-cookie-cleaner patch [check] 离线体检:行在不在、name 对不对、值合不合法、home 层影子
47
- dsh-cookie-cleaner patch plan 输出可直接粘贴的覆盖行(目标值已就位)
48
- --profile <name> 体检哪个 profile(默认 desktop)
49
- --patch-file <路径> 直接指定 patch 文件(优先于 --profile)
50
- --target-days <N> 目标 cookie 绝对寿命(≥ 1,默认 1)
51
-
52
- 退出码:0 成功;1 失败(库被占用/无权限/没找到/参数非法/结构会失效)
53
- `
54
- }
55
-
56
- /** DSH home(与 patch-guard 同式,不重复一套平台规则)。 */
57
- function dshHomeOf(env) {
58
- const explicit = String(env.DSH_HOME ?? '').trim()
59
- return explicit !== '' ? explicit : path.join(os.homedir(), '.dsh')
60
- }
61
-
62
- function parseArgs(argv) {
63
- const options = { clean: false, expiredOnly: false, olderThan: 0, dryRun: false, noBackup: false, noVacuum: false, db: '', lang: '', help: false, version: false, command: '', sub: 'check', profile: 'desktop', patchFile: '', targetDays: 1 }
64
- for (let i = 0; i < argv.length; i++) {
65
- const arg = argv[i]
66
- if (arg === '--clean') options.clean = true
67
- else if (arg === '--expired-only') options.expiredOnly = true
68
- else if (arg === '--older-than') options.olderThan = Number(argv[++i])
69
- else if (arg.startsWith('--older-than=')) options.olderThan = Number(arg.slice('--older-than='.length))
70
- else if (arg === '--dry-run') options.dryRun = true
71
- else if (arg === '--no-backup') options.noBackup = true
72
- else if (arg === '--no-vacuum') options.noVacuum = true
73
- else if (arg === '--help' || arg === '-h') options.help = true
74
- else if (arg === '--version' || arg === '-v') options.version = true
75
- else if (arg.startsWith('--db=')) options.db = arg.slice('--db='.length)
76
- else if (arg === '--lang') options.lang = normalize(argv[++i] ?? '')
77
- else if (arg.startsWith('--lang=')) options.lang = normalize(arg.slice('--lang='.length))
78
- else if (arg === '--profile') options.profile = String(argv[++i] ?? 'desktop')
79
- else if (arg.startsWith('--profile=')) options.profile = arg.slice('--profile='.length)
80
- else if (arg === '--patch-file') options.patchFile = String(argv[++i] ?? '')
81
- else if (arg.startsWith('--patch-file=')) options.patchFile = arg.slice('--patch-file='.length)
82
- else if (arg === '--target-days') options.targetDays = Number(argv[++i])
83
- else if (arg.startsWith('--target-days=')) options.targetDays = Number(arg.slice('--target-days='.length))
84
- else if (!arg.startsWith('-') && options.command === '' && !options.clean) {
85
- // 位置参数只认 `patch`(cookie 面保持无子命令的原样,不破坏 0.1.x 用法习惯)
86
- if (arg !== 'patch') {
87
- process.stderr.write(`未知参数:${arg}\n\n${usage()}`)
88
- process.exitCode = 1
89
- return undefined
90
- }
91
- options.command = 'patch'
92
- const next = argv[i + 1]
93
- if (next === 'check' || next === 'plan') { options.sub = next; i += 1 }
94
- }
95
- else {
96
- process.stderr.write(`未知参数:${arg}\n\n${usage()}`)
97
- process.exitCode = 1
98
- return undefined
99
- }
100
- }
101
- return options
102
- }
103
-
104
- /** patch 子命令的离线路径:只读文件,**绝不写 profile**(写只属于面板/宿主命令)。 */
105
- function runPatch(options) {
106
- const file = options.patchFile !== ''
107
- ? path.resolve(options.patchFile)
108
- : path.join(dshHomeOf(process.env), 'profiles', options.profile, 'cordis.patch.yml')
109
- if (!Number.isInteger(options.targetDays) || options.targetDays < 1) {
110
- process.stderr.write(`--target-days 必须是 ≥ 1 的整数,实际:${String(options.targetDays)}\n`)
111
- process.exitCode = 1
112
- return
113
- }
114
- const result = offlineCheck({ profileFile: file, targetDays: options.targetDays })
115
- if (options.sub === 'plan') {
116
- const parsed = readPatchFile(file).parsed
117
- const conn = findOverrideRow(parsed, 'connection')
118
- process.stdout.write(renderPlanBlock({
119
- rowId: 'connection',
120
- inherited: {},
121
- current: conn?.config ?? { trustedHosts: [], maxRequestBodyBytes: 314572800 },
122
- targetDays: options.targetDays,
123
- }) + '\n')
124
- process.exitCode = parsed.ok ? 0 : 1
125
- return
126
- }
127
- process.stdout.write(patchReportText(result) + '\n')
128
- // 退出码黑名单:只有真读到且结构不是「会失效」的才算成功
129
- process.exitCode = result.level === 'fail' || result.level === 'skipped' ? 1 : 0
130
- }
131
-
132
- function main() {
133
- const options = parseArgs(process.argv.slice(2))
134
- if (options === undefined) return
135
- const lang = options.lang || detectLang(process.env)
136
- core.setLang(lang)
137
- if (options.help) {
138
- process.stdout.write(usage())
139
- return
140
- }
141
- if (options.version) {
142
- // 版本号只从包内 package.json 读:装机别名报的号必须与包体同号(V1 闸的运行态对拍)
143
- try {
144
- const pkg = JSON.parse(readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'))
145
- process.stdout.write(`${pkg.name}@${pkg.version}\n`)
146
- } catch (e) {
147
- process.stderr.write(`读不到 package.json:${String(e && e.message ? e.message : e)}\n`)
148
- process.exitCode = 1
149
- }
150
- return
151
- }
152
- const explicitPath = options.db ? path.resolve(options.db) : ''
153
- const env = process.env
154
- if (options.command === 'patch') {
155
- runPatch(options)
156
- return
157
- }
158
- try {
159
- if (!options.clean) {
160
- // CLI 不借句柄:它是独立进程,镜像名与桌面端不同(目标进程匹配不上),
161
- // 而且一个命令行工具不该去扫全机句柄表。要运行期水位就看面板。
162
- const stat = core.statCookies({ explicitPath, env })
163
- process.stdout.write(core.describeStat(stat) + '\n')
164
- // 占用折算单独一句:describeStat 保持「一句话」契约,但数字不能缺席(与面板同一函数同一句)。
165
- const live = cookieLiveText(stat)
166
- if (live !== undefined) process.stdout.write(live + '\n')
167
- const exit = core.exitInstruction()
168
- if (stat.reason === 'busy') {
169
- process.stdout.write(nextLine('nextCliRerun', { exit }) + '\n')
170
- } else if (stat.reason === 'permission') {
171
- process.stdout.write(nextLine('nextCliPermission', {}) + '\n')
172
- } else if (stat.reason === 'missing') {
173
- // 文件不存在时提“关客户端”是误引导,直接给 --db 形式
174
- process.stdout.write(msg('nextCliPermission', {}) + '\n')
175
- } else if (stat.verdict === 'warn') {
176
- process.stdout.write(nextLine('nextCliClean', { exit }) + '\n')
177
- }
178
- // 退出码用黑名单:只有「真读到内容」的档位才是 0。白名单写法会把新档误归成成功。
179
- const okReason = stat.reason === 'has-stale-entries' || stat.reason === 'nothing-to-clean' || stat.verdict === 'ok'
180
- process.exitCode = okReason ? 0 : 1
181
- return
182
- }
183
- if (!Number.isFinite(options.olderThan) || options.olderThan < 0) {
184
- process.stderr.write(`--older-than 必须是 ≥ 0 的小时数,实际:${String(options.olderThan)}\n`)
185
- process.exitCode = 1
186
- return
187
- }
188
- const result = core.cleanCookies({
189
- expiredOnly: options.expiredOnly,
190
- olderThanHours: options.olderThan,
191
- dryRun: options.dryRun,
192
- noBackup: options.noBackup,
193
- noVacuum: options.noVacuum,
194
- explicitPath,
195
- env,
196
- })
197
- if (result.ok === false) {
198
- process.stderr.write(result.message + '\n')
199
- process.exitCode = 1
200
- return
201
- }
202
- if (result.dryRun) {
203
- process.stdout.write(msg('dryRun', { count: result.wouldDelete, path: result.path }) + '\n' + msg('dryRunTail', {}) + '\n')
204
- return
205
- }
206
- const scope = result.olderThanHours > 0
207
- ? msg('scopeOlderThan', { hours: result.olderThanHours })
208
- : result.expiredOnly ? msg('scopeExpired', {}) : msg('scopeAll', {})
209
- const lines = [
210
- msg('deleted', { count: result.deleted, scope }),
211
- msg('dbSize', { path: result.path, before: result.beforeBytes, after: result.afterBytes }),
212
- ]
213
- if (result.backup) {
214
- lines.push(msg('backup', { backup: result.backup }) + ((result.backupSidecars ?? []).length ? msg('backupWith', { sidecars: result.backupSidecars.join(', ') }) : ''))
215
- if ((result.skippedSidecars ?? []).length) lines.push(msg('backupWarn', { sidecars: result.skippedSidecars.join(', ') }))
216
- } else {
217
- lines.push(msg('backupSkipped', {}))
218
- }
219
- lines.push(msg('untouched', {}))
220
- process.stdout.write(lines.join('\n') + '\n')
221
- } catch (e) {
222
- const busy = e && (e.code === 'cookie-busy' || e.code === 'cookie-permission')
223
- process.stderr.write((busy ? '' : msg('cleanFailed', {})) + (e && e.message ? e.message : String(e)) + '\n')
224
- process.exitCode = 1
225
- }
226
- }
227
-
228
- /** 取当前语言的词条(core 内部也按同一语言出文案,保持一致)。 */
229
- function msg(key, vars) {
230
- return translator(core.activeLang())(key, vars)
231
- }
232
- function nextLine(key, vars) {
233
- return msg(key, vars)
234
- }
235
-
236
- main()
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-cookie-cleaner — 独立清理脚本(可在 npm 全局/任意 shell 下直接执行)。
4
+ *
5
+ * 为什么独立成脚本:cookie 库在客户端运行期间被 Chromium 独占(实测写入必须等退出),
6
+ * 所以清理只能发生在「客户端已完全退出」的时刻——那时宿主插件根本不存在,
7
+ * 执行体必须是这个包里的脚本。
8
+ *
9
+ * 包是 ESM(宿主装载与 npm bin 都走 ESM),core 只有一份实现,两边共用。
10
+ * 输出语言:--lang > DSH_COOKIE_LANG/DSH_LANG > LC_ALL/LANG > 系统 locale > zh。
11
+ */
12
+ import os from 'node:os'
13
+ import path from 'node:path'
14
+ import process from 'node:process'
15
+ import { readFileSync } from 'node:fs'
16
+ import { fileURLToPath } from 'node:url'
17
+ import * as core from './core.js'
18
+ import { LANGS, detectLang, normalize, translator } from './i18n.js'
19
+ import { offlineCheck } from './patch-guard.js'
20
+ import { renderPlanBlock } from './patch-model.js'
21
+ import { findOverrideRow, readPatchFile } from './patch-read.js'
22
+ import { cookieLiveText, patchReportText } from './report.js'
23
+
24
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
25
+
26
+ function usage() {
27
+ return `dsh-cookie-cleaner — 清理 DSH 客户端留在 cookie 库里的本地登录凭据(dsh-auth-*)
28
+
29
+ 用法(务必先${core.exitInstruction()}):
30
+ dsh-cookie-cleaner 查看现状:库在哪、多少条 dsh-auth-*、多少已过期
31
+ dsh-cookie-cleaner --clean 删除回环域(127.0.0.1/localhost/[::1])下全部 dsh-auth-*
32
+ dsh-cookie-cleaner --clean --expired-only 保守档:只删已过期的
33
+ dsh-cookie-cleaner --clean --older-than=24 只删创建超过 24 小时的(可小数,如 0.5=30 分钟)
34
+ dsh-cookie-cleaner --clean --dry-run 只看会删几条,不写盘
35
+ dsh-cookie-cleaner --db=<完整路径> 手动指定 cookie 库(非默认安装/flatpak/snap 用)
36
+
37
+ 库位置默认按平台惯例推导(也可用 DSH_USER_DATA / DSH_COOKIE_DB 覆盖):
38
+ Windows %APPDATA%\\@deepseek-ai\\dsh-desktop\\Network\\Cookies
39
+ macOS ~/Library/Application Support/@deepseek-ai/dsh-desktop/Network/Cookies
40
+ Linux ~/.config/@deepseek-ai/dsh-desktop/Network/Cookies
41
+
42
+ 其它:--no-backup 不产出 .bak 副本;--no-vacuum 不做 VACUUM 收缩;
43
+ --lang <${LANGS.join('|')}> 指定输出语言(缺省跟随系统 locale);--version 只报包名与版本
44
+
45
+ patch 体检(profile 的 cordis.patch.yml 结构,不碰 cookie 库):
46
+ dsh-cookie-cleaner patch [check] 离线体检:行在不在、name 对不对、值合不合法、home 层影子
47
+ dsh-cookie-cleaner patch plan 输出可直接粘贴的覆盖行(目标值已就位)
48
+ dsh-cookie-cleaner legacy 只读:报告旧版插件写进 profile 的 port 注入残留
49
+ --profile <name> 体检哪个 profile(默认 desktop)
50
+ --patch-file <路径> 直接指定 patch 文件(优先于 --profile)
51
+ --target-days <N> 目标 cookie 绝对寿命(≥ 1,默认 1)
52
+
53
+ 退出码:0 成功;1 失败(库被占用/无权限/没找到/参数非法/结构会失效)
54
+ `
55
+ }
56
+
57
+ /** DSH home(与 patch-guard 同式,不重复一套平台规则)。 */
58
+ function dshHomeOf(env) {
59
+ const explicit = String(env.DSH_HOME ?? '').trim()
60
+ return explicit !== '' ? explicit : path.join(os.homedir(), '.dsh')
61
+ }
62
+
63
+ function parseArgs(argv) {
64
+ const options = { clean: false, expiredOnly: false, olderThan: 0, dryRun: false, noBackup: false, noVacuum: false, db: '', lang: '', help: false, version: false, command: '', sub: 'check', profile: 'desktop', patchFile: '', targetDays: 1 }
65
+ for (let i = 0; i < argv.length; i++) {
66
+ const arg = argv[i]
67
+ if (arg === '--clean') options.clean = true
68
+ else if (arg === '--expired-only') options.expiredOnly = true
69
+ else if (arg === '--older-than') options.olderThan = Number(argv[++i])
70
+ else if (arg.startsWith('--older-than=')) options.olderThan = Number(arg.slice('--older-than='.length))
71
+ else if (arg === '--dry-run') options.dryRun = true
72
+ else if (arg === '--no-backup') options.noBackup = true
73
+ else if (arg === '--no-vacuum') options.noVacuum = true
74
+ else if (arg === '--help' || arg === '-h') options.help = true
75
+ else if (arg === '--version' || arg === '-v') options.version = true
76
+ else if (arg.startsWith('--db=')) options.db = arg.slice('--db='.length)
77
+ else if (arg === '--lang') options.lang = normalize(argv[++i] ?? '')
78
+ else if (arg.startsWith('--lang=')) options.lang = normalize(arg.slice('--lang='.length))
79
+ else if (arg === '--profile') options.profile = String(argv[++i] ?? 'desktop')
80
+ else if (arg.startsWith('--profile=')) options.profile = arg.slice('--profile='.length)
81
+ else if (arg === '--patch-file') options.patchFile = String(argv[++i] ?? '')
82
+ else if (arg.startsWith('--patch-file=')) options.patchFile = arg.slice('--patch-file='.length)
83
+ else if (arg === '--target-days') options.targetDays = Number(argv[++i])
84
+ else if (arg.startsWith('--target-days=')) options.targetDays = Number(arg.slice('--target-days='.length))
85
+ else if (!arg.startsWith('-') && options.command === '' && !options.clean) {
86
+ // 位置参数只认 `patch`(cookie 面保持无子命令的原样,不破坏 0.1.x 用法习惯)
87
+ if (arg !== 'patch' && arg !== 'legacy') {
88
+ process.stderr.write(`未知参数:${arg}\n\n${usage()}`)
89
+ process.exitCode = 1
90
+ return undefined
91
+ }
92
+ options.command = arg
93
+ const next = argv[i + 1]
94
+ if (arg === 'patch' && (next === 'check' || next === 'plan')) { options.sub = next; i += 1 }
95
+ }
96
+ else {
97
+ process.stderr.write(`未知参数:${arg}\n\n${usage()}`)
98
+ process.exitCode = 1
99
+ return undefined
100
+ }
101
+ }
102
+ return options
103
+ }
104
+
105
+ /** patch 子命令的离线路径:只读文件,**绝不写 profile**(写只属于面板/宿主命令)。 */
106
+ function runPatch(options) {
107
+ const file = options.patchFile !== ''
108
+ ? path.resolve(options.patchFile)
109
+ : path.join(dshHomeOf(process.env), 'profiles', options.profile, 'cordis.patch.yml')
110
+ if (!Number.isInteger(options.targetDays) || options.targetDays < 1) {
111
+ process.stderr.write(`--target-days 必须是 ≥ 1 的整数,实际:${String(options.targetDays)}\n`)
112
+ process.exitCode = 1
113
+ return
114
+ }
115
+ const result = offlineCheck({ profileFile: file, targetDays: options.targetDays })
116
+ if (options.sub === 'plan') {
117
+ const parsed = readPatchFile(file).parsed
118
+ const conn = findOverrideRow(parsed, 'connection')
119
+ process.stdout.write(renderPlanBlock({
120
+ rowId: 'connection',
121
+ inherited: {},
122
+ current: conn?.config ?? { trustedHosts: [], maxRequestBodyBytes: 314572800 },
123
+ targetDays: options.targetDays,
124
+ }) + '\n')
125
+ process.exitCode = parsed.ok ? 0 : 1
126
+ return
127
+ }
128
+ process.stdout.write(patchReportText(result) + '\n')
129
+ // 退出码黑名单:只有真读到且结构不是「会失效」的才算成功
130
+ process.exitCode = result.level === 'fail' || result.level === 'skipped' ? 1 : 0
131
+ }
132
+
133
+ /**
134
+ * `legacy` 子命令:**只读**报告旧版插件写进 profile 的 port 注入残留。
135
+ *
136
+ * 为什么 CLI 只报不改:清理必须走 `configEditor.edit`(schema 校验 + 原子写 + HMR),
137
+ * 那是宿主运行期的能力;离线进程直改 profile 会绕过校验,正是本插件一直避免的做法。
138
+ * 所以离线只给"有/没有 + 原表达式 + 该怎么做",写留给面板或命令面。
139
+ */
140
+ function runLegacy(options) {
141
+ const file = options.patchFile !== ''
142
+ ? path.resolve(options.patchFile)
143
+ : path.join(dshHomeOf(process.env), 'profiles', options.profile, 'cordis.patch.yml')
144
+ const read = readPatchFile(file)
145
+ if (read.exists !== true) {
146
+ process.stdout.write(`patch 文件不存在:${file}\n`)
147
+ process.exitCode = 1
148
+ return
149
+ }
150
+ if (read.parsed.ok !== true) {
151
+ process.stdout.write(`patch 文件解析失败(${read.parsed.reason}):${file}\n`)
152
+ process.exitCode = 1
153
+ return
154
+ }
155
+ const row = findOverrideRow(read.parsed, 'webserver')
156
+ const port = row?.config?.port
157
+ const hit = port !== null && typeof port === 'object' && typeof port.__jsExpr === 'string'
158
+ ? /^\s*ctx\.webStartup\.port\s*\?\?\s*(\+?\s*\d+)\s*$/.exec(port.__jsExpr)
159
+ : null
160
+ if (hit === null) {
161
+ process.stdout.write(`没有历史注入残留(${file})\n`)
162
+ return
163
+ }
164
+ process.stdout.write(
165
+ `发现历史注入残留:webserver.port = !!js ${port.__jsExpr}\n`
166
+ + ` 这是旧版 dsh-cookie-cleaner 的「应用端口」动作写的(0.2.1 起该能力已删除)。\n`
167
+ + ` 现在生效的就是你钉的 ${hit[1].replace(/[+\s]/g, '')},启动层传来的 --port 压不动它。\n`
168
+ + ` 清理:在面板「历史注入」处点清理(需宿主 0.2.2-rc.2+,官方已接管 cookie 清理),\n`
169
+ + ` 或手动删掉 ${file} 里那一行 port。\n`,
170
+ )
171
+ }
172
+
173
+ function main() {
174
+ const options = parseArgs(process.argv.slice(2))
175
+ if (options === undefined) return
176
+ const lang = options.lang || detectLang(process.env)
177
+ core.setLang(lang)
178
+ if (options.help) {
179
+ process.stdout.write(usage())
180
+ return
181
+ }
182
+ if (options.version) {
183
+ // 版本号只从包内 package.json 读:装机别名报的号必须与包体同号(V1 闸的运行态对拍)
184
+ try {
185
+ const pkg = JSON.parse(readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'))
186
+ process.stdout.write(`${pkg.name}@${pkg.version}\n`)
187
+ } catch (e) {
188
+ process.stderr.write(`读不到 package.json:${String(e && e.message ? e.message : e)}\n`)
189
+ process.exitCode = 1
190
+ }
191
+ return
192
+ }
193
+ const explicitPath = options.db ? path.resolve(options.db) : ''
194
+ const env = process.env
195
+ if (options.command === 'patch') {
196
+ runPatch(options)
197
+ return
198
+ }
199
+ if (options.command === 'legacy') {
200
+ runLegacy(options)
201
+ return
202
+ }
203
+ try {
204
+ if (!options.clean) {
205
+ // CLI 不借句柄:它是独立进程,镜像名与桌面端不同(目标进程匹配不上),
206
+ // 而且一个命令行工具不该去扫全机句柄表。要运行期水位就看面板。
207
+ const stat = core.statCookies({ explicitPath, env })
208
+ process.stdout.write(core.describeStat(stat) + '\n')
209
+ // 占用折算单独一句:describeStat 保持「一句话」契约,但数字不能缺席(与面板同一函数同一句)。
210
+ const live = cookieLiveText(stat)
211
+ if (live !== undefined) process.stdout.write(live + '\n')
212
+ const exit = core.exitInstruction()
213
+ if (stat.reason === 'busy') {
214
+ process.stdout.write(nextLine('nextCliRerun', { exit }) + '\n')
215
+ } else if (stat.reason === 'permission') {
216
+ process.stdout.write(nextLine('nextCliPermission', {}) + '\n')
217
+ } else if (stat.reason === 'missing') {
218
+ // 文件不存在时提“关客户端”是误引导,直接给 --db 形式
219
+ process.stdout.write(msg('nextCliPermission', {}) + '\n')
220
+ } else if (stat.verdict === 'warn') {
221
+ process.stdout.write(nextLine('nextCliClean', { exit }) + '\n')
222
+ }
223
+ // 退出码用黑名单:只有「真读到内容」的档位才是 0。白名单写法会把新档误归成成功。
224
+ const okReason = stat.reason === 'has-stale-entries' || stat.reason === 'nothing-to-clean' || stat.verdict === 'ok'
225
+ process.exitCode = okReason ? 0 : 1
226
+ return
227
+ }
228
+ if (!Number.isFinite(options.olderThan) || options.olderThan < 0) {
229
+ process.stderr.write(`--older-than 必须是 ≥ 0 的小时数,实际:${String(options.olderThan)}\n`)
230
+ process.exitCode = 1
231
+ return
232
+ }
233
+ const result = core.cleanCookies({
234
+ expiredOnly: options.expiredOnly,
235
+ olderThanHours: options.olderThan,
236
+ dryRun: options.dryRun,
237
+ noBackup: options.noBackup,
238
+ noVacuum: options.noVacuum,
239
+ explicitPath,
240
+ env,
241
+ })
242
+ if (result.ok === false) {
243
+ process.stderr.write(result.message + '\n')
244
+ process.exitCode = 1
245
+ return
246
+ }
247
+ if (result.dryRun) {
248
+ process.stdout.write(msg('dryRun', { count: result.wouldDelete, path: result.path }) + '\n' + msg('dryRunTail', {}) + '\n')
249
+ return
250
+ }
251
+ const scope = result.olderThanHours > 0
252
+ ? msg('scopeOlderThan', { hours: result.olderThanHours })
253
+ : result.expiredOnly ? msg('scopeExpired', {}) : msg('scopeAll', {})
254
+ const lines = [
255
+ msg('deleted', { count: result.deleted, scope }),
256
+ msg('dbSize', { path: result.path, before: result.beforeBytes, after: result.afterBytes }),
257
+ ]
258
+ if (result.backup) {
259
+ lines.push(msg('backup', { backup: result.backup }) + ((result.backupSidecars ?? []).length ? msg('backupWith', { sidecars: result.backupSidecars.join(', ') }) : ''))
260
+ if ((result.skippedSidecars ?? []).length) lines.push(msg('backupWarn', { sidecars: result.skippedSidecars.join(', ') }))
261
+ } else {
262
+ lines.push(msg('backupSkipped', {}))
263
+ }
264
+ lines.push(msg('untouched', {}))
265
+ process.stdout.write(lines.join('\n') + '\n')
266
+ } catch (e) {
267
+ const busy = e && (e.code === 'cookie-busy' || e.code === 'cookie-permission')
268
+ process.stderr.write((busy ? '' : msg('cleanFailed', {})) + (e && e.message ? e.message : String(e)) + '\n')
269
+ process.exitCode = 1
270
+ }
271
+ }
272
+
273
+ /** 取当前语言的词条(core 内部也按同一语言出文案,保持一致)。 */
274
+ function msg(key, vars) {
275
+ return translator(core.activeLang())(key, vars)
276
+ }
277
+ function nextLine(key, vars) {
278
+ return msg(key, vars)
279
+ }
280
+
281
+ main()