dsh-plugin 1.1.2 → 1.2.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.
Files changed (110) hide show
  1. package/client/client.js +4465 -1442
  2. package/client/client.js.map +1 -1
  3. package/lib/http/routes.js +438 -22
  4. package/lib/index.js +1 -1
  5. package/lib/services/install/install.js +4 -0
  6. package/lib/services/install/npm-check.js +55 -0
  7. package/lib/services/{npm-resolve.js → install/npm-resolve.js} +7 -5
  8. package/lib/services/{preflight.js → install/preflight.js} +15 -4
  9. package/lib/services/{task-queue.js → install/task-queue.js} +155 -66
  10. package/lib/services/loader.js +56 -1
  11. package/lib/services/log.js +138 -0
  12. package/lib/services/probe.js +157 -0
  13. package/lib/services/{profile.js → profile/profile.js} +29 -1
  14. package/lib/services/settings.js +60 -0
  15. package/lib/types/http/routes.d.ts +1 -1
  16. package/lib/types/index.d.ts +1 -1
  17. package/lib/types/services/{install-types.d.ts → install/install-types.d.ts} +3 -0
  18. package/lib/types/services/{install.d.ts → install/install.d.ts} +5 -5
  19. package/lib/types/services/install/npm-check.d.ts +12 -0
  20. package/lib/types/services/{npm-resolve.d.ts → install/npm-resolve.d.ts} +2 -1
  21. package/lib/types/services/{task-queue.d.ts → install/task-queue.d.ts} +5 -1
  22. package/lib/types/services/loader.d.ts +14 -8
  23. package/lib/types/services/log.d.ts +49 -0
  24. package/lib/types/services/probe.d.ts +30 -0
  25. package/lib/types/services/{pending-restart.d.ts → profile/pending-restart.d.ts} +1 -1
  26. package/lib/types/services/{profile.d.ts → profile/profile.d.ts} +2 -0
  27. package/lib/types/services/settings.d.ts +24 -0
  28. package/package.json +1 -1
  29. package/src/client/components/PluginHubSection.tsx +341 -120
  30. package/src/client/components/{CatalogList.tsx → catalog/CatalogList.tsx} +11 -7
  31. package/src/client/components/{PluginCard.tsx → catalog/PluginCard.tsx} +5 -4
  32. package/src/client/components/layout/CatalogControls.tsx +80 -0
  33. package/src/client/components/{CatalogHeader.tsx → layout/CatalogHeader.tsx} +4 -4
  34. package/src/client/components/{CategoryTabs.tsx → layout/CategoryTabs.tsx} +3 -3
  35. package/src/client/components/layout/SectionTabs.tsx +60 -0
  36. package/src/client/components/{AboutModal.tsx → modals/AboutModal.tsx} +7 -7
  37. package/src/client/components/{HubUpdateModal.tsx → modals/HubUpdateModal.tsx} +5 -5
  38. package/src/client/components/modals/InstalledDetailModal.tsx +193 -0
  39. package/src/client/components/modals/LogsModal.tsx +301 -0
  40. package/src/client/components/modals/LogsPathModal.tsx +161 -0
  41. package/src/client/components/{NotificationsModal.tsx → modals/NotificationsModal.tsx} +47 -20
  42. package/src/client/components/{ProgressView.tsx → modals/ProgressView.tsx} +2 -2
  43. package/src/client/components/{modals.tsx → modals/modals.tsx} +117 -40
  44. package/src/client/components/{Dropdown.tsx → ui/Dropdown.tsx} +14 -6
  45. package/src/client/components/ui/Toggle.tsx +28 -0
  46. package/src/client/components/ui/icons.tsx +343 -0
  47. package/src/client/components/views/CustomInstallView.tsx +250 -0
  48. package/src/client/components/views/DiagnosticsView.tsx +172 -0
  49. package/src/client/components/views/InstalledView.tsx +328 -0
  50. package/src/client/components/views/LogsView.tsx +150 -0
  51. package/src/client/components/views/MarketView.tsx +66 -0
  52. package/src/client/components/views/SettingsView.tsx +273 -0
  53. package/src/client/data/catalog.ts +38 -0
  54. package/src/client/data/host.ts +107 -0
  55. package/src/client/data/hub.ts +41 -0
  56. package/src/client/hooks/useCatalog.ts +71 -115
  57. package/src/client/hooks/useIncrementalList.ts +46 -0
  58. package/src/client/hooks/useLanguage.ts +40 -0
  59. package/src/client/hooks/useSettings.ts +90 -0
  60. package/src/client/hooks/useTaskQueue.ts +156 -39
  61. package/src/client/locales.ts +358 -38
  62. package/src/client/logic/constants.ts +86 -0
  63. package/src/client/{lib → logic}/failures.ts +95 -74
  64. package/src/client/logic/install-command.ts +56 -0
  65. package/src/client/logic/installed.ts +207 -0
  66. package/src/client/logic/normalize.ts +52 -0
  67. package/src/client/logic/urls.ts +125 -0
  68. package/src/client/styles/CustomInstallView.module.css +191 -0
  69. package/src/client/styles/DiagnosticsView.module.css +231 -0
  70. package/src/client/styles/Dropdown.module.css +42 -41
  71. package/src/client/styles/Header.module.css +100 -132
  72. package/src/client/styles/InstalledView.module.css +447 -0
  73. package/src/client/styles/List.module.css +6 -0
  74. package/src/client/styles/LogsView.module.css +503 -0
  75. package/src/client/styles/Modal.module.css +352 -70
  76. package/src/client/styles/SectionTabs.module.css +142 -0
  77. package/src/client/styles/SettingsView.module.css +232 -0
  78. package/src/client/styles/Toggle.module.css +60 -0
  79. package/src/client/styles/tokens.module.css +1 -0
  80. package/src/client/types.ts +23 -3
  81. package/src/server/http/routes.ts +414 -22
  82. package/src/server/index.ts +1 -1
  83. package/src/server/services/{install-types.ts → install/install-types.ts} +3 -1
  84. package/src/server/services/{install.ts → install/install.ts} +5 -5
  85. package/src/server/services/install/npm-check.ts +53 -0
  86. package/src/server/services/{npm-resolve.ts → install/npm-resolve.ts} +7 -5
  87. package/src/server/services/{preflight.ts → install/preflight.ts} +16 -4
  88. package/src/server/services/{task-queue.ts → install/task-queue.ts} +157 -63
  89. package/src/server/services/loader.ts +55 -1
  90. package/src/server/services/log.ts +167 -0
  91. package/src/server/services/probe.ts +157 -0
  92. package/src/server/services/{pending-restart.ts → profile/pending-restart.ts} +1 -1
  93. package/src/server/services/{profile.ts → profile/profile.ts} +31 -1
  94. package/src/server/services/settings.ts +79 -0
  95. package/lib/services/install.js +0 -4
  96. package/src/client/components/CatalogControls.tsx +0 -108
  97. package/src/client/components/icons.tsx +0 -129
  98. package/src/client/lib/catalog.ts +0 -293
  99. package/src/client/lib/env.ts +0 -20
  100. /package/lib/services/{install-types.js → install/install-types.js} +0 -0
  101. /package/lib/services/{installed-versions.js → profile/installed-versions.js} +0 -0
  102. /package/lib/services/{pending-restart.js → profile/pending-restart.js} +0 -0
  103. /package/lib/services/{progress.js → profile/progress.js} +0 -0
  104. /package/lib/types/services/{preflight.d.ts → install/preflight.d.ts} +0 -0
  105. /package/lib/types/services/{installed-versions.d.ts → profile/installed-versions.d.ts} +0 -0
  106. /package/lib/types/services/{progress.d.ts → profile/progress.d.ts} +0 -0
  107. /package/src/client/{lib → logic}/format.ts +0 -0
  108. /package/src/client/{lib → logic}/renderMarkdown.ts +0 -0
  109. /package/src/server/services/{installed-versions.ts → profile/installed-versions.ts} +0 -0
  110. /package/src/server/services/{progress.ts → profile/progress.ts} +0 -0
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * 这是通用机制,不针对任何具体插件:只要作者发布了 repository 指向该
10
10
  * GitHub 仓库的 npm 包(scope 名与 GitHub 用户名是否一致无所谓),就能命中,
