@hyzyn/dsh-safe 0.13.1 → 0.14.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.en.md CHANGED
@@ -48,7 +48,8 @@ Error: dsh: plugin tree failed to load: failed to apply loader entry smoke-broke
48
48
  | `dsh-safe doctor` | environment check: versions, DSH_HOME, profiles, ledger, patch health |
49
49
  | `dsh-safe restore [--profile <name>] (--id <id> \| --all) [--dry-run]` | re-enable auto-disabled plugins (omit `--profile` to cover every profile in the ledger) |
50
50
  | `dsh-safe explain [id] [--profile <name> \| --file <path>]` | interpret failure info with AI: an `id` interprets that quarantine record (with repair advice); defaults to the last failure log, falling back to the ledger; `--file`/stdin read any log (needs `DSH_SAFE_AI_KEY`) |
51
- | `dsh-safe repair [id] [--profile <name>] [--to <version>] [-y] [--dry-run]` | reinstall/upgrade a quarantined plugin and auto-restore it (failures a reinstall/upgrade may fix: package resolution, export mismatches; installs via `dsh plugin`'s pnpm channel); duplicate mounts support auto-dedup (interactively pick which source to keep) |
51
+ | `dsh-safe -r [dsh args…]` | repair all repairable quarantined plugins first, then boot in wrap mode (`--repair` alias; mirrors `-u`) |
52
+ | `dsh-safe repair [id] [--all] [--profile <name>] [--to <version>] [-y] [--dry-run]` | reinstall/upgrade a quarantined plugin and auto-restore it (failures a reinstall/upgrade may fix: package resolution, export mismatches; installs via `dsh plugin`'s pnpm channel); duplicate mounts support auto-dedup (interactively pick which source to keep) |
52
53
  | `dsh-safe help` (`-h` / `--help`) | show help |
53
54
  | `dsh-safe --version` (`-V`) | show version |
54
55
 
package/README.md CHANGED
@@ -48,7 +48,8 @@ Error: dsh: plugin tree failed to load: failed to apply loader entry smoke-broke
48
48
  | `dsh-safe doctor` | 环境体检:版本、DSH_HOME、profiles、台账、各 patch 健康度 |
49
49
  | `dsh-safe restore [--profile <名>] (--id <id> \| --all) [--dry-run]` | 恢复被自动禁用的插件(省略 `--profile` 时遍历台账全部 profile) |
50
50
  | `dsh-safe explain [id] [--profile <名> \| --file <路径>]` | 用 AI 解读失败信息:指定 `id` 解读该条隔离记录(给 repair 建议);默认解读最近一次失败日志,无日志则解读隔离台账;`--file`/stdin 读任意日志(需 `DSH_SAFE_AI_KEY`) |
51
- | `dsh-safe repair [id] [--profile <名>] [--to <版本>] [-y] [--dry-run]` | 重装/升级被隔离的插件并自动恢复(限重装/升级可能修复的失败:包解析失败、导出版本不匹配等;经 `dsh plugin` pnpm 通道安装);重复挂载类支持自动去重(交互选择保留哪个来源,从 bundles 移除冗余) |
51
+ | `dsh-safe -r [dsh 参数…]` | 先修复全部可修复的隔离记录,再按包装模式启动(`--repair` 等价;与 `-u` 对称) |
52
+ | `dsh-safe repair [id] [--all] [--profile <名>] [--to <版本>] [-y] [--dry-run]` | 重装/升级被隔离的插件并自动恢复(限重装/升级可能修复的失败:包解析失败、导出版本不匹配等;经 `dsh plugin` 的 pnpm 通道安装);重复挂载类支持自动去重(交互选择保留哪个来源,从 bundles 移除冗余) |
52
53
  | `dsh-safe help`(`-h` / `--help`) | 显示帮助 |
53
54
  | `dsh-safe --version`(`-V`) | 显示版本 |
54
55
 
package/lib/cli.js CHANGED
@@ -11,7 +11,7 @@ import { createRequire } from 'node:module'
11
11
  import { loadLedger, restoreQuarantine } from './quarantine.js'
12
12
  import { runWrapped } from './wrap.js'
13
13
  import { cmdUpdate, cmdUpdateAndBoot, maybeNotifySelfUpdate } from './update.js'
14
- import { cmdRepair } from './repair.js'
14
+ import { cmdRepair, cmdRepairAndBoot } from './repair.js'
15
15
  import { printDoctor } from './doctor.js'
16
16
  import { cmdExplain } from './ai.js'
17
17
  import { t } from './i18n.js'
@@ -142,6 +142,7 @@ export async function main(argv) {
142
142
  return 0
143
143
  }
144
144
  if (cmd === '-u' || cmd === '--update') return cmdUpdateAndBoot(argv.slice(1), { boot: runWrapperMode })
145
+ if (cmd === '-r' || cmd === '--repair') return cmdRepairAndBoot(argv.slice(1), { boot: runWrapperMode })
145
146
 
146
147
  // 包装模式:剥掉 dsh-safe 自己的旗标(必须出现在第一个位置参数之前),
147
148
  // 其余原样转发给 dsh。
package/lib/i18n.js CHANGED
@@ -25,8 +25,9 @@ const ZH = {
25
25
  dsh-safe update [-y] [--to <版本>] [--self] [--no-restore] [--no-verify] [--pm npm|pnpm]
26
26
  升级 dsh 与 dsh-safe 自身,并自动恢复被隔离的插件
27
27
  dsh-safe explain [id] [--profile <名> | --file <路径>] 用 AI 解读:最近失败日志 / 隔离台账 / 任意日志
28
- dsh-safe repair [id] [--profile <名>] [--to <版本>] [-y] [--dry-run]
29
- 重装/升级被隔离的插件并自动恢复(限包解析/导出不匹配类;省略 id 时只有一条记录则直接修)
28
+ dsh-safe repair [id] [--all] [--profile <名>] [--to <版本>] [-y] [--dry-run]
29
+ 重装/升级被隔离的插件并自动恢复(--all 批量;限可自动修复类;省略 id 时只有一条记录则直接修)
30
+ dsh-safe -r [dsh 参数…] 先修复全部可修复的隔离记录,再启动(--repair 等价)
30
31
  dsh-safe help 显示本帮助
31
32
  dsh-safe --version 显示版本
32
33
 
@@ -142,6 +143,11 @@ const ZH = {
142
143
  repairDedupePlan: '[dsh-safe] 修复方案:保留 {keep} 的挂载,从 bundles 移除 {remove},并摘除 {id} 的禁用行',
143
144
  repairDedupeNoManifest: '[dsh-safe] profile 清单中没有可编辑的 bundles 数组,请手动处理。',
144
145
  repairDedupeDone: '[dsh-safe] 去重完成:已从 bundles 移除 {removed};{keep} 的挂载保留、禁用行已摘除。跑 dsh-safe <启动命令> 验证。',
146
+ repairAllConflict: '[dsh-safe] --all 与 <id> 不能同时使用。',
147
+ repairUnknownArg: '[dsh-safe] repair 无法识别的参数: {arg}',
148
+ repairBatchPlan: '[dsh-safe] 将修复 {count} 条隔离记录: {ids}',
149
+ repairBatchSkip: '[dsh-safe] 跳过 {count} 条(不支持自动修复): {ids}',
150
+ repairBatchDone: '[dsh-safe] 批量修复完成:成功 {repaired} 条,失败 {failed} 条。',
145
151
  repairInstallFailed: '[dsh-safe] 插件安装失败(退出码 {code}),隔离状态保持不变。',
146
152
  repairDone: '[dsh-safe] 修复完成:跑 dsh-safe <启动命令> 验证;若仍失败会被自动重新隔离。',
147
153
  }
@@ -166,8 +172,9 @@ Usage:
166
172
  dsh-safe update [-y] [--to <ver>] [--self] [--no-restore] [--no-verify] [--pm npm|pnpm]
167
173
  upgrade dsh and dsh-safe itself, auto-restore quarantined plugins
168
174
  dsh-safe explain [id] [--profile <name> | --file <path>] interpret with AI: last failure log / ledger / any log
169
- dsh-safe repair [id] [--profile <name>] [--to <ver>] [-y] [--dry-run]
170
- reinstall/upgrade a quarantined plugin and auto-restore it (resolution/export-mismatch failures; omit id when there is exactly one record)
175
+ dsh-safe repair [id] [--all] [--profile <name>] [--to <ver>] [-y] [--dry-run]
176
+ reinstall/upgrade quarantined plugins and auto-restore (--all for batch; repairable failures only; omit id when there is exactly one record)
177
+ dsh-safe -r [dsh args…] repair all repairable quarantined plugins, then boot (--repair alias)
171
178
  dsh-safe help show this help
172
179
  dsh-safe --version show version
173
180
 
@@ -286,6 +293,11 @@ Notes:
286
293
  repairDedupePlan: '[dsh-safe] fix plan: keep {keep} mounted, remove {remove} from bundles, and drop the disabled row for {id}',
287
294
  repairDedupeNoManifest: '[dsh-safe] the profile manifest has no editable bundles array; handle it manually.',
288
295
  repairDedupeDone: '[dsh-safe] dedupe finished: removed {removed} from bundles; {keep} stays mounted and the disabled row was dropped. Run dsh-safe <boot command> to verify.',
296
+ repairAllConflict: '[dsh-safe] --all and <id> are mutually exclusive.',
297
+ repairUnknownArg: '[dsh-safe] unrecognized argument for repair: {arg}',
298
+ repairBatchPlan: '[dsh-safe] repairing {count} quarantine record(s): {ids}',
299
+ repairBatchSkip: '[dsh-safe] skipping {count} (not auto-repairable): {ids}',
300
+ repairBatchDone: '[dsh-safe] batch repair finished: {repaired} succeeded, {failed} failed.',
289
301
  repairInstallFailed: '[dsh-safe] plugin install failed (exit code {code}); quarantine state left unchanged.',
290
302
  repairDone: '[dsh-safe] repair finished: run dsh-safe <boot command> to verify; a still-broken plugin will be auto-quarantined again.',
291
303
  }
package/lib/repair.js CHANGED
@@ -1,14 +1,25 @@
1
1
  /**
2
- * @hyzyn/dsh-safe — `dsh-safe repair <id>`:半自动修复被隔离的插件。
2
+ * @hyzyn/dsh-safe — `dsh-safe repair` 与 `dsh-safe -r`:修复被隔离的插件。
3
3
  *
4
- * 只处理"模块解析失败"类(Cannot find package / could not be resolved /
5
- * ERR_MODULE_NOT_FOUND)——这类问题重装/升级插件包即可修复。其它类型
6
- * (apply 抛错、pending 服务等待等)属于代码或配置问题,明确拒接。
4
+ * repair 可修复的失败特征:问题出在"包的安装状态或版本适配"上,重装/升级
5
+ * 插件包可能修复——
6
+ * - 模块解析失败:包缺失/损坏/未安装 重装即愈;
7
+ * - ESM 导出不匹配(does not provide an [export|import binding]):插件与
8
+ * 当前 dsh API 版本不兼容,升级插件到适配版本可能修复(真实案例:
9
+ * describe-image 隔离于 dsh-settings 导出变更)。修复失败不恢复、无损。
10
+ * 注意:台账 reason 经 summarizeLine 截断过(160 字符),关键短语可能被
11
+ * "…" 切断,因此导出不匹配的特征只匹配到 "does not provide an" 为止。
12
+ *
13
+ * duplicate(同一 id 被多个 bundle 挂载)是配置层问题,重装无意义——但
14
+ * 支持自动去重:从 profile 清单的 bundles 移除一个来源(交互选择保留哪个,
15
+ * -y 保留先声明者),并摘除无效的禁用行。include 子文件里的重复不在
16
+ * bundle 层对照表内,自动去重帮不上,给手动指引。
7
17
  *
8
- * 流程:台账定位条目 类别门禁 → 展示计划 → 确认 → 经 `dsh plugin add`
9
- * (dsh 官方的 pnpm 转发通道)安装 → 自动摘除隔离行。不内置启动:装好后
10
- * 由用户跑 dsh-safe 验证,再失败会自动回到隔离管线。安装失败则保持隔离
11
- * 状态不变,退出码透传。
18
+ * 安装路径修复完成后会复查该 id 的挂载来源:修复的插件若同时被聚合包等
19
+ * 其它 bundle 挂载,恢复后下次启动会 duplicate——自动去重防复发。
20
+ *
21
+ * `--all` 批量修复台账里全部可修复记录;`-r/--repair` = 批量修复 + 启动
22
+ * (与 -u 对称:位置参数全部是 dsh 启动参数)。
12
23
  */
13
24
  import { spawnSync } from 'node:child_process'
14
25
  import { createInterface } from 'node:readline/promises'
@@ -22,129 +33,130 @@ import { t } from './i18n.js'
22
33
  const err = (line) => process.stderr.write(`${line}\n`)
23
34
  const out = (line) => process.stdout.write(`${line}\n`)
24
35
 
25
- /**
26
- * repair 可修复的失败特征:问题出在"包的安装状态或版本适配"上,重装/升级
27
- * 插件包可能修复——
28
- * - 模块解析失败:包缺失/损坏/未安装 → 重装即愈;
29
- * - ESM 导出不匹配(does not provide an [export|import binding]):插件与
30
- * 当前 dsh API 版本不兼容,升级插件到适配版本可能修复(真实案例:
31
- * describe-image 隔离于 dsh-settings 导出变更)。修复失败不恢复、无损。
32
- * 注意:台账 reason 经 summarizeLine 截断过(160 字符),关键短语可能被
33
- * "…" 切断,因此导出不匹配的特征只匹配到 "does not provide an" 为止。
34
- */
35
36
  const REPAIRABLE_RE =
36
37
  /Cannot find package|could not be resolved|ERR_MODULE_NOT_FOUND|does not provide an( (?:export|import binding))?/i
38
+ const DUPLICATE_RE = /duplicate loader entry id/i
37
39
 
38
- function parseRepairArgs(args) {
39
- const opts = { id: undefined, profile: undefined, to: undefined, yes: false, dryRun: false }
40
- for (let i = 0; i < args.length; i++) {
41
- const a = args[i]
42
- if (a === '-y' || a === '--yes') opts.yes = true
43
- else if (a === '--dry-run') opts.dryRun = true
44
- else if (a === '--profile') {
45
- const v = args[++i]
46
- if (v === undefined) return { error: { key: 'updateUnknownFlag', params: { arg: '--profile' } } }
47
- opts.profile = v
48
- } else if (a.startsWith('--profile=')) opts.profile = a.slice('--profile='.length)
49
- else if (a === '--to') {
50
- const v = args[++i]
51
- if (v === undefined) return { error: { key: 'updateUnknownFlag', params: { arg: '--to' } } }
52
- opts.to = v
53
- } else if (a.startsWith('--to=')) opts.to = a.slice('--to='.length)
54
- else if (!a.startsWith('-') && opts.id === undefined) opts.id = a
55
- else return { error: { key: 'updateUnknownFlag', params: { arg: a } } }
40
+ const isRepairable = (reason) => REPAIRABLE_RE.test(reason ?? '') || DUPLICATE_RE.test(reason ?? '')
41
+
42
+ const readJsonIfExists = (path) => {
43
+ const raw = readIfExists(path)
44
+ if (raw === undefined) return undefined
45
+ try {
46
+ return JSON.parse(raw)
47
+ } catch {
48
+ return undefined
56
49
  }
57
- if (opts.to !== undefined && !/^[\w.+-]+$/.test(opts.to)) return { error: { key: 'updateToInvalid' } }
58
- return { opts }
50
+ }
51
+
52
+ /** 该 id 的 bundle 挂载来源(profile/home 层是 override,不算挂载来源)。 */
53
+ function bundleMountSources(known, id) {
54
+ return [
55
+ ...new Set(
56
+ known.rows.filter((r) => r.id === id && r.source !== 'profile' && r.source !== 'home').map((r) => r.source),
57
+ ),
58
+ ]
59
+ }
60
+
61
+ /** 从 profile 清单的 bundles 数组移除指定来源;没有变化返回 false。 */
62
+ function removeFromManifestBundles(profile, removeNames) {
63
+ const manifestPath = profileManifestPath(profile)
64
+ const manifest = readJsonIfExists(manifestPath)
65
+ const current = manifest?.dsh?.profile?.bundles
66
+ if (!Array.isArray(current)) return false
67
+ const next = current.filter((b) => !removeNames.includes(b))
68
+ if (next.length === current.length) return false
69
+ manifest.dsh.profile.bundles = next
70
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
71
+ return true
72
+ }
73
+
74
+ function askConfirm(question) {
75
+ const rl = createInterface({ input: process.stdin, output: process.stderr })
76
+ return rl.question(question).then(
77
+ (answer) => {
78
+ rl.close()
79
+ const a = answer.trim().toLowerCase()
80
+ return a === 'y' || a === 'yes'
81
+ },
82
+ () => {
83
+ rl.close()
84
+ return false
85
+ },
86
+ )
59
87
  }
60
88
 
61
89
  /**
62
- * @param {string[]} args
63
- * @param {{
64
- * spawn?: typeof spawnSync,
65
- * log?: (line: string) => void,
66
- * write?: (line: string) => void,
67
- * }} [hooks] spawn/log/write 可注入(测试)
68
- * @returns {Promise<number>} 退出码
90
+ * 对单条隔离记录执行修复动作。安装确认由调用方完成(单条路径确认、批量
91
+ * 路径整体确认后以 yes: true 调用)。
92
+ * @returns {Promise<{ code: number, outcome: 'repaired'|'deduped'|'skipped'|'failed' }>}
69
93
  */
70
- export async function cmdRepair(args, { spawn = spawnSync, log = err, write = out } = {}) {
71
- if (args.includes('-h') || args.includes('--help')) {
72
- out(t('helpText', {}))
73
- return 0
74
- }
75
- const { opts, error } = parseRepairArgs(args)
76
- if (error) {
77
- log(t(error.key, error.params))
78
- return 2
79
- }
94
+ async function repairEntry({ profile, entry, to = undefined, yes = false, tty = true, dryRun = false, spawn = spawnSync, log = err, write = out }) {
95
+ const id = entry.id
80
96
 
81
- // 台账定位:省略 --profile 时跨 profile 搜索;省略 id 时——
82
- // 恰好一条隔离记录 直接修它(最常见情况);
83
- // 多条 列出清单让用户挑(标记哪些可自动修复)。
84
- const ledger = loadLedger()
85
- let matches = []
86
- for (const [profile, entries] of Object.entries(ledger.profiles)) {
87
- if (opts.profile && profile !== opts.profile) continue
88
- for (const entry of entries ?? []) {
89
- if (opts.id === undefined || entry.id === opts.id) matches.push({ profile, entry })
90
- }
91
- }
92
- if (opts.id === undefined) {
93
- if (!matches.length) {
94
- log(t('noRecords'))
95
- return 0
97
+ // duplicate:自动去重(多 bundle 来源),来源不足给手动指引
98
+ if (DUPLICATE_RE.test(entry.reason ?? '')) {
99
+ const sources = bundleMountSources(collectKnownRows(profile), id)
100
+ if (sources.length < 2) {
101
+ log(t('repairDuplicate'))
102
+ return { code: 1, outcome: 'skipped' }
96
103
  }
97
- if (matches.length > 1) {
98
- log(t('repairPickOne', { count: matches.length }))
99
- for (const m of matches) {
100
- const repairable = REPAIRABLE_RE.test(m.entry.reason ?? '')
101
- log(` - ${m.entry.id}(${m.entry.name ?? '-'})${repairable ? '' : t('repairNotSupportedTag')}`)
104
+ const manifest = readJsonIfExists(profileManifestPath(profile))
105
+ const declared = manifest?.dsh?.profile?.bundles
106
+ const ordered = Array.isArray(declared)
107
+ ? [...sources].sort(
108
+ (a, b) =>
109
+ (declared.indexOf(a) < 0 ? 999 : declared.indexOf(a)) - (declared.indexOf(b) < 0 ? 999 : declared.indexOf(b)),
110
+ )
111
+ : sources
112
+ let keep = ordered[0]
113
+ if (!yes && !dryRun) {
114
+ if (!tty) {
115
+ log(t('updateNonInteractive'))
116
+ return { code: 1, outcome: 'failed' }
102
117
  }
103
- return 0
118
+ const rl = createInterface({ input: process.stdin, output: process.stderr })
119
+ log(t('repairDedupePick', { id }))
120
+ ordered.forEach((b, i) => log(`${i + 1}. ${b}${i === 0 ? t('repairDedupeDefault') : ''}`))
121
+ const answer = await rl.question(t('repairDedupeChoose'))
122
+ rl.close()
123
+ const pick = Math.min(Math.max(parseInt(answer, 10) || 1, 1), ordered.length)
124
+ keep = ordered[pick - 1]
104
125
  }
105
- opts.id = matches[0].entry.id
106
- }
107
- if (!matches.length) {
108
- log(t('repairEntryMissing', { id: opts.id }))
109
- return 1
110
- }
111
- if (matches.length > 1) {
112
- log(t('repairAmbiguous', { id: opts.id, profiles: matches.map((m) => m.profile).join(', ') }))
113
- return 2
126
+ const remove = ordered.filter((b) => b !== keep)
127
+ log(t('repairDedupePlan', { keep, remove: remove.join(', '), id }))
128
+ if (dryRun) {
129
+ log(t('dryRunNotice'))
130
+ return { code: 0, outcome: 'deduped' }
131
+ }
132
+ if (!removeFromManifestBundles(profile, remove)) {
133
+ log(t('repairDedupeNoManifest'))
134
+ return { code: 1, outcome: 'failed' }
135
+ }
136
+ const { restored } = restoreQuarantine(profile, [id], false)
137
+ if (restored.length) {
138
+ const e = restored[0]
139
+ write(`[dsh-safe] ${t('restored')} ${e.name ?? e.id} (id: ${e.id})`)
140
+ }
141
+ log(t('repairDedupeDone', { removed: remove.join(', '), keep }))
142
+ log(t('repairDone'))
143
+ return { code: 0, outcome: 'deduped' }
114
144
  }
115
- const { profile, entry } = matches[0]
116
- const name = entry.name ?? entry.id
117
145
 
118
- // 类别门禁:重复挂载是配置层问题(同一 id 多处挂载),重装无意义——
119
- // 但可以自动去重:从 profile 的 bundles 移除一个挂载来源
120
- if (/duplicate loader entry id/i.test(entry.reason ?? '')) {
121
- return dedupeForDuplicate({ id: opts.id, profile, opts, spawn, log, write })
122
- }
123
- // 只修"包的安装状态/版本适配"类
146
+ // 其它非包类失败:拒接并给针对性指引
124
147
  if (!REPAIRABLE_RE.test(entry.reason ?? '')) {
125
148
  log(t('repairUnsupported', { reason: summarizeLine(entry.reason) }))
126
- return 1
149
+ return { code: 1, outcome: 'skipped' }
127
150
  }
128
151
 
129
- const target = opts.to ?? 'latest'
130
- const spec = `${name}@${target}`
152
+ // 安装 + 恢复
153
+ const spec = `${entry.name ?? entry.id}@${to ?? 'latest'}`
131
154
  const spawnTarget = resolveDshSpawnTarget('dsh')
132
155
  const commandDesc = `dsh plugin --profile ${profile} add ${spec}`
133
- log(t('repairPlan', { profile, name, command: commandDesc }))
134
- if (opts.dryRun) {
156
+ log(t('repairPlan', { profile, name: entry.name ?? entry.id, command: commandDesc }))
157
+ if (dryRun) {
135
158
  log(t('dryRunNotice'))
136
- return 0
137
- }
138
- if (!opts.yes) {
139
- if (!process.stdin.isTTY) {
140
- log(t('updateNonInteractive'))
141
- return 1
142
- }
143
- const ok = await askConfirm(t('updateConfirm'))
144
- if (!ok) {
145
- log(t('updateAborted'))
146
- return 0
147
- }
159
+ return { code: 0, outcome: 'repaired' }
148
160
  }
149
161
 
150
162
  const { status } = spawn(spawnTarget.file, [...spawnTarget.prefix, 'plugin', '--profile', profile, 'add', spec], {
@@ -154,10 +166,10 @@ export async function cmdRepair(args, { spawn = spawnSync, log = err, write = ou
154
166
  })
155
167
  if (status !== 0) {
156
168
  log(t('repairInstallFailed', { code: status ?? '?' }))
157
- return status ?? 1
169
+ return { code: status ?? 1, outcome: 'failed' }
158
170
  }
159
171
 
160
- const { restored } = restoreQuarantine(profile, [opts.id], false)
172
+ const { restored } = restoreQuarantine(profile, [id], false)
161
173
  if (!restored.length) {
162
174
  log(t('noMatching'))
163
175
  } else {
@@ -168,7 +180,7 @@ export async function cmdRepair(args, { spawn = spawnSync, log = err, write = ou
168
180
  // 防复发:修复的插件若同时被多个 bundle 挂载(如聚合包已内置同一插件),
169
181
  // 恢复后下次启动会 duplicate——自动去重(交互选择保留来源,-y 保留先声明者)
170
182
  const knownAfter = collectKnownRows(profile)
171
- const sources = bundleMountSources(knownAfter, opts.id)
183
+ const sources = bundleMountSources(knownAfter, id)
172
184
  if (sources.length >= 2) {
173
185
  const manifest = readJsonIfExists(profileManifestPath(profile))
174
186
  const declared = manifest?.dsh?.profile?.bundles
@@ -179,9 +191,9 @@ export async function cmdRepair(args, { spawn = spawnSync, log = err, write = ou
179
191
  )
180
192
  : sources
181
193
  let keep = ordered[0]
182
- if (!opts.yes) {
194
+ if (!yes) {
183
195
  const rl = createInterface({ input: process.stdin, output: process.stderr })
184
- log(t('repairDedupePick', { id: opts.id }))
196
+ log(t('repairDedupePick', { id }))
185
197
  ordered.forEach((b, i) => log(`${i + 1}. ${b}${i === 0 ? t('repairDedupeDefault') : ''}`))
186
198
  const answer = await rl.question(t('repairDedupeChoose'))
187
199
  rl.close()
@@ -195,139 +207,239 @@ export async function cmdRepair(args, { spawn = spawnSync, log = err, write = ou
195
207
  }
196
208
 
197
209
  log(t('repairDone'))
198
- return 0
199
- }
200
-
201
- function askConfirm(question) {
202
- const rl = createInterface({ input: process.stdin, output: process.stderr })
203
- return rl.question(question).then(
204
- (answer) => {
205
- rl.close()
206
- const a = answer.trim().toLowerCase()
207
- return a === 'y' || a === 'yes'
208
- },
209
- () => {
210
- rl.close()
211
- return false
212
- },
213
- )
210
+ return { code: 0, outcome: 'repaired' }
214
211
  }
215
212
 
216
- const readJsonIfExists = (path) => {
217
- const raw = readIfExists(path)
218
- if (raw === undefined) return undefined
219
- try {
220
- return JSON.parse(raw)
221
- } catch {
222
- return undefined
213
+ function parseRepairArgs(args) {
214
+ const opts = { id: undefined, all: false, profile: undefined, to: undefined, yes: false, dryRun: false }
215
+ for (let i = 0; i < args.length; i++) {
216
+ const a = args[i]
217
+ if (a === '-y' || a === '--yes') opts.yes = true
218
+ else if (a === '--dry-run') opts.dryRun = true
219
+ else if (a === '--all') opts.all = true
220
+ else if (a === '--profile') {
221
+ const v = args[++i]
222
+ if (v === undefined) return { error: { key: 'updateUnknownFlag', params: { arg: '--profile' } } }
223
+ opts.profile = v
224
+ } else if (a.startsWith('--profile=')) opts.profile = a.slice('--profile='.length)
225
+ else if (a === '--to') {
226
+ const v = args[++i]
227
+ if (v === undefined) return { error: { key: 'updateUnknownFlag', params: { arg: '--to' } } }
228
+ opts.to = v
229
+ } else if (a.startsWith('--to=')) opts.to = a.slice('--to='.length)
230
+ else if (!a.startsWith('-') && opts.id === undefined) opts.id = a
231
+ else return { error: { key: 'repairUnknownArg', params: { arg: a } } }
223
232
  }
233
+ if (opts.all && opts.id !== undefined) return { error: { key: 'repairAllConflict' } }
234
+ if (opts.to !== undefined && !/^[\w.+-]+$/.test(opts.to)) return { error: { key: 'updateToInvalid' } }
235
+ return { opts }
224
236
  }
225
237
 
226
- /** id bundle 挂载来源(profile/home 层是 override,不算挂载来源)。 */
227
- function bundleMountSources(known, id) {
228
- return [
229
- ...new Set(
230
- known.rows.filter((r) => r.id === id && r.source !== 'profile' && r.source !== 'home').map((r) => r.source),
231
- ),
232
- ]
238
+ /** 台账定位:按 id / --all / 菜单三种形态收集修复目标。 */
239
+ function collectTargets(opts, ledger) {
240
+ const matches = []
241
+ for (const [profile, entries] of Object.entries(ledger.profiles)) {
242
+ if (opts.profile && profile !== opts.profile) continue
243
+ for (const entry of entries ?? []) {
244
+ if (opts.all || opts.id === undefined || entry.id === opts.id) matches.push({ profile, entry })
245
+ }
246
+ }
247
+ return matches
233
248
  }
234
249
 
235
- /** profile 清单的 bundles 数组移除指定来源;没有变化返回 false。 */
236
- function removeFromManifestBundles(profile, removeNames) {
237
- const manifestPath = profileManifestPath(profile)
238
- const manifest = readJsonIfExists(manifestPath)
239
- const current = manifest?.dsh?.profile?.bundles
240
- if (!Array.isArray(current)) return false
241
- const next = current.filter((b) => !removeNames.includes(b))
242
- if (next.length === current.length) return false
243
- manifest.dsh.profile.bundles = next
244
- writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
245
- return true
250
+ /** 批量修复:一次确认,逐条执行,汇总结果。返回失败的条数。 */
251
+ async function repairBatch(targets, { to = undefined, yes = false, dryRun = false, spawn = spawnSync, log = err, write = out }) {
252
+ const repairable = targets.filter((t) => isRepairable(t.entry.reason))
253
+ const unsupported = targets.filter((t) => !repairable.includes(t))
254
+ log(
255
+ t('repairBatchPlan', {
256
+ count: repairable.length,
257
+ ids: repairable.map((t) => t.entry.id).join(', ') || '-',
258
+ }),
259
+ )
260
+ if (unsupported.length) {
261
+ log(t('repairBatchSkip', { count: unsupported.length, ids: unsupported.map((t) => t.entry.id).join(', ') }))
262
+ }
263
+ if (dryRun) {
264
+ for (const t of repairable) {
265
+ await repairEntry({ profile: t.profile, entry: t.entry, to: to, yes: true, tty: true, dryRun: true, spawn, log, write })
266
+ }
267
+ log(t('dryRunNotice'))
268
+ return { failed: 0 }
269
+ }
270
+ if (!yes) {
271
+ if (!process.stdin.isTTY) {
272
+ log(t('updateNonInteractive'))
273
+ return { failed: targets.length }
274
+ }
275
+ const ok = await askConfirm(t('updateConfirm'))
276
+ if (!ok) {
277
+ log(t('updateAborted'))
278
+ return { failed: 0 }
279
+ }
280
+ }
281
+ let repaired = 0
282
+ let failed = 0
283
+ for (const t of repairable) {
284
+ const { code } = await repairEntry({ profile: t.profile, entry: t.entry, to: to, yes: true, tty: true, spawn, log, write })
285
+ if (code === 0) repaired++
286
+ else failed++
287
+ }
288
+ log(t('repairBatchDone', { repaired, failed }))
289
+ return { failed }
246
290
  }
247
291
 
248
292
  /**
249
- * duplicate 类的自动去重:同一 id 被多个 bundle 挂载时,从 profile 清单的
250
- * bundles 数组移除一个来源(保留的来源继续提供插件),并摘除无效的禁用行。
251
- * 编辑的是用户自己的 profile 清单(与 cordis.patch.yml 托管区块同信任级别),
252
- * 有确认环节、可逆(bundles 加回来即可)。
293
+ * @param {string[]} args
294
+ * @param {{
295
+ * spawn?: typeof spawnSync,
296
+ * log?: (line: string) => void,
297
+ * write?: (line: string) => void,
298
+ * }} [hooks]
299
+ * @returns {Promise<number>} 退出码
253
300
  */
254
- async function dedupeForDuplicate({ id, profile, opts, spawn, log, write }) {
255
- const known = collectKnownRows(profile)
256
- // 挂载来源只统计 bundle 层;profile/home 层的同 id 是 override,不是重复来源
257
- const sources = new Set()
258
- for (const row of known.rows) {
259
- if (row.id !== id) continue
260
- if (row.source === 'profile' || row.source === 'home') continue
261
- sources.add(row.source)
301
+ export async function cmdRepair(args, { spawn = spawnSync, log = err, write = out } = {}) {
302
+ if (args.includes('-h') || args.includes('--help')) {
303
+ out(t('helpText', {}))
304
+ return 0
262
305
  }
263
- const sourceList = [...sources]
264
- if (sourceList.length < 2) {
265
- // 重复不在 bundle 层(可能在 include 文件或用户层),自动去重帮不上,给指引
266
- log(t('repairDuplicate'))
267
- return 1
306
+ const { opts, error } = parseRepairArgs(args)
307
+ if (error) {
308
+ log(t(error.key, error.params))
309
+ return 2
268
310
  }
269
311
 
270
- const manifestPath = profileManifestPath(profile)
271
- const manifest = readJsonIfExists(manifestPath)
272
- const bundles = manifest?.dsh?.profile?.bundles
273
- if (!Array.isArray(bundles)) {
274
- log(t('repairDedupeNoManifest'))
275
- return 1
312
+ const ledger = loadLedger()
313
+ const matches = collectTargets(opts, ledger)
314
+
315
+ // --all:批量修复(一次确认,默认策略)
316
+ if (opts.all) {
317
+ if (!matches.length) {
318
+ log(t('noRecords'))
319
+ return 0
320
+ }
321
+ const { failed } = await repairBatch(matches, { to: opts.to, yes: opts.yes, dryRun: opts.dryRun, spawn, log, write })
322
+ return failed ? 1 : 0
276
323
  }
277
- // 按 bundles 数组声明顺序排序:先声明的是既有来源,缺省保留
278
- const ordered = [...sourceList].sort((a, b) => {
279
- const ia = bundles.indexOf(a)
280
- const ib = bundles.indexOf(b)
281
- return (ia < 0 ? 999 : ia) - (ib < 0 ? 999 : ib)
282
- })
283
324
 
284
- const keepDefault = ordered[0]
285
- const planLine = () => log(t('repairDedupePlan', { keep: keep, remove: remove.join(', '), id }))
286
- if (opts.dryRun) {
287
- log(t('repairDedupePlan', { keep: keepDefault, remove: ordered.slice(1).join(', '), id }))
288
- log(t('dryRunNotice'))
289
- return 0
325
+ // id:单条直接修;多条列菜单让用户挑
326
+ if (opts.id === undefined) {
327
+ if (!matches.length) {
328
+ log(t('noRecords'))
329
+ return 0
330
+ }
331
+ if (matches.length > 1) {
332
+ log(t('repairPickOne', { count: matches.length }))
333
+ for (const m of matches) {
334
+ const repairable = isRepairable(m.entry.reason)
335
+ log(` - ${m.entry.id}(${m.entry.name ?? '-'})${repairable ? '' : t('repairNotSupportedTag')}`)
336
+ }
337
+ return 0
338
+ }
339
+ opts.id = matches[0].entry.id
290
340
  }
291
341
 
292
- let keep
293
- if (!opts.yes && !process.stdin.isTTY) {
294
- log(t('updateNonInteractive'))
342
+ if (!matches.length) {
343
+ // duplicate 类失败不会产生台账条目(0.12.1 起的设计)——台账查无记录时,
344
+ // 按挂载来源直接支持去重:该 id 被 ≥2 个 bundle 挂载即视为重复挂载目标。
345
+ const candidates = opts.profile
346
+ ? [opts.profile]
347
+ : (() => {
348
+ try {
349
+ return readdirSync(join(dshHome(), 'profiles'), { withFileTypes: true })
350
+ .filter((e) => e.isDirectory())
351
+ .map((e) => e.name)
352
+ } catch {
353
+ return []
354
+ }
355
+ })()
356
+ for (const p of candidates) {
357
+ if (bundleMountSources(collectKnownRows(p), opts.id).length >= 2) {
358
+ const rows = collectKnownRows(p).rows.filter((r) => r.id === opts.id)
359
+ matches.push({
360
+ profile: p,
361
+ entry: { id: opts.id, name: rows[0]?.name ?? null, reason: 'duplicate loader entry id' },
362
+ })
363
+ break
364
+ }
365
+ }
366
+ }
367
+ if (!matches.length) {
368
+ log(t('repairEntryMissing', { id: opts.id }))
295
369
  return 1
296
370
  }
297
- if (opts.yes) {
298
- keep = keepDefault // -y:保留先声明的来源
299
- } else {
300
- const rl = createInterface({ input: process.stdin, output: process.stderr })
301
- log(t('repairDedupePick', { id }))
302
- ordered.forEach((b, i) => log(`${i + 1}. ${b}${i === 0 ? t('repairDedupeDefault') : ''}`))
303
- const answer = await rl.question(t('repairDedupeChoose'))
304
- rl.close()
305
- const pick = Math.min(Math.max(parseInt(answer, 10) || 1, 1), ordered.length)
306
- keep = ordered[pick - 1]
371
+ if (matches.length > 1) {
372
+ log(t('repairAmbiguous', { id: opts.id, profiles: matches.map((m) => m.profile).join(', ') }))
373
+ return 2
307
374
  }
308
- const remove = ordered.filter((b) => b !== keep)
309
- planLine()
375
+ const { profile, entry } = matches[0]
310
376
 
311
- const fresh = readJsonIfExists(manifestPath)
312
- const current = fresh?.dsh?.profile?.bundles
313
- if (!Array.isArray(current)) {
314
- log(t('repairDedupeNoManifest'))
315
- return 1
377
+ // 单条路径:安装前确认(dry-run 免确认)
378
+ if (!opts.dryRun && !opts.yes) {
379
+ if (!process.stdin.isTTY) {
380
+ log(t('updateNonInteractive'))
381
+ return 1
382
+ }
383
+ if (!(await askConfirm(t('updateConfirm')))) {
384
+ log(t('updateAborted'))
385
+ return 0
386
+ }
316
387
  }
317
- const next = current.filter((b) => !remove.includes(b))
318
- if (next.length === current.length) {
319
- log(t('repairDedupeNoManifest'))
320
- return 1
388
+ const { code } = await repairEntry({ profile, entry, to: opts.to, yes: opts.yes || !opts.dryRun ? true : false, tty: true, dryRun: opts.dryRun, spawn, log, write })
389
+ return code
390
+ }
391
+
392
+ /**
393
+ * `-r/--repair [dsh 参数…]`:批量修复全部可修复的隔离记录,再按包装模式
394
+ * 启动(与 -u 对称:位置参数全部是 dsh 启动参数)。
395
+ * @param {string[]} args
396
+ * @param {{
397
+ * spawn?: typeof spawnSync,
398
+ * boot?: (args: string[]) => Promise<number>,
399
+ * log?: (line: string) => void,
400
+ * write?: (line: string) => void,
401
+ * isTTY?: boolean,
402
+ * readStdin?: never,
403
+ * }} [hooks]
404
+ * @returns {Promise<number>} 退出码
405
+ */
406
+ export async function cmdRepairAndBoot(args, { boot, spawn = spawnSync, log = err, write = out, isTTY = process.stdin.isTTY } = {}) {
407
+ if (args.includes('-h') || args.includes('--help')) {
408
+ out(t('helpText', {}))
409
+ return 0
410
+ }
411
+ // 位置参数全部是 dsh 启动参数(修全部可修复记录);前缀旗标为 repair 选项
412
+ const opts = { profile: undefined, to: undefined, yes: false, dryRun: false }
413
+ let i = 0
414
+ for (; i < args.length; i++) {
415
+ const a = args[i]
416
+ if (a === '-y' || a === '--yes') opts.yes = true
417
+ else if (a === '--dry-run') opts.dryRun = true
418
+ else if (a === '--profile' && args[i + 1] !== undefined) opts.profile = args[++i]
419
+ else if (a.startsWith('--profile=')) opts.profile = a.slice('--profile='.length)
420
+ else if (a === '--to' && args[i + 1] !== undefined) opts.to = args[++i]
421
+ else if (a.startsWith('--to=')) opts.to = a.slice('--to='.length)
422
+ else break
423
+ }
424
+ if (opts.to !== undefined && !/^[\w.+-]+$/.test(opts.to)) {
425
+ log(t('updateToInvalid'))
426
+ return 2
321
427
  }
322
- fresh.dsh.profile.bundles = next
323
- writeFileSync(manifestPath, `${JSON.stringify(fresh, null, 2)}\n`)
428
+ const bootArgs = args.slice(i)
324
429
 
325
- const { restored } = restoreQuarantine(profile, [id], false)
326
- if (restored.length) {
327
- const e = restored[0]
328
- write(`[dsh-safe] ${t('restored')} ${e.name ?? e.id} (id: ${e.id})`)
430
+ const ledger = loadLedger()
431
+ const targets = []
432
+ for (const [profile, entries] of Object.entries(ledger.profiles)) {
433
+ if (opts.profile && profile !== opts.profile) continue
434
+ for (const entry of entries ?? []) targets.push({ profile, entry })
329
435
  }
330
- log(t('repairDedupeDone', { removed: remove.join(', '), keep }))
331
- log(t('repairDone'))
332
- return 0
436
+ if (!targets.length) {
437
+ log(t('noRecords'))
438
+ if (bootArgs.length) return boot(bootArgs)
439
+ return 0
440
+ }
441
+
442
+ const { failed } = await repairBatch(targets, { to: opts.to, yes: opts.yes, dryRun: opts.dryRun, spawn, log, write })
443
+ if (bootArgs.length) return boot(bootArgs)
444
+ return failed ? 1 : 0
333
445
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyzyn/dsh-safe",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "description": "dsh 启动保险丝:社区插件不兼容导致 dsh 启动失败时,自动禁用坏插件并重试",
5
5
  "type": "module",
6
6
  "license": "MIT",