11
- * 从而把「git 直装必败」的插件切换到 npm 通道安装。命中结果带内存缓存,
11
+ * 从而把 git 分发不完整的插件切换到 npm 通道安装。命中结果带内存缓存,
12
12
  * 避免同一会话内重复查询 registry。
13
13
  */
14
14
  import { get } from 'node:https'
@@ -23,20 +23,22 @@ const REQUEST_TIMEOUT_MS = 8000
23
23
  * 反查 repo(`owner/repo`)对应的官方 npm 包名;未命中、网络异常或超时返回 null。
24
24
  * 返回 null 不代表仓库一定没有 npm 包,只代表本次未能确认 —— 调用方应保留
25
25
  * 原有错误路径,反查只是额外的一次尝试。
26
+ * @param registry - npm 镜像源地址(空串 = 官方 https://registry.npmjs.org)
26
27
  */
27
- export function resolveNpmPackage(repo: string): Promise<string | null> {
28
+ export function resolveNpmPackage(repo: string, registry = ''): Promise<string | null> {
28
29
  const key = repo.toLowerCase()
29
30
  if (cache.has(key)) return Promise.resolve(cache.get(key) ?? null)
30
- const name = searchRepo(repo)
31
+ const name = searchRepo(repo, registry)
31
32
  name.then((found) => cache.set(key, found)).catch(() => cache.set(key, null))
32
33
  return name
33
34
  }
34
35
 
35
36
  /** 用 npm search 接口按 repository 地址反查,并做铁证校验(包元数据必须指向该仓库)。 */
36
- function searchRepo(repo: string): Promise<string | null> {
37
+ function searchRepo(repo: string, registry: string): Promise<string | null> {
37
38
  const [owner, name] = repo.split('/')
38
39
  if (owner === undefined || name === undefined || name === '') return Promise.resolve(null)
39
- const url = `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(`repository:${owner}/${name}`)}&size=10`
40
+ const base = registry === '' ? 'https://registry.npmjs.org' : registry.replace(/\/+$/, '')
41
+ const url = `${base}/-/v1/search?text=${encodeURIComponent(`repository:${owner}/${name}`)}&size=10`
40
42
  return new Promise((resolve) => {
41
43
  const req = get(url, { timeout: REQUEST_TIMEOUT_MS }, (res) => {
42
44
  if (res.statusCode !== 200) {
@@ -17,10 +17,14 @@ import { tmpdir } from 'node:os'
17
17
  import { join } from 'node:path'
18
18
  import { pipeline } from 'node:stream/promises'
19
19
  import { promisify } from 'node:util'
20
- import { githubRepoOf } from './profile.ts'
20
+ import { githubRepoOf } from '../profile/profile.ts'
21
21
 
22
22
  const execFileAsync = promisify(execFile)
23
23
 
24
+ /** 单次网络操作超时(ms):git ls-remote / codeload 下载。网络不可达时不能无限挂起,
25
+ * 否则 `/install` 请求永远不返回、任务不入队、前端进度卡 0%。超时后放行(交给装后校验)。 */
26
+ const PREFLIGHT_TIMEOUT_MS = 15_000
27
+
24
28
  /** 预检结果:ok=false 表示分发改入口文件缺失,missing 为该文件在包内的相对路径。 */
25
29
  export interface PreflightResult {
26
30
  ok: boolean
@@ -33,7 +37,10 @@ export async function preflightTarget(target: string): Promise<PreflightResult>
33
37
  const [owner, repo] = source.split('/')
34
38
  let commit = ''
35
39
  try {
36
- const { stdout } = await execFileAsync('git', ['ls-remote', `https://github.com/${owner}/${repo}.git`, 'HEAD'])
40
+ const { stdout } = await execFileAsync('git', ['ls-remote', `https://github.com/${owner}/${repo}.git`, 'HEAD'], {
41
+ timeout: PREFLIGHT_TIMEOUT_MS,
42
+ maxBuffer: 1024 * 1024,
43
+ })
37
44
  commit = stdout.split(/\s+/)[0] ?? ''
38
45
  } catch {
39
46
  return { ok: true, missing: null }
@@ -63,13 +70,15 @@ export async function preflightTarget(target: string): Promise<PreflightResult>
63
70
 
64
71
  function download(url: string, dest: string): Promise<void> {
65
72
  return new Promise((resolve, reject) => {
66
- get(url, (res) => {
73
+ const req = get(url, { timeout: PREFLIGHT_TIMEOUT_MS }, (res) => {
67
74
  if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 303) {
68
75
  res.resume()
69
76
  if (res.headers.location) {
70
77
  void download(res.headers.location, dest).then(resolve, reject)
71
78
  return
72
79
  }
80
+ reject(new Error('download failed: redirect without location'))
81
+ return
73
82
  }
74
83
  if (res.statusCode !== 200) {
75
84
  res.resume()
@@ -77,7 +86,10 @@ function download(url: string, dest: string): Promise<void> {
77
86
  return
78
87
  }
79
88
  void pipeline(res, createWriteStream(dest)).then(resolve, reject)
80
- }).on('error', reject)
89
+ })
90
+ // 网络不可达时 connect/响应可能无限挂起:超时销毁,避免预检卡死(放行交给装后校验)
91
+ req.on('timeout', () => req.destroy(new Error(`download timeout after ${PREFLIGHT_TIMEOUT_MS}ms`)))
92
+ req.on('error', reject)
81
93
  })
82
94
  }
83
95
 
@@ -12,11 +12,13 @@ import { readFileSync, statSync } from 'node:fs'
12
12
  import { dirname, join, resolve } from 'node:path'
13
13
  import type { InstallResult, InstallTask, Invocation, QueueItem } from './install-types.ts'
14
14
  import { CAPTURE_LIMIT_BYTES, MAX_TASKS, MAX_TASK_LINES } from './install-types.ts'
15
- import { cleanLine, estimateProgress } from './progress.ts'
16
- import type { LoaderHandle } from './loader.ts'
17
- import { removeLoadedEntry } from './loader.ts'
18
- import { addPendingRestart, clearPendingRestart } from './pending-restart.ts'
19
- import { addAllowBuildsKey, githubRepoOf, parseAllowBuildsKey, profileDirectory } from './profile.ts'
15
+ import { npmTooLowMarker } from './npm-check.ts'
16
+ import { cleanLine, estimateProgress } from '../profile/progress.ts'
17
+ import type { LoaderHandle } from '../loader.ts'
18
+ import { removeLoadedEntry } from '../loader.ts'
19
+ import { addPendingRestart, clearPendingRestart } from '../profile/pending-restart.ts'
20
+ import { addAllowBuildsKey, githubRepoOf, parseAllowBuildsKey, profileDirectory } from '../profile/profile.ts'
21
+ import { appendLog } from '../log.ts'
20
22
 
21
23
  /** In-memory task registry, keyed by task id. */
22
24
  const tasks = new Map<number, InstallTask>()
@@ -167,6 +169,8 @@ export function startPluginMutation(options: {
167
169
  target: string
168
170
  timeoutMs?: number
169
171
  env?: NodeJS.ProcessEnv
172
+ /** 全局 npm 安装(官方 `npm install -g <pkgs>`):非空时执行全局安装,不进任何 profile、无需宿主重启 */
173
+ globalNpm?: string[]
170
174
  /** 待重启行的展示目标(owner/repo):卸载时用于把 npm 包名映射回仓库名 */
171
175
  displayTarget?: string
172
176
  /** 运行中 loader:卸载成功后主动移除条目、立即生效(缺失时卸载仍需重启清理) */
@@ -174,7 +178,7 @@ export function startPluginMutation(options: {
174
178
  /** 入队前已尝试的安装方式(npm registry 反查等):失败提 Issue 时如实展示;实际执行的命令由 spawn 时追加 */
175
179
  attempts?: string[]
176
180
  }): InstallTask {
177
- const task: InstallTask = { id: nextTaskId, target: options.target, displayTarget: options.displayTarget, action: options.action, status: 'pending', timedOut: false, exitCode: null, progress: 0, lines: [], attempts: options.attempts ?? [], needsRestart: false }
181
+ const task: InstallTask = { id: nextTaskId, target: options.target, displayTarget: options.displayTarget, globalNpm: options.globalNpm, action: options.action, status: 'pending', timedOut: false, exitCode: null, progress: 0, lines: [], attempts: options.attempts ?? [], needsRestart: false }
178
182
  nextTaskId = nextTaskId >= Number.MAX_SAFE_INTEGER ? 1 : nextTaskId + 1
179
183
  tasks.set(task.id, task)
180
184
  if (tasks.size > MAX_TASKS) {
@@ -187,6 +191,15 @@ export function startPluginMutation(options: {
187
191
  })
188
192
  }
189
193
  queue.push({ task, options: { ...options } })
194
+ // 系统日志:记录任务入队(安装/卸载开始)
195
+ const category = options.action === 'add' ? 'install' : 'uninstall'
196
+ appendLog(options.profile, {
197
+ at: Date.now(),
198
+ level: 'info',
199
+ category,
200
+ event: `${category}.start`,
201
+ message: `${options.action === 'add' ? '开始安装' : '开始卸载'} ${options.displayTarget ?? options.target}`,
202
+ })
190
203
  pumpQueue()
191
204
  return task
192
205
  }
@@ -200,6 +213,34 @@ function pumpQueue(): void {
200
213
  task.status = 'running'
201
214
  void runPluginMutation({ ...options, task }).finally(() => {
202
215
  runningChildren.delete(task.id)
216
+ // 系统日志:任务终态(成功/失败/取消),按动作归类安装/卸载日志
217
+ const show = task.displayTarget ?? task.target
218
+ const category = task.action === 'add' ? 'install' : 'uninstall'
219
+ if (task.status === 'done') {
220
+ appendLog(options.profile, {
221
+ at: Date.now(),
222
+ level: 'success',
223
+ category,
224
+ event: `${category}.done`,
225
+ message: `${task.action === 'add' ? '安装成功' : '卸载成功'} ${show}${task.needsRestart ? '(待重启生效)' : ''}`,
226
+ })
227
+ } else if (task.status === 'failed') {
228
+ appendLog(options.profile, {
229
+ at: Date.now(),
230
+ level: 'error',
231
+ category,
232
+ event: `${category}.fail`,
233
+ message: `${task.action === 'add' ? '安装失败' : '卸载失败'} ${show}`,
234
+ })
235
+ } else if (task.status === 'cancelled') {
236
+ appendLog(options.profile, {
237
+ at: Date.now(),
238
+ level: 'warn',
239
+ category,
240
+ event: 'task.cancel',
241
+ message: `已取消 ${show}`,
242
+ })
243
+ }
203
244
  // 已终态的任务移出队列:既防 queue 数组无限增长(内存泄漏),也让下一轮 pump 干净
204
245
  const idx = queue.findIndex((it) => it.task === task)
205
246
  if (idx >= 0) queue.splice(idx, 1)
@@ -223,24 +264,37 @@ function spawnMutation(options: {
223
264
  displayTarget?: string
224
265
  /** 运行中 loader:卸载成功后主动移除条目、立即生效(缺失时卸载仍需重启清理) */
225
266
  uninstallLoader?: LoaderHandle
267
+ /** 全局 npm 安装(官方 `npm install -g <pkgs>`):非空时执行全局安装,不进任何 profile、无需宿主重启 */
268
+ globalNpm?: string[]
226
269
  }): Promise<InstallResult> {
227
- const { action, profile, target, timeoutMs = 5 * 60 * 1000, env, task, displayTarget, uninstallLoader } = options
228
- const invocation = cliInvocation()
229
- const args = [...invocation.prefixArgs, 'plugin', '--profile', profile, action, target]
230
- // 记录实际执行的命令(npm 通道显示包名,git 通道显示 HTTPS 源):失败提 Issue 时
231
- // 「已尝试的安装方式」如实展示完整命令链,作者一眼看清我们跑过什么
232
- const executed = `dsh plugin --profile ${profile} ${action} ${target}`
270
+ const { action, profile, target, timeoutMs = 5 * 60 * 1000, env, task, displayTarget, uninstallLoader, globalNpm } = options
271
+ // 全局 npm 安装:直接 spawn 本机 npm(`npm install -g <pkgs>`),不是 dsh plugin 命令
272
+ const isGlobalNpm = (globalNpm ?? []).length > 0
273
+ const invocation = isGlobalNpm
274
+ ? { file: 'npm', prefixArgs: [], cwd: process.cwd(), useShell: process.platform === 'win32' }
275
+ : cliInvocation()
276
+ const args = isGlobalNpm
277
+ ? ['install', '-g', ...(globalNpm ?? [])]
278
+ : [...invocation.prefixArgs, 'plugin', '--profile', profile, action, target]
279
+ // 记录实际执行的命令(npm 通道显示包名,git 通道显示 HTTPS 源),
280
+ // 失败提 Issue 时作为「已尝试的安装方式」随附
281
+ const executed = isGlobalNpm
282
+ ? `npm install -g ${(globalNpm ?? []).join(' ')}`
283
+ : `dsh plugin --profile ${profile} ${action} ${target}`
233
284
  if (task && !task.attempts.includes(executed)) {
234
285
  task.attempts.push(executed)
235
286
  }
236
- return new Promise((resolvePromise) => {
287
+ // 单次 spawn 并捕获结果:流式输出打日志 + 超时/取消兜底,close 后 resolve。
288
+ // 不做任何终态后处理(exitCode/status/needsRestart 由下方统一收尾),
289
+ // 这样全局 npm 首次失败后可以干净地换参数重试一次。
290
+ const spawnOnce = (attemptArgs: string[]): Promise<InstallResult> => new Promise((resolveOnce) => {
237
291
  let stdout = ''
238
292
  let stderr = ''
239
293
  let timedOut = false
240
294
  let settled = false
241
295
  let child: ReturnType<typeof spawn>
242
296
  try {
243
- child = spawn(invocation.file, args, {
297
+ child = spawn(invocation.file, attemptArgs, {
244
298
  cwd: invocation.cwd,
245
299
  env,
246
300
  shell: invocation.useShell,
@@ -255,7 +309,7 @@ function spawnMutation(options: {
255
309
  task.exitCode = null
256
310
  pushLine(task, `[error] ${error instanceof Error ? error.message : String(error)}`)
257
311
  }
258
- resolvePromise({
312
+ resolveOnce({
259
313
  exitCode: null,
260
314
  timedOut: false,
261
315
  error: error instanceof Error ? error.message : String(error),
@@ -272,9 +326,8 @@ function spawnMutation(options: {
272
326
  let exitWatch: ReturnType<typeof setTimeout> | undefined
273
327
  let forceSettle: ReturnType<typeof setTimeout> | undefined
274
328
 
275
- // 唯一收尾入口:close / error / 兜底超时 三者只放行一次,
276
- // 保证 runPluginMutation 必然 resolve、队列 worker 必然继续推进
277
- const settle = (result: InstallResult): void => {
329
+ // 唯一收尾入口:close / error / 兜底超时 三者只放行一次,确保任务持续推进
330
+ const settleOnce = (result: InstallResult): void => {
278
331
  if (settled) return
279
332
  settled = true
280
333
  if (timer !== undefined) clearTimeout(timer)
@@ -282,7 +335,7 @@ function spawnMutation(options: {
282
335
  if (exitWatch !== undefined) clearTimeout(exitWatch)
283
336
  if (forceSettle !== undefined) clearTimeout(forceSettle)
284
337
  if (task) runningChildren.delete(task.id)
285
- resolvePromise(result)
338
+ resolveOnce(result)
286
339
  }
287
340
 
288
341
  timer = setTimeout(() => {
@@ -298,7 +351,7 @@ function spawnMutation(options: {
298
351
  if (kind === 'stdout') stdout = (stdout + text).slice(-CAPTURE_LIMIT_BYTES)
299
352
  else stderr = (stderr + text).slice(-CAPTURE_LIMIT_BYTES)
300
353
  if (task) {
301
- // 原生透传 pnpm 输出:stdout/stderr 原样入日志,不做格式化,保证报错信息完整可见
354
+ // 原生透传 pnpm/npm 输出:stdout/stderr 原样入日志,不做格式化,保证报错信息完整可见
302
355
  for (const line of text.split(/\r?\n|\r/)) {
303
356
  if (line.trim() !== '') pushLine(task, line.trimEnd())
304
357
  }
@@ -310,7 +363,7 @@ function spawnMutation(options: {
310
363
  child.once('exit', () => {
311
364
  // dsh 内部会 fork pnpm:pnpm 退出后仍攥着 stdout/stderr 管道时,
312
365
  // close 事件不会到来。exit 后给 close 一段宽限,未按时触发则整组清理强制结束,
313
- // 保证任务必然进入终态、后续排队任务自动启动。
366
+ // 确保任务进入终态、后续排队任务自动启动。
314
367
  exitWatch = setTimeout(() => {
315
368
  if (settled) return
316
369
  if (task && task.status !== 'cancelled') pushLine(task, '[stale pipe] force closing child')
@@ -324,7 +377,7 @@ function spawnMutation(options: {
324
377
  task.timedOut = true
325
378
  pushLine(task, '[timed out]')
326
379
  }
327
- settle({ exitCode: null, timedOut: true, error: 'child failed to close', stdout, stderr })
380
+ settleOnce({ exitCode: null, timedOut: true, error: 'child failed to close', stdout, stderr })
328
381
  }, 5_000)
329
382
  }, 3_000)
330
383
  })
@@ -335,43 +388,62 @@ function spawnMutation(options: {
335
388
  task.exitCode = null
336
389
  pushLine(task, `[error] ${error.message}`)
337
390
  }
338
- settle({ exitCode: null, timedOut: false, error: error.message, stdout, stderr })
391
+ settleOnce({ exitCode: null, timedOut: false, error: error.message, stdout, stderr })
339
392
  })
340
393
 
341
- child.once('close', async (code) => {
342
- try {
343
- if (task) {
344
- task.exitCode = code
345
- task.timedOut = timedOut
346
- if (task.status !== 'cancelled') {
347
- task.status = timedOut || code !== 0 ? 'failed' : 'done'
348
- if (task.status === 'done') {
349
- task.progress = 100
350
- if (action === 'remove' && uninstallLoader) {
351
- // 卸载成功 → 主动从运行中 loader 停用该包条目;
352
- // 仅当宿主从未加载过它(磁盘已干净)才判「无需重启」;
353
- // 只要曾在 loader 中存活(停用过 live entry)就仍要求重启——
354
- // 带 UI 的插件(侧边栏面板等宿主启动时渲染的槽位)disable 后不会
355
- // 主动消失,重启才能立即摘除面板
356
- const removed = await removeLoadedEntry(uninstallLoader, target)
357
- task.needsRestart = !removed
358
- if (removed) clearPendingRestart(displayTarget ?? target)
359
- else addPendingRestart(displayTarget ?? target, 'uninstall')
360
- } else {
361
- // 安装成功(或卸载但无 loader 引用)→ 登记待重启:
362
- // 插件要宿主重启才会挂载/卸载干净,重启前一直提醒;展示目标用 displayTarget(owner/repo)
363
- task.needsRestart = true
364
- addPendingRestart(displayTarget ?? target, action === 'add' ? 'install' : 'uninstall')
365
- }
366
- }
367
- pushLine(task, timedOut ? '[timed out]' : `[exit ${code ?? '?'}]`)
394
+ child.once('close', (code) => {
395
+ settleOnce({ exitCode: code, timedOut, error: null, stdout, stderr })
396
+ })
397
+ })
398
+
399
+ return (async () => {
400
+ let result = await spawnOnce(args)
401
+ // npm 11 的 arborist peer-set bug(`Cannot read properties of null (reading 'children')`,npm/cli#9911):
402
+ // 某些包的 peerDependencies 用「双段 prerelease 范围」(如 dsh-tui@0.9.0 的 `^0.1.0-rc.6 || ^0.1.1-rc.1`,
403
+ // 26 个必需 peer 全是这种形状)会让 `npm install -g` 在解析阶段直接崩溃 —— 退出码 1、什么都没装,
404
+ // 与是不是从我们界面发起无关(终端里同样复现)。首次失败后自动带 `--legacy-peer-deps` 重试一次:
405
+ // 跳过 peer 自动解析即可绕过该 bug(peer 通常由同装的 @deepseek-ai/dsh 依赖树天然提供)。
406
+ // 二次尝试仍失败则保留其错误信息,不掩盖真正的原因。
407
+ if (isGlobalNpm && result.exitCode !== 0 && !result.timedOut && task?.status !== 'cancelled') {
408
+ const retryArgs = ['install', '-g', '--legacy-peer-deps', ...(globalNpm ?? [])]
409
+ const retryExecuted = `npm install -g --legacy-peer-deps ${(globalNpm ?? []).join(' ')}`
410
+ if (task && !task.attempts.includes(retryExecuted)) task.attempts.push(retryExecuted)
411
+ if (task) pushLine(task, '[npm] peer-set resolution crashed npm (known npm bug) — retrying with --legacy-peer-deps')
412
+ result = await spawnOnce(retryArgs)
413
+ }
414
+ // 统一终态后处理:exitCode/status/needsRestart 以最后一次尝试为准
415
+ if (task) {
416
+ task.exitCode = result.exitCode
417
+ task.timedOut = result.timedOut
418
+ if (task.status !== 'cancelled') {
419
+ task.status = result.timedOut || result.exitCode !== 0 ? 'failed' : 'done'
420
+ if (task.status === 'done') {
421
+ task.progress = 100
422
+ if (isGlobalNpm) {
423
+ // 全局 npm 安装:装的是本机 CLI 工具(如 dsh-tui),不进任何 profile,无需宿主重启
424
+ task.needsRestart = false
425
+ } else if (action === 'remove' && uninstallLoader) {
426
+ // 卸载成功 → 主动从运行中 loader 停用该包条目;
427
+ // 仅当宿主从未加载过它(磁盘已干净)才判「无需重启」;
428
+ // 只要曾在 loader 中存活(停用过 live entry)就仍要求重启——
429
+ // 带 UI 的插件(侧边栏面板等宿主启动时渲染的槽位)disable 后不会
430
+ // 主动消失,重启才能立即摘除面板
431
+ const removed = await removeLoadedEntry(uninstallLoader, target)
432
+ task.needsRestart = !removed
433
+ if (removed) clearPendingRestart(displayTarget ?? target)
434
+ else addPendingRestart(displayTarget ?? target, 'uninstall')
435
+ } else {
436
+ // 安装成功(或卸载但无 loader 引用)→ 登记待重启:
437
+ // 插件要宿主重启才会挂载/卸载干净,重启前一直提醒;展示目标用 displayTarget(owner/repo)
438
+ task.needsRestart = true
439
+ addPendingRestart(displayTarget ?? target, action === 'add' ? 'install' : 'uninstall')
368
440
  }
369
441
  }
370
- } finally {
371
- settle({ exitCode: code, timedOut, error: null, stdout, stderr })
442
+ pushLine(task, result.timedOut ? '[timed out]' : `[exit ${result.exitCode ?? '?'}]`)
372
443
  }
373
- })
374
- })
444
+ }
445
+ return result
446
+ })()
375
447
  }
376
448
 
377
449
  /**
@@ -427,6 +499,21 @@ function ignoredBuildKeys(output: string): string[] {
427
499
  .filter((s) => s !== '')
428
500
  }
429
501
 
502
+ /** npm arborist edgesOut 崩溃 + 本机 npm 版本过低 → 把 [npm-too-low] 标记追加到任务输出,
503
+ * 前端据此展示「本机 npm 版本过低」的准确原因 —— 避免该报错被外层 ERR_PNPM_PREPARE_PACKAGE
504
+ * 误判成插件打包/分发问题、误导用户提 Issue。检测逻辑在独立的 npm-check.ts(本机 npm 环境职责)。 */
505
+ function annotateNpmTooLow(result: InstallResult, options: {
506
+ action: 'add' | 'remove'
507
+ task?: InstallTask
508
+ env?: NodeJS.ProcessEnv
509
+ }): InstallResult {
510
+ if (options.action !== 'add' || result.exitCode === 0 || result.timedOut) return result
511
+ const line = npmTooLowMarker(`${result.stderr}\n${result.stdout}`, options.env)
512
+ if (line === null) return result
513
+ if (options.task && options.task.status !== 'cancelled') pushLine(options.task, line)
514
+ return { ...result, stderr: `${result.stderr}\n${line}`, error: result.error ? `${result.error}\n${line}` : line }
515
+ }
516
+
430
517
  /**
431
518
  * Run a plugin mutation with one recovery path: when `add` fails because
432
519
  * pnpm's allowBuilds gate blocks a build script — either the git-hosted
@@ -447,9 +534,13 @@ export async function runPluginMutation(options: {
447
534
  displayTarget?: string
448
535
  /** 运行中 loader:卸载成功后主动移除条目、立即生效(缺失时卸载仍需重启清理) */
449
536
  uninstallLoader?: LoaderHandle
537
+ /** 全局 npm 安装(官方 `npm install -g <pkgs>`):非空时执行全局安装,不进任何 profile、无需宿主重启 */
538
+ globalNpm?: string[]
450
539
  }): Promise<InstallResult> {
451
- const result = await spawnMutation(options)
452
- if (options.action === 'add' && result.exitCode !== 0 && !result.timedOut) {
540
+ let result = await spawnMutation(options)
541
+ // allowBuilds 放行 / 装后入口校验都是 profile 专属(pnpm 装进 profile 的场景);
542
+ // 全局 npm 安装直接走 npm,无 pnpm allowBuilds 拦截、也不进 profile,跳过这两类恢复
543
+ if (options.action === 'add' && result.exitCode !== 0 && !result.timedOut && (options.globalNpm ?? []).length === 0) {
453
544
  const output = `${result.stderr}\n${result.stdout}`
454
545
  // git 源:pnpm 打印的 key@url 提示
455
546
  if (output.includes('ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED')) {
@@ -463,14 +554,15 @@ export async function runPluginMutation(options: {
463
554
  pushLine(options.task, `[allow build] ${key}`)
464
555
  }
465
556
  addAllowBuildsKey(options.profile, key)
466
- return spawnMutation(options)
557
+ result = await spawnMutation(options)
467
558
  }
468
559
  }
469
560
  // 依赖原生模块/构建脚本被 pnpm v11 拦截(ERR_PNPM_IGNORED_BUILDS):git 与 npm 源都会出现。
470
561
  // allowBuilds 的 key 是输出里列出的 name@version(如 node-pty@1.1.0),逐个放行后重试一次;
471
562
  // 输出解析不到时回退用目标名(插件自身构建脚本被拦的 npm 场景)。
472
- if (output.includes('ERR_PNPM_IGNORED_BUILDS')) {
473
- const keys = ignoredBuildKeys(output)
563
+ // 用重试后的最终结果判断:git 源放行 prepare 后可能又在依赖层撞上原生构建拦截。
564
+ if (result.exitCode !== 0 && !result.timedOut && `${result.stderr}\n${result.stdout}`.includes('ERR_PNPM_IGNORED_BUILDS')) {
565
+ const keys = ignoredBuildKeys(`${result.stderr}\n${result.stdout}`)
474
566
  if (keys.length === 0 && githubRepoOf(options.target) === null) keys.push(options.target)
475
567
  if (keys.length > 0) {
476
568
  if (options.task) {
@@ -479,13 +571,14 @@ export async function runPluginMutation(options: {
479
571
  pushLine(options.task, `[allow build] ${keys.join(', ')}`)
480
572
  }
481
573
  for (const key of keys) addAllowBuildsKey(options.profile, key)
482
- return spawnMutation(options)
574
+ result = await spawnMutation(options)
483
575
  }
484
576
  }
485
577
  }
486
578
  // pnpm 安装本身成功,但目标包入口文件缺失(git 分发缺构建产物)→ 判为失败:
487
- // 撤销刚登记的待重启,避免用户重启时宿主加载残缺包直接崩溃
488
- if (options.action === 'add' && result.exitCode === 0 && !result.timedOut) {
579
+ // 撤销刚登记的待重启,避免用户重启时宿主加载残缺包直接崩溃。
580
+ // 全局 npm 安装不进 profile(profile deps 里没有这些包),跳过入口校验
581
+ if (options.action === 'add' && result.exitCode === 0 && !result.timedOut && (options.globalNpm ?? []).length === 0) {
489
582
  const verified = verifyInstalledEntry(options.profile, options.target)
490
583
  if (verified.name !== null && verified.missing !== null) {
491
584
  clearPendingRestart(options.displayTarget ?? options.target)
@@ -499,5 +592,6 @@ export async function runPluginMutation(options: {
499
592
  return { exitCode: 1, timedOut: false, error: `entry file missing: ${verified.missing}`, stdout: result.stdout, stderr: `${result.stderr}\n${detail}` }
500
593
  }
501
594
  }
502
- return result
595
+ // npm arborist edgesOut 崩溃 + 本机 npm 版本过低 → 追加 [npm-too-low] 标记,前端据此给准确原因
596
+ return annotateNpmTooLow(result, options)
503
597
  }
@@ -6,6 +6,9 @@
6
6
  * 运行中 loader 的读取与停用:卸载成功后对匹配条目做 live-disable,
7
7
  * 使卸载立即生效(刷新页面不再加载已卸载的 client bundle,也无需重启)。
8
8
  */
9
+ import { readFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import { profileDirectory } from './profile/profile.ts'
9
12
 
10
13
  /**
11
14
  * 运行中 loader 的最小接口:卸载成功后即时移除条目用。
@@ -36,6 +39,19 @@ export function dumpLoaderEntries(loader: LoaderHandle | undefined): Array<{ id:
36
39
  return entries
37
40
  }
38
41
 
42
+ /**
43
+ * 判断某 npm 包名是否已加载进运行中 loader(宽匹配:条目名存在别名变体)。
44
+ * 官方 `ctx.loader.entries()` 遍历整棵树(reference.md §1.3),条目名 == 插件作者声明的名字。
45
+ * 安装完成但未重启时条目不在 loader → 返回 false,UI 据此标「待重启/未加载」。
46
+ */
47
+ export function isEntryLoaded(loader: LoaderHandle | undefined, name: string): boolean {
48
+ if (!loader) return false
49
+ for (const entry of Array.from(loader.entries())) {
50
+ if (nameMatches(entry.options?.name, name)) return true
51
+ }
52
+ return false
53
+ }
54
+
39
55
  /**
40
56
  * 卸载目标(npm 包名,如 `@scope/widget`)与 loader 条目名的匹配。
41
57
  * loader 条目名由插件作者/工具写入,形式不可控,常见变体:
@@ -43,7 +59,8 @@ export function dumpLoaderEntries(loader: LoaderHandle | undefined): Array<{ id:
43
59
  * - 去 `@` 前缀:`scope/widget`
44
60
  * - 去 scope 的短名:`widget`
45
61
  * - scope 分隔符变 `-`:`scope-widget`
46
- * 因此归一化后比较全串与短名两个维度。profile 内包名唯一,宽松匹配不会误伤其它包。
62
+ * - 包内模块路径:`widget/extensions/dsh/index.js`(bundle patch 的 name 常写成模块路径)
63
+ * 因此归一化后比较全串、短名、路径前缀三个维度。profile 内包名唯一,宽松匹配不会误伤其它包。
47
64
  */
48
65
  function nameMatches(entryName: string | undefined, target: string): boolean {
49
66
  if (!entryName) return false
@@ -60,6 +77,12 @@ function nameMatches(entryName: string | undefined, target: string): boolean {
60
77
  // 3) 反向变体:目标短名可能就是条目的完整形式(条目 `scope-widget`,
61
78
  // 目标短名 `widget` 是它的尾段)——用「条目名以短名结尾」收口,避免误伤。
62
79
  if (tShort.length >= 2 && e.endsWith(`-${tShort}`)) return true
80
+ // 4) 条目名是目标包内的模块路径(`aegis/extensions/dsh/index.js` 属于包 `aegis`,
81
+ // `@scope/pkg/dist/x.js` 属于 `@scope/pkg`):归一化会吞掉路径分隔符,
82
+ // 必须在归一化前用原始形态做「target/」前缀判断(大小写不敏感)。
83
+ const rawE = entryName.trim().toLowerCase()
84
+ const rawT = target.trim().toLowerCase()
85
+ if (rawE === rawT || rawE.startsWith(`${rawT}/`)) return true
63
86
  return false
64
87
  }
65
88
 
@@ -119,3 +142,34 @@ export async function removeLoadedEntry(loader: LoaderHandle, name: string): Pro
119
142
  console.log(`[hub-uninstall] disable ${name} -> ${result ? 'ok/clean' : 'timed out or failed'}`)
120
143
  return result
121
144
  }
145
+
146
+ /**
147
+ * 判断某已安装包是否是真正的 dsh 插件(宿主会加载 / 值得提示「待重启」):
148
+ * 1) 包名已写进 profile 的 `dsh.profile.bundles`(宿主启动时按清单加载);
149
+ * 2) 或包内 package.json 声明了 dsh 配置(`dsh.bundle` / `dsh.profile` 等)或 dsh 相关 keywords。
150
+ * 两者都满足不了(如 GitHub 官方示例仓库 octocat/Hello-World)说明它不是 dsh 插件,
151
+ * 装上也不会被宿主加载——UI 据此不再提示「待重启」,避免误导用户反复重启一个不会生效的东西。
152
+ */
153
+ export function isDshPlugin(profile: string, name: string): boolean {
154
+ // 1) profile 级 bundles 清单:包名在清单里 → 宿主启动会加载它
155
+ try {
156
+ const profilePkg = JSON.parse(readFileSync(join(profileDirectory(profile), 'package.json'), 'utf8')) as {
157
+ dsh?: { profile?: { bundles?: unknown } }
158
+ }
159
+ if (Array.isArray(profilePkg.dsh?.profile?.bundles)) {
160
+ if ((profilePkg.dsh.profile.bundles as unknown[]).includes(name)) return true
161
+ }
162
+ } catch { /* profile 读取失败按无 bundles 处理 */ }
163
+ // 2) 包内声明:dsh 字段(bundle patch / profile 配置)或 dsh 关键字
164
+ try {
165
+ const pkg = JSON.parse(readFileSync(join(profileDirectory(profile), 'node_modules', name, 'package.json'), 'utf8')) as {
166
+ dsh?: unknown
167
+ keywords?: unknown
168
+ }
169
+ if (pkg.dsh) return true
170
+ if (Array.isArray(pkg.keywords)) {
171
+ if ((pkg.keywords as unknown[]).some((k) => typeof k === 'string' && /^(?:dsh|dsh-plugin)$/i.test(k))) return true
172
+ }
173
+ } catch { /* 包缺失 / 无 package.json → 不是 dsh 插件 */ }
174
+ return false
175
+ }