dsh-dpharness 0.4.4 → 0.5.2
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 +358 -16
- package/icon.svg +11 -0
- package/lib/changelog.js +208 -0
- package/lib/client.js +2902 -361
- package/lib/index.js +1026 -27
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +18 -7
package/lib/index.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-dpharness — host half (v0.
|
|
2
|
+
* dsh-dpharness — host half (v0.5.2).
|
|
3
3
|
*
|
|
4
4
|
* Catalog routes, a write-only telemetry relay and a one-click installer:
|
|
5
5
|
*
|
|
6
|
-
* GET /api/dpharness/search?q=<kw>&take=<n>&sort=stars
|
|
6
|
+
* GET /api/dpharness/search?q=<kw>&take=<n>&sort=stars → { count, total, plugins[] }
|
|
7
|
+
* `count` = 本次返回条数,`total` = 该筛选下的真实命中总数(两者常不等)
|
|
7
8
|
* GET /api/dpharness/meta
|
|
9
|
+
* GET /api/dpharness/changelog
|
|
10
|
+
* GET /api/dpharness/updates
|
|
8
11
|
* GET /api/dpharness/postinstall?pkg=<pkg>&via=<local|market>&at=<epochMs>
|
|
9
12
|
* POST /api/dpharness/event → relayed to https://dpharness.com/api/track/event
|
|
10
13
|
* POST /api/dpharness/install → spawns `dsh plugin --profile <p> add <pkg>`
|
|
@@ -20,9 +23,11 @@
|
|
|
20
23
|
* and a keyword *length* are relayed. Telemetry can be switched off in the UI.
|
|
21
24
|
*
|
|
22
25
|
* Upstream contracts (all read from source / measured 2026-09-17):
|
|
23
|
-
* - GET https://dpharness.com/api/plugins → { count, plugins[] }; `q` covers
|
|
24
|
-
* whole catalog; `take` is clamped at 500; `sort=stars` is a strictly
|
|
25
|
-
* descending star order;
|
|
26
|
+
* - GET https://dpharness.com/api/plugins → { count, total, plugins[] }; `q` covers
|
|
27
|
+
* the whole catalog; `take` is clamped at 500; `sort=stars` is a strictly
|
|
28
|
+
* descending star order; `count` is this page's size while `total` is the real
|
|
29
|
+
* hit count under the filter (measured 2026-09-30: q=统计 → count=3/30, total=106);
|
|
30
|
+
* item.installCheck = { status, pkgName }
|
|
26
31
|
* - POST https://dpharness.com/api/track/event → { type, value, path, visitorId }
|
|
27
32
|
* (`path` is truncated at "?", so detail belongs in `value`)
|
|
28
33
|
* - POST /dsh-market/install (dshmarket, when installed) → body { url }, same-origin
|
|
@@ -33,13 +38,32 @@ import { spawn } from "node:child_process";
|
|
|
33
38
|
import fs from "node:fs";
|
|
34
39
|
import os from "node:os";
|
|
35
40
|
import path from "node:path";
|
|
41
|
+
import { CHANGELOG, RELEASES_URL, REPO, compareVersions, mergeChangelog, npmLatestUrl } from "./changelog.js";
|
|
36
42
|
|
|
37
43
|
export const name = "dpharness";
|
|
38
44
|
|
|
39
45
|
/** The dsh web server service used to register HTTP routes. */
|
|
40
46
|
export const inject = ["webServer"];
|
|
41
47
|
|
|
42
|
-
export const VERSION = "0.
|
|
48
|
+
export const VERSION = "0.5.2";
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 本插件在 npm 上的包名 —— 与 dsh 的插件 id(上面的 `name = "dpharness"`)**不是一回事**,
|
|
52
|
+
* 别互相替代:前者用于 registry 查询与升级命令,后者用于 profile 加载清单。
|
|
53
|
+
*/
|
|
54
|
+
export const PKG_NAME = "dsh-dpharness";
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 接口负载的**形状版本**。改动 /updates、/changelog 返回的字段时**必须 +1**。
|
|
58
|
+
*
|
|
59
|
+
* 为什么需要它:desktop profile 里本插件是指向工作区的符号链接 —— 客户端刷新页面即生效,
|
|
60
|
+
* 而宿主的路由与字段要**重启 dsh** 才会更新。这个窗口期里界面会缺字段(实测已误导过两次),
|
|
61
|
+
* 客户端据此显式提示「宿主进程是旧版本」,而不是让用户以为功能坏了。
|
|
62
|
+
*
|
|
63
|
+
* ⚠️ 客户端侧有一份同名常量(两个半边同包但不同运行时,没法 import),
|
|
64
|
+
* test-local.mjs **双向断言两者相等** —— 改一处忘了另一处会当场变红。
|
|
65
|
+
*/
|
|
66
|
+
export const SHAPE_REV = 3;
|
|
43
67
|
|
|
44
68
|
/**
|
|
45
69
|
* Wall-clock time this dsh process started.
|
|
@@ -61,11 +85,42 @@ const STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
|
|
|
61
85
|
const PROFILE = (() => {
|
|
62
86
|
const flag = process.argv.indexOf("--profile");
|
|
63
87
|
if (flag >= 0 && process.argv[flag + 1]) return process.argv[flag + 1];
|
|
64
|
-
|
|
88
|
+
if (process.env.DSH_DPHARNESS_PROFILE) return process.env.DSH_DPHARNESS_PROFILE;
|
|
89
|
+
return profileFromArgv() || "web";
|
|
65
90
|
})();
|
|
66
91
|
|
|
92
|
+
/**
|
|
93
|
+
* Recover the profile name from the desktop shell's positional arguments.
|
|
94
|
+
*
|
|
95
|
+
* The Electron shell boots this host as
|
|
96
|
+
* …/MacOS/DeepSeek Harness --expose-internals <…>/dsh-desktop-host/lib/index.js \
|
|
97
|
+
* <…>/app.asar/dsh <…>/.dsh/profiles/<profile> <…>/runtime/primary-runtime
|
|
98
|
+
* so neither `--profile` nor DSH_DPHARNESS_PROFILE exists and the plain
|
|
99
|
+
* fallback ("web") names the WRONG profile: the user is looking at `desktop`
|
|
100
|
+
* while the install would land in `web` (measured 2026-09-30 against
|
|
101
|
+
* @deepseek-ai/dsh-desktop 0.2.0-rc.2, where argv held …/profiles/desktop).
|
|
102
|
+
*
|
|
103
|
+
* A candidate is accepted only when a package.json really sits there, so an
|
|
104
|
+
* unrelated path that merely contains "profiles" cannot be mistaken for it.
|
|
105
|
+
*/
|
|
106
|
+
export function profileFromArgv(argv = process.argv) {
|
|
107
|
+
for (const arg of argv) {
|
|
108
|
+
if (typeof arg !== "string") continue;
|
|
109
|
+
const normalized = arg.replace(/[\\/]+$/, "");
|
|
110
|
+
const match = /[\\/]profiles[\\/]([^\\/]+)$/.exec(normalized);
|
|
111
|
+
if (!match) continue;
|
|
112
|
+
try {
|
|
113
|
+
if (fs.statSync(path.join(normalized, "package.json")).isFile()) return match[1];
|
|
114
|
+
} catch (error) {
|
|
115
|
+
/* not a profile directory — keep looking */
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
67
121
|
const UPSTREAM = "https://dpharness.com/api/plugins";
|
|
68
122
|
const BEST_UPSTREAM = "https://dpharness.com/api/best";
|
|
123
|
+
const SETS_UPSTREAM = "https://dpharness.com/api/sets";
|
|
69
124
|
const SITE = "https://dpharness.com";
|
|
70
125
|
const TRACK = "https://dpharness.com/api/track/event";
|
|
71
126
|
const DEFAULT_TAKE = 30;
|
|
@@ -94,6 +149,15 @@ const EVENT_MAX_PER_WINDOW = 120;
|
|
|
94
149
|
*/
|
|
95
150
|
const TARGET_RE = /^[A-Za-z0-9@:./_#+~^=-]+$/;
|
|
96
151
|
const INSTALL_TIMEOUT_MS = 180 * 1000;
|
|
152
|
+
/**
|
|
153
|
+
* 超时之后的收尾宽限。
|
|
154
|
+
*
|
|
155
|
+
* SIGKILL 已经发出,退出事件通常毫秒级就到 —— 这段时间只用来等 close 收尾,
|
|
156
|
+
* 不改变任何结论;到点仍未收敛就**强制解锁**(见 forceUnlock)。它存在的理由是:
|
|
157
|
+
* close 是 active 的**唯一**复位点,而 close 会缺席(2026-10-14 实测宿主因此
|
|
158
|
+
* 彻底装不了任何插件,见 forceUnlock 的注释)。
|
|
159
|
+
*/
|
|
160
|
+
const INSTALL_SETTLE_MS = 5 * 1000;
|
|
97
161
|
|
|
98
162
|
/**
|
|
99
163
|
* Re-invoke the dsh CLI that launched this host, instead of looking for `dsh`
|
|
@@ -103,25 +167,85 @@ const INSTALL_TIMEOUT_MS = 180 * 1000;
|
|
|
103
167
|
*
|
|
104
168
|
* Spawning through the managed node's bin directory also puts `pnpm` on PATH,
|
|
105
169
|
* because the dsh web process is started by that same node.
|
|
170
|
+
*
|
|
171
|
+
* ⚠️ Under the Electron desktop shell argv[1] is a **flag**, not a path —
|
|
172
|
+
* measured 2026-09-30 on @deepseek-ai/dsh-desktop 0.2.0-rc.2:
|
|
173
|
+
* argv = [ …/MacOS/DeepSeek Harness, "--expose-internals",
|
|
174
|
+
* …/app.asar/dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/index.js,
|
|
175
|
+
* …/app.asar/dsh, ~/.dsh/profiles/desktop, …/runtime/primary-runtime ]
|
|
176
|
+
* The old single branch therefore returned null and **every** install died with
|
|
177
|
+
* "cannot locate the dsh entry point (process.argv[1])" — the failure the user
|
|
178
|
+
* sees in the panel. The shell ships its own CLI wrapper, so reuse that.
|
|
106
179
|
*/
|
|
107
180
|
function dshInvocation() {
|
|
108
181
|
const entry = process.argv[1];
|
|
109
|
-
if (typeof entry
|
|
110
|
-
|
|
111
|
-
|
|
182
|
+
if (typeof entry === "string" && /[\\/](?:bin\.(?:js|ts)|dsh)$/.test(entry)) {
|
|
183
|
+
const abs = path.resolve(entry);
|
|
184
|
+
return { file: process.execPath, args: [...process.execArgv, abs], cwd: path.dirname(abs) };
|
|
185
|
+
}
|
|
186
|
+
const shellCli = desktopShellCli();
|
|
187
|
+
/* cwd 取用户主目录:桌面版 CLI 位于 .app 包内(只读),任何意外写盘都会失败。
|
|
188
|
+
CLI 自己会切到 profile 目录再跑 pnpm(实测错误信息
|
|
189
|
+
"dsh: pnpm failed in profile directory …" 即由此而来),cwd 只作兜底。 */
|
|
190
|
+
if (shellCli !== null) return { file: shellCli, args: [], cwd: os.homedir() };
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* The Electron desktop shell ships a CLI wrapper inside its own bundle:
|
|
196
|
+
* <Contents>/Resources/runtime/cli/bin/dsh
|
|
197
|
+
* It is the only entry that can drive the shell's embedded dsh — a bare
|
|
198
|
+
* `node <asar>/…/bin.js` cannot read asar, and process.execPath there is the
|
|
199
|
+
* Electron binary rather than node. The wrapper itself sets
|
|
200
|
+
* ELECTRON_RUN_AS_NODE=1 and points at dsh-desktop-host/lib/cli.js (read from
|
|
201
|
+
* the file, not guessed).
|
|
202
|
+
*
|
|
203
|
+
* Path derived from the standard macOS bundle layout (…/Contents/MacOS/<App> →
|
|
204
|
+
* …/Contents) and `accessSync`-checked before use, so an unexpected layout
|
|
205
|
+
* degrades to the previous behaviour instead of spawning something wrong.
|
|
206
|
+
*/
|
|
207
|
+
export function desktopShellCli(execPath = process.execPath, isElectron = typeof process.versions?.electron === "string") {
|
|
208
|
+
if (!isElectron) return null;
|
|
209
|
+
const contents = path.resolve(path.dirname(execPath), "..");
|
|
210
|
+
const candidates = [
|
|
211
|
+
path.join(contents, "Resources", "runtime", "cli", "bin", "dsh"),
|
|
212
|
+
path.join(contents, "Resources", "runtime", "cli", "bin", "dsh.cmd"),
|
|
213
|
+
];
|
|
214
|
+
for (const candidate of candidates) {
|
|
215
|
+
try {
|
|
216
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
217
|
+
return candidate;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
/* try the next candidate */
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
112
223
|
}
|
|
113
224
|
|
|
114
225
|
const installJob = {
|
|
115
226
|
active: false,
|
|
116
227
|
stage: "idle",
|
|
228
|
+
/* add(安装/升级)| remove(卸载)—— 同一条通道,界面按它决定措辞 */
|
|
229
|
+
verb: "add",
|
|
117
230
|
target: "",
|
|
118
231
|
startedAt: 0,
|
|
119
232
|
finishedAt: 0,
|
|
120
233
|
code: null,
|
|
121
234
|
output: [],
|
|
122
235
|
error: null,
|
|
236
|
+
/* "incompatible" = dsh 自带的兼容性闸门拒绝(见 incompatibleFrom) */
|
|
237
|
+
why: null,
|
|
238
|
+
reject: null,
|
|
239
|
+
/* "changed" / "same"(本来就是目标版本)/ "none"(真的什么都没发生) */
|
|
240
|
+
outcome: null,
|
|
123
241
|
};
|
|
124
242
|
|
|
243
|
+
/* 当前在跑的安装子进程与它的序号。
|
|
244
|
+
序号是给**延迟收尾**用的:超时兜底计时器可能在下一个任务开始之后才到点,
|
|
245
|
+
没有序号就会把新任务误判成"卡死的老任务"解锁掉。 */
|
|
246
|
+
let installChild = null;
|
|
247
|
+
let installSeq = 0;
|
|
248
|
+
|
|
125
249
|
/**
|
|
126
250
|
* Build a clean environment for the child process.
|
|
127
251
|
*
|
|
@@ -152,7 +276,80 @@ function sanitizedEnv(binDir) {
|
|
|
152
276
|
return env;
|
|
153
277
|
}
|
|
154
278
|
|
|
155
|
-
|
|
279
|
+
/**
|
|
280
|
+
* 去掉 `@版本` 后缀,得到裸包名(`@scope/name@1.2.3` → `@scope/name`)。
|
|
281
|
+
*
|
|
282
|
+
* 用它去 profile 清单/安装目录里查东西 —— 清单的键是裸包名,
|
|
283
|
+
* 带着 `@latest` 去查会永远查不到。
|
|
284
|
+
*/
|
|
285
|
+
export function stripVersion(target) {
|
|
286
|
+
const value = String(target || "");
|
|
287
|
+
const matched = /^(.*?)@[^@/]+$/.exec(value);
|
|
288
|
+
return matched ? matched[1] : value;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 把安装任务复位成「已结束」—— **不依赖 close 事件**的兜底解锁。
|
|
293
|
+
*
|
|
294
|
+
* 🔴 2026-10-14 事故(用户实测,代价=整个插件面板再也装不了东西):
|
|
295
|
+
* 超时分支只把 error 置成 "timeout" 并 kill 掉**直系**子进程,而真正的安装是
|
|
296
|
+
* **孙进程**(宿主 → dsh CLI → pnpm):SIGKILL 打不到孙进程,它继续跑;孙进程继承了
|
|
297
|
+
* 管道,于是直系子进程的 close 永远不触发 —— 而 active 的唯一复位点就在 close 里。
|
|
298
|
+
* 结果是 active 永久为 true,之后每一次安装都被守卫拦成 409;现场实测卡死 36 分钟,
|
|
299
|
+
* 界面只显示「安装失败:an install is already running」,用户没有任何自救手段。
|
|
300
|
+
*
|
|
301
|
+
* 所以这里做三件事:①无条件解锁;②把仍在跑的进程组再杀一次(best effort);
|
|
302
|
+
* ③**补读一次磁盘**——超时时真实安装很可能已经成功(本轮事故正是 4.4.2 → 4.4.3
|
|
303
|
+
* 已落盘却报失败),把事实交给界面,别让"超时"被读成"什么都没发生"。
|
|
304
|
+
*
|
|
305
|
+
* @param reason 记进 error 的兜底原因(仅在 error 为空时使用)
|
|
306
|
+
* @param seq 调用方认定的任务序号;与当前序号不符则**不动手**(老计时器迟到)
|
|
307
|
+
*
|
|
308
|
+
* 导出是给 test-local.mjs 用的(同 desktopShellCli / errorLineFrom 的先例):
|
|
309
|
+
* "迟到计时器必须无害"这条只能从外部验。
|
|
310
|
+
*/
|
|
311
|
+
export function forceUnlock(reason, seq) {
|
|
312
|
+
if (seq !== undefined && seq !== installSeq) return false;
|
|
313
|
+
if (!installJob.active) return false;
|
|
314
|
+
installJob.active = false;
|
|
315
|
+
installJob.finishedAt = Date.now();
|
|
316
|
+
installJob.stage = "failed";
|
|
317
|
+
if (!installJob.error) installJob.error = reason || "unlocked";
|
|
318
|
+
killInstallTree();
|
|
319
|
+
if (installJob.pkg) {
|
|
320
|
+
const after = installedVersionOf(installJob.pkg);
|
|
321
|
+
if (after !== null && after !== installJob.before) {
|
|
322
|
+
installJob.after = after;
|
|
323
|
+
installJob.outcome = "changed";
|
|
324
|
+
installJob.changed = true;
|
|
325
|
+
/* 版本真变了 ⇒ 更新检查与"已安装"标注的缓存都得作废,否则界面刷新后
|
|
326
|
+
还显示旧版本号,用户会判定"升级没成功"。 */
|
|
327
|
+
updatesCache = { at: 0, value: null };
|
|
328
|
+
installedCache = { at: 0, value: {} };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** 按**进程组**杀掉当前安装(detached 让子进程自成一组,杀组才不会漏掉孙进程)。 */
|
|
335
|
+
function killInstallTree() {
|
|
336
|
+
const child = installChild;
|
|
337
|
+
installChild = null;
|
|
338
|
+
if (!child || !child.pid) return;
|
|
339
|
+
try {
|
|
340
|
+
process.kill(-child.pid, "SIGKILL");
|
|
341
|
+
return;
|
|
342
|
+
} catch (error) {
|
|
343
|
+
/* 进程组不可用(Windows / 已经退出)→ 退回只杀直系子进程 */
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
child.kill("SIGKILL");
|
|
347
|
+
} catch (error) {
|
|
348
|
+
/* already gone */
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function startInstall(target, verb) {
|
|
156
353
|
const invocation = dshInvocation();
|
|
157
354
|
if (invocation === null) {
|
|
158
355
|
installJob.active = false;
|
|
@@ -160,6 +357,10 @@ function startInstall(target) {
|
|
|
160
357
|
installJob.error = "cannot locate the dsh entry point (process.argv[1])";
|
|
161
358
|
return;
|
|
162
359
|
}
|
|
360
|
+
/* verb:add(安装/升级)或 remove(卸载)。同一条 spawn/轮询/脱敏通道,
|
|
361
|
+
所以三态结论(changed/same/none)对两者都成立:
|
|
362
|
+
remove 时 changed = 卸掉了 / same = 还在(没卸成)/ none = 本来就没装。 */
|
|
363
|
+
installJob.verb = verb === "remove" ? "remove" : "add";
|
|
163
364
|
installJob.active = true;
|
|
164
365
|
installJob.stage = "running";
|
|
165
366
|
installJob.target = target;
|
|
@@ -168,13 +369,31 @@ function startInstall(target) {
|
|
|
168
369
|
installJob.code = null;
|
|
169
370
|
installJob.output = [];
|
|
170
371
|
installJob.error = null;
|
|
372
|
+
/* 兼容性闸门是**预期结果**而非意外故障,单独占一个字段,供界面给可操作的说明 */
|
|
373
|
+
installJob.why = null;
|
|
374
|
+
installJob.reject = null;
|
|
375
|
+
/* 装之前的版本号:装完由 host **亲自读磁盘**比对。
|
|
376
|
+
实测(2026-10-12)dsh 的 `plugin add` 对已安装的包会**静默空转** ——
|
|
377
|
+
退出码 0、pnpm.log 0 字节、版本纹丝不动。若只看退出码,界面会谎报"已安装"。 */
|
|
378
|
+
installJob.pkg = stripVersion(target);
|
|
379
|
+
installJob.before = installedVersionOf(installJob.pkg);
|
|
380
|
+
installJob.after = null;
|
|
381
|
+
installJob.changed = null;
|
|
382
|
+
installJob.outcome = null;
|
|
171
383
|
|
|
172
384
|
const binDir = path.dirname(process.execPath);
|
|
173
|
-
|
|
385
|
+
/* 本任务的序号:所有**延迟**收尾(超时宽限、exit 兜底)都要拿它比对,
|
|
386
|
+
否则迟到的老计时器会把之后那个健康的任务解锁掉。 */
|
|
387
|
+
const seq = ++installSeq;
|
|
388
|
+
const child = spawn(invocation.file, [...invocation.args, "plugin", "--profile", PROFILE, installJob.verb, target], {
|
|
174
389
|
cwd: invocation.cwd,
|
|
175
390
|
env: sanitizedEnv(binDir),
|
|
176
391
|
stdio: ["ignore", "pipe", "pipe"],
|
|
392
|
+
/* detached ⇒ 子进程自成进程组,超时可以按 -pid 杀掉**整棵树**。
|
|
393
|
+
不这么做的话孙进程(真正干活的 pnpm)活下来,close 就永远不来。 */
|
|
394
|
+
detached: true,
|
|
177
395
|
});
|
|
396
|
+
installChild = child;
|
|
178
397
|
|
|
179
398
|
const push = (chunk) => {
|
|
180
399
|
const text = String(chunk);
|
|
@@ -186,28 +405,124 @@ function startInstall(target) {
|
|
|
186
405
|
|
|
187
406
|
const timer = setTimeout(() => {
|
|
188
407
|
installJob.error = "timeout";
|
|
189
|
-
|
|
408
|
+
/* 按进程组杀整棵树 —— 只杀直系子进程会把真正干活的 pnpm 孙进程留下
|
|
409
|
+
(2026-10-14 实测它又活了 36 分钟,并把宿主永久卡进 409)。 */
|
|
410
|
+
killInstallTree();
|
|
411
|
+
/* 但 kill 不保证 close 一定来(孙进程握着管道 / 直系子进程已被换掉)⇒ 到点强制解锁。
|
|
412
|
+
这一层是**必须**的:close 是 active 的唯一复位点,它缺席就等于宿主死锁。 */
|
|
413
|
+
setTimeout(() => {
|
|
414
|
+
if (forceUnlock("timeout", seq)) {
|
|
415
|
+
console.warn(`[dpharness] install of ${target} timed out and did not settle — unlocked`);
|
|
416
|
+
}
|
|
417
|
+
}, INSTALL_SETTLE_MS);
|
|
190
418
|
}, INSTALL_TIMEOUT_MS);
|
|
191
419
|
|
|
192
420
|
child.on("error", (error) => {
|
|
193
421
|
clearTimeout(timer);
|
|
422
|
+
if (seq !== installSeq) return;
|
|
194
423
|
installJob.active = false;
|
|
195
424
|
installJob.stage = "failed";
|
|
196
425
|
installJob.error = String((error && error.message) || error);
|
|
197
426
|
installJob.finishedAt = Date.now();
|
|
427
|
+
installChild = null;
|
|
428
|
+
});
|
|
429
|
+
/**
|
|
430
|
+
* exit 兜底:进程退了、但 stdio 还被孙进程攥着 ⇒ close 可能永远不来。
|
|
431
|
+
* 等一个宽限期,让 close 有机会做完整收尾(读磁盘核对三态);它没来就自己解锁。
|
|
432
|
+
*/
|
|
433
|
+
child.on("exit", () => {
|
|
434
|
+
setTimeout(() => {
|
|
435
|
+
if (forceUnlock("exit-without-close", seq)) {
|
|
436
|
+
console.warn(`[dpharness] install of ${target} exited without closing its pipes — unlocked`);
|
|
437
|
+
}
|
|
438
|
+
}, INSTALL_SETTLE_MS);
|
|
198
439
|
});
|
|
199
440
|
child.on("close", (code) => {
|
|
200
441
|
clearTimeout(timer);
|
|
442
|
+
if (seq !== installSeq) return;
|
|
443
|
+
installChild = null;
|
|
201
444
|
installJob.active = false;
|
|
202
445
|
installJob.code = code;
|
|
203
446
|
installJob.finishedAt = Date.now();
|
|
204
447
|
installJob.stage = code === 0 ? "done" : "failed";
|
|
205
|
-
if (code
|
|
448
|
+
if (code === 0) {
|
|
449
|
+
/* 装完**读磁盘**核对:退出码 0 不等于装上了(dsh 对已安装的包会静默空转)。
|
|
450
|
+
⚠️ 必须三态 —— 别把"本来就是这个版本"说成"什么都没装"(2026-10-12 用户被这句误导:
|
|
451
|
+
他在目录卡片上点「安装」装一个早就装好的插件,界面报"什么都没装",他读成安装失败):
|
|
452
|
+
changed 装上了 / 升级了 → 需要重启
|
|
453
|
+
same **本来就是目标版本** → 这是成功,不是失败
|
|
454
|
+
none 装前装后都查不到 → 那才是真的什么都没发生 */
|
|
455
|
+
installJob.after = installedVersionOf(installJob.pkg);
|
|
456
|
+
installJob.outcome = installJob.before === null && installJob.after === null
|
|
457
|
+
? "none"
|
|
458
|
+
: (installJob.before === installJob.after ? "same" : "changed");
|
|
459
|
+
installJob.changed = installJob.outcome === "changed";
|
|
460
|
+
/* 装成了就把更新检查的缓存作废:否则界面刷新后拿到的还是装之前那份清单,
|
|
461
|
+
"升完还显示可升级" —— 用户只会判定"升级没成功"(2026-10-12 实测撞到)。 */
|
|
462
|
+
updatesCache = { at: 0, value: null };
|
|
463
|
+
/* 已装版本变了,目录卡片上的「已安装」标注也要跟着刷新 */
|
|
464
|
+
installedCache = { at: 0, value: {} };
|
|
465
|
+
}
|
|
466
|
+
if (code !== 0 && installJob.error === null) {
|
|
467
|
+
const blocked = incompatibleFrom(installJob.output.join(""));
|
|
468
|
+
if (blocked) {
|
|
469
|
+
installJob.why = "incompatible";
|
|
470
|
+
installJob.reject = blocked;
|
|
471
|
+
/* 给一个结构化、可检索的兜底描述;界面会按 why 翻成人话,不依赖这句 */
|
|
472
|
+
installJob.error = `dsh rejected ${blocked.spec} (incompatible with dsh ${blocked.dsh})`;
|
|
473
|
+
} else {
|
|
474
|
+
/* 供应链策略拒绝也单独成类(同 incompatible 的做法):它是**预期结果**,
|
|
475
|
+
界面要给出条目、剩余等待时间与通路,而不是一句英文错误码。 */
|
|
476
|
+
const aged = releaseAgeFrom(installJob.output.join(""));
|
|
477
|
+
if (aged) {
|
|
478
|
+
installJob.why = "release-age";
|
|
479
|
+
installJob.reject = aged;
|
|
480
|
+
installJob.error = `pnpm supply-chain policy rejected ${aged.count} lockfile entries (minimumReleaseAge)`;
|
|
481
|
+
} else {
|
|
482
|
+
installJob.error = errorLine();
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
206
486
|
});
|
|
207
487
|
}
|
|
208
488
|
|
|
489
|
+
/**
|
|
490
|
+
* 展示前的统一脱敏。
|
|
491
|
+
*
|
|
492
|
+
* 为什么必须在**服务端**做(2026-09-30 用户提出,且这次是我先踩了):
|
|
493
|
+
* pnpm 输出的尾部会原样出现在面板卡片上(安装失败时用于定位),而 `.npmrc` 里的
|
|
494
|
+
* registry token 一旦落到卡片上就会被截图、被日志外带、被会话记录保存 ——
|
|
495
|
+
* **换 token 也挡不住,因为展示路径还在**。所以堵点是"展示"而不是"凭据"。
|
|
496
|
+
*
|
|
497
|
+
* pnpm 多数情况会自己打成 `Bearer npm_[hidden]`(实测 11.7.0),但那不是契约;
|
|
498
|
+
* 这里按最坏情况兜底:只要形如凭据就替换成 `***`。
|
|
499
|
+
*
|
|
500
|
+
* ⚠️ 调用顺序固定为「先截断、后脱敏」—— 反过来的话,截断会把 token 切成半截,
|
|
501
|
+
* 半截 token 照样是泄露,而且再也匹配不上任何模式。
|
|
502
|
+
*/
|
|
503
|
+
const SECRET_PATTERNS = [
|
|
504
|
+
/* 第三方已自带的部分脱敏(pnpm 实测就是 `Bearer npm_[hidden]`,2026-09-30)。
|
|
505
|
+
内容虽然隐藏了,但"日志里会出现 token"这件事本身就该消失——统一压成 ***,
|
|
506
|
+
信息量不减:`Bearer ***` 仍然告诉读者这次请求带了凭据。 */
|
|
507
|
+
[/\bnpm_\[[^\]]*\]/g, "***"],
|
|
508
|
+
/* .npmrc 常见写法://registry.npmjs.org/:_authToken=xxx、_auth、_password */
|
|
509
|
+
[/((?:_authToken|_auth|_password|password|token)\s*[=:]\s*)\S+/gi, "$1***"],
|
|
510
|
+
/* Authorization 头:Authorization: Bearer xxx / Basic xxx */
|
|
511
|
+
[/(authorization\s*[=:]\s*)(?:bearer|basic|token)\s+\S+/gi, "$1***"],
|
|
512
|
+
/* 无字段名的裸方案前缀:Bearer npm_xxx(pnpm 的错误提示就是这个形状) */
|
|
513
|
+
[/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{12,}/gi, "$1 ***"],
|
|
514
|
+
/* npm 的 token 形状本身 */
|
|
515
|
+
[/npm_[A-Za-z0-9]{16,}/g, "npm_***"],
|
|
516
|
+
];
|
|
517
|
+
|
|
518
|
+
export function redactSecrets(text) {
|
|
519
|
+
let out = String(text == null ? "" : text);
|
|
520
|
+
for (const [pattern, replacement] of SECRET_PATTERNS) out = out.replace(pattern, replacement);
|
|
521
|
+
return out;
|
|
522
|
+
}
|
|
523
|
+
|
|
209
524
|
function tail() {
|
|
210
|
-
return installJob.output.join("").trim().slice(-600);
|
|
525
|
+
return redactSecrets(installJob.output.join("").trim().slice(-600));
|
|
211
526
|
}
|
|
212
527
|
|
|
213
528
|
/**
|
|
@@ -219,7 +534,78 @@ function tail() {
|
|
|
219
534
|
* a distinctive pnpm error code first, generic wording only as a fallback.
|
|
220
535
|
*/
|
|
221
536
|
function errorLine() {
|
|
222
|
-
|
|
537
|
+
/* 与 tail() 同一口径:这一行同样会展示在卡片上,必须脱敏后再出 */
|
|
538
|
+
return redactSecrets(errorLineFrom(installJob.output.join("")));
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* dsh **自带的兼容性闸门**拒绝安装时的专用识别。
|
|
543
|
+
*
|
|
544
|
+
* 实测(2026-10-12,桌面版 dsh 0.2.0-rc.2):`dsh plugin add <pkg>@latest` 会拿目标版本的
|
|
545
|
+
* peerDependencies 跟本机 dsh 比对,不匹配就**硬拒绝**,输出形如:
|
|
546
|
+
* dsh: installation rejected: Plugin dsh-restart@0.1.2 is incompatible with dsh 0.2.0-rc.2:
|
|
547
|
+
* peerDependencies {…}. Running it may cause crashes or data loss. …
|
|
548
|
+
* dsh: nothing was installed.
|
|
549
|
+
*
|
|
550
|
+
* ⚠️ 这段文本里**没有** ERR_ / error / failed 任何一个关键词,所以通用的 errorLineFrom()
|
|
551
|
+
* 抓不到它,界面只剩一句 "dsh: nothing was installed." —— 用户根本看不出为什么"升级不了"
|
|
552
|
+
* (本次实际踩到)。这里把它识别成一个**闭集原因**(incompatible)并带上两端版本,
|
|
553
|
+
* 交给界面翻成人话:该说的说清(拒绝原因 + 放行通道),且**不代用户放行**。
|
|
554
|
+
*/
|
|
555
|
+
export function incompatibleFrom(text) {
|
|
556
|
+
const matched = /installation rejected:\s*Plugin\s+(\S+?)\s+is incompatible with dsh\s+([^\s:]+)/i.exec(String(text || ""));
|
|
557
|
+
if (!matched) return null;
|
|
558
|
+
const spec = matched[1];
|
|
559
|
+
const at = spec.lastIndexOf("@");
|
|
560
|
+
return {
|
|
561
|
+
/* name@version 拆开:scoped 包(@scope/name@1.2.3)取最后一个 @ 才是版本分隔符 */
|
|
562
|
+
name: at > 0 ? spec.slice(0, at) : spec,
|
|
563
|
+
version: at > 0 ? spec.slice(at + 1) : "",
|
|
564
|
+
spec,
|
|
565
|
+
dsh: matched[2],
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* pnpm **供应链策略**拒绝时的专用识别(pnpm 11 内置 `minimumReleaseAge`,2026-10-14 实测)。
|
|
571
|
+
*
|
|
572
|
+
* 原文形状:
|
|
573
|
+
* [ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION] 3 lockfile entries failed verification:
|
|
574
|
+
* dsh-connect-workbuddy@4.4.5 was published at 2026-10-13T20:06:51.203Z, within the minimumReleaseAge cutoff (…)
|
|
575
|
+
*
|
|
576
|
+
* 为什么必须单独识别:它**不是"安装出错"**,而是**策略性拒绝** —— 用户能做的只有「等它满 24 小时」
|
|
577
|
+
* 或「改本机 profile 的豁免名单」,界面得说清"哪几条、大概还要等多久、去哪儿加豁免"。
|
|
578
|
+
* 通用的 errorLineFrom() 只会给出头部那一行 `[ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION] 3 lockfile …`,
|
|
579
|
+
* 用户既看不出这是什么、也不知道下一步做什么(2026-10-14 用户实际撞到,卡片上只有这行原文)。
|
|
580
|
+
*
|
|
581
|
+
* ⚠️ 附带一条实测出来、值得写进界面提示的坑:`minimumReleaseAgeExclude` 是**同一包名只认第一条匹配**
|
|
582
|
+
* (pnpm 源码 evaluateVersionPolicy 命中 name 就 return)⇒ 同一个包写成多条 `name@v1`/`name@v2`
|
|
583
|
+
* 时**只有第一条生效**,必须写成同一条规则 `name@v1 || v2`,或用通配符。
|
|
584
|
+
*/
|
|
585
|
+
export function releaseAgeFrom(text) {
|
|
586
|
+
const source = String(text || "");
|
|
587
|
+
if (!source.includes("MINIMUM_RELEASE_AGE_VIOLATION")) return null;
|
|
588
|
+
const entries = [];
|
|
589
|
+
let cutoff = null;
|
|
590
|
+
for (const line of source.split(/\r?\n/)) {
|
|
591
|
+
const matched = /(\S+) was published at ([\dT:.Z+-]+), within the minimumReleaseAge cutoff \(([\dT:.Z+-]+)\)/.exec(line);
|
|
592
|
+
if (matched === null) continue;
|
|
593
|
+
const at = matched[1].lastIndexOf("@");
|
|
594
|
+
entries.push({
|
|
595
|
+
/* scoped 包(@scope/name@1.2.3)取最后一个 @ 才是版本分隔符 */
|
|
596
|
+
name: at > 0 ? matched[1].slice(0, at) : matched[1],
|
|
597
|
+
version: at > 0 ? matched[1].slice(at + 1) : "",
|
|
598
|
+
publishedAt: matched[2],
|
|
599
|
+
});
|
|
600
|
+
if (cutoff === null) cutoff = matched[3];
|
|
601
|
+
}
|
|
602
|
+
const counted = /(\d+) lockfile entr(?:y|ies) failed verification/.exec(source);
|
|
603
|
+
return {
|
|
604
|
+
/* 头部条数可能大于可见条数(pnpm 超过上限会省略 "…and N more"),两个都留着 */
|
|
605
|
+
count: counted ? Number(counted[1]) : entries.length,
|
|
606
|
+
cutoff,
|
|
607
|
+
entries,
|
|
608
|
+
};
|
|
223
609
|
}
|
|
224
610
|
|
|
225
611
|
/** Same extraction, exposed for tests (input is the raw captured output). */
|
|
@@ -242,10 +628,18 @@ function jobView() {
|
|
|
242
628
|
return {
|
|
243
629
|
active: installJob.active,
|
|
244
630
|
stage: installJob.stage,
|
|
631
|
+
verb: installJob.verb,
|
|
245
632
|
target: installJob.target,
|
|
246
633
|
seconds: installJob.active ? Math.round((Date.now() - installJob.startedAt) / 1000) : 0,
|
|
247
634
|
code: installJob.code,
|
|
248
635
|
error: installJob.error,
|
|
636
|
+
why: installJob.why,
|
|
637
|
+
reject: installJob.reject,
|
|
638
|
+
pkg: installJob.pkg,
|
|
639
|
+
before: installJob.before,
|
|
640
|
+
after: installJob.after,
|
|
641
|
+
outcome: installJob.outcome,
|
|
642
|
+
changed: installJob.changed,
|
|
249
643
|
tail: installJob.output.length > 0 ? tail() : "",
|
|
250
644
|
};
|
|
251
645
|
}
|
|
@@ -292,6 +686,8 @@ export function pkgState(pkg, manifest = profileManifest()) {
|
|
|
292
686
|
const cache = new Map();
|
|
293
687
|
/** /api/best 单键缓存(榜单每月只重算一次,5 分钟缓存足够) */
|
|
294
688
|
let bestCache = { at: 0, value: null };
|
|
689
|
+
/** /api/sets 单键缓存(套装同样每月才同步一次,缓存策略与 /best 一致) */
|
|
690
|
+
let setsCache = { at: 0, value: null };
|
|
295
691
|
let eventWindow = { startedAt: 0, count: 0 };
|
|
296
692
|
|
|
297
693
|
/**
|
|
@@ -448,8 +844,12 @@ function slim(item) {
|
|
|
448
844
|
src: pkgName ? "npm" : "repo",
|
|
449
845
|
/** 站点是否验证通过(pass);未验证/警告都按保守处理 */
|
|
450
846
|
verified,
|
|
451
|
-
|
|
452
|
-
|
|
847
|
+
/* ⚠️ 这里必须用**本机真实 profile**,不能抄站点详情页的 `--profile web`(2026-10-12 修正)。
|
|
848
|
+
原先照抄站点口径是想"两个出口给同一句话",但对 desktop profile 的用户来说,
|
|
849
|
+
复制出来的命令会装进 **web** profile —— 桌面上永远看不到那个插件,
|
|
850
|
+
用户只会得出"安装不成功"(实测用户就是这么撞上的)。
|
|
851
|
+
站点无法知道你本机用的是哪个 profile,所以这一处**必须分歧**:命令是给人当场执行的。 */
|
|
852
|
+
cmd: target ? `dsh plugin --profile ${PROFILE} add ${target}` : null,
|
|
453
853
|
};
|
|
454
854
|
}
|
|
455
855
|
|
|
@@ -483,7 +883,7 @@ async function fetchCatalog(params) {
|
|
|
483
883
|
const now = Date.now();
|
|
484
884
|
const hit = cache.get(key);
|
|
485
885
|
if (hit && now - hit.at < CACHE_TTL_MS) {
|
|
486
|
-
return { count: hit.value.count, plugins: hit.value.plugins, cached: true, fetchedAt: hit.at };
|
|
886
|
+
return { count: hit.value.count, total: hit.value.total, plugins: hit.value.plugins, cached: true, fetchedAt: hit.at };
|
|
487
887
|
}
|
|
488
888
|
|
|
489
889
|
const controller = new AbortController();
|
|
@@ -500,7 +900,13 @@ async function fetchCatalog(params) {
|
|
|
500
900
|
if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
|
|
501
901
|
const body = await response.json();
|
|
502
902
|
const list = Array.isArray(body && body.plugins) ? body.plugins : [];
|
|
503
|
-
|
|
903
|
+
/* 上游同时给两个数:count = 本次返回条数,total = 该筛选下的真实命中总数。
|
|
904
|
+
⚠️ 以前只取 list.length 当结果数,于是「共 N 条结果」里的 N 永远等于 take
|
|
905
|
+
(默认 30)—— 搜索前后这个数字完全不变,用户据此判定「搜索不生效」
|
|
906
|
+
(2026-09-30 实测:搜「统计」真实命中 106 条,面板写死「共 30 条结果」)。
|
|
907
|
+
total 缺失时退回 list.length,保证老上游下文案仍有意义。 */
|
|
908
|
+
const total = Number.isFinite(body && body.total) ? body.total : list.length;
|
|
909
|
+
const value = { count: list.length, total, plugins: list.map(slim) };
|
|
504
910
|
cache.set(key, { at: Date.now(), value });
|
|
505
911
|
return { ...value, cached: false, fetchedAt: Date.now() };
|
|
506
912
|
} finally {
|
|
@@ -559,6 +965,89 @@ async function fetchBest() {
|
|
|
559
965
|
}
|
|
560
966
|
}
|
|
561
967
|
|
|
968
|
+
/**
|
|
969
|
+
* 「组合方案套装」(站点 /api/sets 的同源数据,2026-10-13 新增)。
|
|
970
|
+
*
|
|
971
|
+
* 与 /best 的分工:best 是同类**横向**最优(按小类导购);sets 是跨插件**纵向**
|
|
972
|
+
* 组合(一整套协作方案 + 安装顺序 + 冲突提示)。两者都回答"该装哪个",但粒度不同 ——
|
|
973
|
+
* 用户说"我要做 OCR"时,套装才是答案。
|
|
974
|
+
*
|
|
975
|
+
* ⚠️ 命令一律**由本机拼装**,不抄站点给的字符串:
|
|
976
|
+
* · 站点侧的命令常量 profile 是 `web`,而本机可能是 desktop(抄了就是错命令,
|
|
977
|
+
* 桌面用户装进 web profile 后永远看不到 —— 2026-10-12 已实测踩过);
|
|
978
|
+
* · 站点条目自带 `pluginTier`(core|related)与 `installCheck`,`slim` 已有同一套
|
|
979
|
+
* target 口径(pass 用包名,否则 owner/repo)+ 本机 profile 注入;
|
|
980
|
+
* · `related`(MCP / Koishi / 通用客户端等无 npm 归属可核验的生态)走 git clone ——
|
|
981
|
+
* 与站点 lib/installCmd.ts 的 resolveSetItemCommand 同为一条规则。
|
|
982
|
+
* 批量命令 = 逐条命令按安装顺序换行拼接(与站点 buildSetInstallBlock 同语义)。
|
|
983
|
+
*
|
|
984
|
+
* ⚠️ 套装条目的 `tier`(套装内必要性 required|enhance|optional)与插件的 `tier`
|
|
985
|
+
* (生态分层 core|related)**同名不同义**,传输时后者已由站点改名为 `pluginTier`。
|
|
986
|
+
*/
|
|
987
|
+
async function fetchSets() {
|
|
988
|
+
const now = Date.now();
|
|
989
|
+
if (setsCache.value && now - setsCache.at < CACHE_TTL_MS) {
|
|
990
|
+
return { ...setsCache.value, cached: true, fetchedAt: setsCache.at };
|
|
991
|
+
}
|
|
992
|
+
const controller = new AbortController();
|
|
993
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
994
|
+
try {
|
|
995
|
+
const response = await fetch(SETS_UPSTREAM, {
|
|
996
|
+
headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
|
|
997
|
+
signal: controller.signal,
|
|
998
|
+
});
|
|
999
|
+
if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
|
|
1000
|
+
const body = await response.json();
|
|
1001
|
+
const installed = installedMap();
|
|
1002
|
+
const sets = (Array.isArray(body && body.sets) ? body.sets : []).map((set) => {
|
|
1003
|
+
const items = (Array.isArray(set.items) ? set.items : []).map((raw) => {
|
|
1004
|
+
/* tier 覆盖成**插件的**生态分层再交给 slim —— 否则 slim 会把套装必要性
|
|
1005
|
+
(required/enhance/optional)当生态分层读,"related → git clone" 永远不成立。 */
|
|
1006
|
+
const shaped = slim(Object.assign({}, raw, { tier: raw.pluginTier, category: null }));
|
|
1007
|
+
if (shaped.tier === "related" && shaped.fullName) {
|
|
1008
|
+
shaped.cmd = `git clone https://github.com/${shaped.fullName}.git`;
|
|
1009
|
+
shaped.src = "repo";
|
|
1010
|
+
}
|
|
1011
|
+
return Object.assign(shaped, {
|
|
1012
|
+
/* 套装内必要性(与 slim 的 tier 不是一回事,单列一个字段避免混用) */
|
|
1013
|
+
need: raw.tier || "enhance",
|
|
1014
|
+
/* 槽位职责:这个"位置"是干什么的(滚动槽位每月可能换人,所以不写插件名) */
|
|
1015
|
+
slotRole: raw.slotRole || null,
|
|
1016
|
+
installed: installedOf(shaped, installed),
|
|
1017
|
+
});
|
|
1018
|
+
});
|
|
1019
|
+
return {
|
|
1020
|
+
slug: set.slug || null,
|
|
1021
|
+
name: set.name || null,
|
|
1022
|
+
summary: set.summary || "",
|
|
1023
|
+
audience: set.audience || null,
|
|
1024
|
+
sceneLabel: set.sceneLabel || null,
|
|
1025
|
+
itemCount: items.length,
|
|
1026
|
+
risk: set.risk || null,
|
|
1027
|
+
syncedMonth: set.syncedMonth || null,
|
|
1028
|
+
syncedSlots: typeof set.syncedSlots === "number" ? set.syncedSlots : null,
|
|
1029
|
+
syncedReplaced: typeof set.syncedReplaced === "number" ? set.syncedReplaced : null,
|
|
1030
|
+
conflictNote: set.conflictNote || null,
|
|
1031
|
+
steps: set.steps || null,
|
|
1032
|
+
exampleParams: set.exampleParams || null,
|
|
1033
|
+
effectNote: set.effectNote || null,
|
|
1034
|
+
url: set.url ? `${SITE}${set.url}` : null,
|
|
1035
|
+
/* 批量安装命令:逐条命令按顺序换行拼接(顺序即安装顺序) */
|
|
1036
|
+
installBlock: items.map((item) => item.cmd).filter(Boolean).join("\n"),
|
|
1037
|
+
items,
|
|
1038
|
+
};
|
|
1039
|
+
}).filter((set) => set.itemCount > 0);
|
|
1040
|
+
const value = {
|
|
1041
|
+
total: sets.length,
|
|
1042
|
+
sets,
|
|
1043
|
+
};
|
|
1044
|
+
setsCache = { at: Date.now(), value };
|
|
1045
|
+
return { ...value, cached: false, fetchedAt: Date.now() };
|
|
1046
|
+
} finally {
|
|
1047
|
+
clearTimeout(timer);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
|
|
562
1051
|
function withinEventBudget() {
|
|
563
1052
|
const now = Date.now(); if (now - eventWindow.startedAt > EVENT_WINDOW_MS) {
|
|
564
1053
|
eventWindow = { startedAt: now, count: 0 };
|
|
@@ -610,8 +1099,10 @@ function buildTrackPayload(input) {
|
|
|
610
1099
|
// 旧版 open 事件用的字段名是 `scope`,保留兼容,避免同一含义两个键。
|
|
611
1100
|
const via = detail.via || detail.scope;
|
|
612
1101
|
if (via) parts.push("via=" + clean(via, 12));
|
|
613
|
-
// `why` 是**闭集枚举**(
|
|
1102
|
+
// `why` 是**闭集枚举**(http_405 / network / busy / timeout / cli_exit …),
|
|
614
1103
|
// 不是错误原文:原文可能含本地路径与包名,既超长又不可聚合。
|
|
1104
|
+
// 2026-09-30 起 HTTP 失败细化为 `http_<status>`(原 market_http 已被取代)——
|
|
1105
|
+
// 只有区分 405(路由缺席)/403(被拦)/5xx(上游故障)才能定位市场通道的问题。
|
|
615
1106
|
if (detail.why) parts.push("why=" + clean(detail.why, 24));
|
|
616
1107
|
// 布尔量只在**明确知道**时才写入(调用方不传即省略)。
|
|
617
1108
|
// 省略 = 未知,与 `=0`(明确为否)必须在数据层可区分 —— 否则「查不到」
|
|
@@ -636,6 +1127,381 @@ function registerRoute(ctx, pathname, handler) {
|
|
|
636
1127
|
);
|
|
637
1128
|
}
|
|
638
1129
|
|
|
1130
|
+
/* --------------------------------------------------------------- 更新日志 */
|
|
1131
|
+
/** /api/dpharness/changelog 的结果缓存(日志正文与版本号都不是秒级变化的数据)。 */
|
|
1132
|
+
let changelogCache = null;
|
|
1133
|
+
|
|
1134
|
+
/**
|
|
1135
|
+
* 任一个包在 npm 上的最新版(走 npmmirror)。本插件自身与「已装插件」的检查共用它。
|
|
1136
|
+
*
|
|
1137
|
+
* 查不到就返回 null —— **既不编造版本号,也不把「查不到」当成「已是最新」**:
|
|
1138
|
+
* 这两件事在界面上是两句不同的话,混为一谈会让离线用户以为自己已经最新而错过升级。
|
|
1139
|
+
* (同类三态问题本插件已踩过一次:postinstall 的 restarted 绝不用 false 兜底。)
|
|
1140
|
+
*/
|
|
1141
|
+
async function fetchNpmVersion(pkg) {
|
|
1142
|
+
const controller = new AbortController();
|
|
1143
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
1144
|
+
try {
|
|
1145
|
+
const response = await fetch(npmLatestUrl(pkg), {
|
|
1146
|
+
headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
|
|
1147
|
+
signal: controller.signal,
|
|
1148
|
+
});
|
|
1149
|
+
if (!response.ok) throw new Error(`npm HTTP ${response.status}`);
|
|
1150
|
+
const body = await response.json();
|
|
1151
|
+
const version = body && typeof body.version === "string" ? body.version.trim() : "";
|
|
1152
|
+
return /^\d+\.\d+\.\d+/.test(version) ? version : null;
|
|
1153
|
+
} catch (error) {
|
|
1154
|
+
return null;
|
|
1155
|
+
} finally {
|
|
1156
|
+
clearTimeout(timer);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/**
|
|
1161
|
+
* GitHub Releases(可选增强)。
|
|
1162
|
+
*
|
|
1163
|
+
* 仓库没发过 Release 时 GitHub 返回 `[]`(实测 2026-10-12 就是这种状态),
|
|
1164
|
+
* 网络/代理失败返回 null —— 两者都不该让「更新日志」整体不可用,故一律降级到内置底稿。
|
|
1165
|
+
*/
|
|
1166
|
+
async function fetchReleases() {
|
|
1167
|
+
const controller = new AbortController();
|
|
1168
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
1169
|
+
try {
|
|
1170
|
+
const response = await fetch(RELEASES_URL, {
|
|
1171
|
+
headers: { accept: "application/vnd.github+json", "user-agent": `dsh-dpharness/${VERSION}` },
|
|
1172
|
+
signal: controller.signal,
|
|
1173
|
+
});
|
|
1174
|
+
if (!response.ok) throw new Error(`github HTTP ${response.status}`);
|
|
1175
|
+
const body = await response.json();
|
|
1176
|
+
return Array.isArray(body) ? body : [];
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
return null;
|
|
1179
|
+
} finally {
|
|
1180
|
+
clearTimeout(timer);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/* --------------------------------------------- 已装插件的更新检查(v0.5.0) */
|
|
1185
|
+
/** 逐包出站请求的并发上限。全串行会拖到十几秒,全并发容易触发镜像限流。 */
|
|
1186
|
+
const UPDATE_CONCURRENCY = 6;
|
|
1187
|
+
/** 结果缓存。比目录的 5 分钟更长:这一段是 N 个出站请求,不该被反复触发。 */
|
|
1188
|
+
const UPDATE_TTL_MS = 10 * 60 * 1000;
|
|
1189
|
+
/** 「检查更新」按钮连点时的最小间隔:缓存可以绕过,但镜像不能被连点打爆。 */
|
|
1190
|
+
const UPDATE_MIN_FORCE_MS = 30 * 1000;
|
|
1191
|
+
let updatesCache = { at: 0, value: null };
|
|
1192
|
+
|
|
1193
|
+
/** profile 目录。与 profileManifest() 同源,避免两处各拼一次路径。 */
|
|
1194
|
+
function profileDir() {
|
|
1195
|
+
return path.join(os.homedir(), ".dsh", "profiles", PROFILE);
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* profile 里声明过的依赖清单(即「用户装了什么」)。
|
|
1200
|
+
*
|
|
1201
|
+
* 纯函数 + 入参可注入,便于单测;`bundled` 与 pkgState() 同口径
|
|
1202
|
+
* —— bundles 是更强的信号:包躺在 node_modules 里也可能根本没被加载。
|
|
1203
|
+
*/
|
|
1204
|
+
export function pluginCandidates(manifest) {
|
|
1205
|
+
if (manifest === null || typeof manifest !== "object") return [];
|
|
1206
|
+
const deps = manifest.dependencies && typeof manifest.dependencies === "object" ? manifest.dependencies : null;
|
|
1207
|
+
if (deps === null) return [];
|
|
1208
|
+
const profile = manifest.dsh && manifest.dsh.profile ? manifest.dsh.profile : null;
|
|
1209
|
+
const bundles = profile && Array.isArray(profile.bundles) ? profile.bundles : [];
|
|
1210
|
+
/* spec 一并带出来:它决定"这个包能不能靠 plugin add 升级"(见 classifySpec) */
|
|
1211
|
+
return Object.keys(deps).sort().map((name) => ({
|
|
1212
|
+
name,
|
|
1213
|
+
bundled: bundles.includes(name),
|
|
1214
|
+
spec: typeof deps[name] === "string" ? deps[name] : "",
|
|
1215
|
+
}));
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
/**
|
|
1219
|
+
* 依赖 spec 的形态 —— 它决定"还能不能升级",这是实测撞出来的三类:
|
|
1220
|
+
*
|
|
1221
|
+
* local : `link:…` / `file:…` —— **本地开发链接**,指向本机源码目录。
|
|
1222
|
+
* "升级"它等于去装 npm 上的版本,既会被 dsh 的兼容性闸门拒,
|
|
1223
|
+
* **语义上也是错的**(用户自己正在开发这个包)。实测本机 desktop profile
|
|
1224
|
+
* 20 个依赖里有 11 个是这种,其中就包括本插件自己。
|
|
1225
|
+
* pinned : `0.5.27` 这种**精确锁定**。`plugin add` 不会把它挪走(实测版本号纹丝不动)。
|
|
1226
|
+
* range : `^0.8.5` 这类允许浮动的范围。
|
|
1227
|
+
*
|
|
1228
|
+
* 判定只看清单里写的形态,不猜语义 —— 猜错会误伤(比如把范围包当成锁定包)。
|
|
1229
|
+
*/
|
|
1230
|
+
export function classifySpec(spec) {
|
|
1231
|
+
const value = String(spec || "");
|
|
1232
|
+
if (value.startsWith("link:") || value.startsWith("file:")) return "local";
|
|
1233
|
+
if (/^\d/.test(value)) return "pinned";
|
|
1234
|
+
return "range";
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* 读一个已装包在 profile 里的实际版本,并判断它是不是 dsh 插件。
|
|
1239
|
+
*
|
|
1240
|
+
* 判据按**插件契约**判,不按包名猜(`dsh-` 前缀不是契约,第三方包名五花八门):
|
|
1241
|
+
* · package.json 里声明了 dsh 字段(dsh.bundle / dsh.client),或
|
|
1242
|
+
* · 依赖里出现 @deepseek-ai/dsh —— 与站点 lib/detect.ts 的分层判据同源。
|
|
1243
|
+
* 读不到返回 null(未知),调用方必须把它和「不是插件」分开处理。
|
|
1244
|
+
*/
|
|
1245
|
+
export function readInstalled(name, dir = profileDir()) {
|
|
1246
|
+
try {
|
|
1247
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(dir, "node_modules", name, "package.json"), "utf8"));
|
|
1248
|
+
const deps = manifest.dependencies && typeof manifest.dependencies === "object" ? manifest.dependencies : {};
|
|
1249
|
+
const peers = manifest.peerDependencies && typeof manifest.peerDependencies === "object" ? manifest.peerDependencies : {};
|
|
1250
|
+
return {
|
|
1251
|
+
version: typeof manifest.version === "string" ? manifest.version : null,
|
|
1252
|
+
plugin: Boolean(manifest.dsh && typeof manifest.dsh === "object")
|
|
1253
|
+
|| Object.prototype.hasOwnProperty.call(deps, "@deepseek-ai/dsh")
|
|
1254
|
+
|| Object.prototype.hasOwnProperty.call(peers, "@deepseek-ai/dsh"),
|
|
1255
|
+
/* 原文描述。中文名/说明都没有时,界面拿它兜底并明确标注「未汉化」——不假装有中文。 */
|
|
1256
|
+
desc: typeof manifest.description === "string" ? manifest.description.trim().slice(0, 200) : "",
|
|
1257
|
+
};
|
|
1258
|
+
} catch (error) {
|
|
1259
|
+
return null;
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/* -------------------------------------- 已装插件的「这是谁」(v0.5.0) */
|
|
1264
|
+
/**
|
|
1265
|
+
* 只显示 npm 包名(dsh-context / billion-context),用户认不出这是哪个插件 ——
|
|
1266
|
+
* 「更新」页面的价值就塌了一半(它要回答的是"我装的哪些该升级",前提是认得出是谁)。
|
|
1267
|
+
*
|
|
1268
|
+
* 两个来源**互补且都不完整**(2026-10-12 实测本机 desktop profile 的 20 个依赖):
|
|
1269
|
+
* · 本机 `<pkg>/locale/zh.json` 的 meta.title:15/20 —— 离线、零请求,
|
|
1270
|
+
* 而且是**包自己声明**的,最贴近"这是谁";
|
|
1271
|
+
* · 站点目录(`take=500`,而目录共 17304 条):9/20 —— 但补上了本机完全没有的那 5 个。
|
|
1272
|
+
* 并集 20/20。单用任何一个都会让一部分插件只剩裸包名 —— 那就等于没说。
|
|
1273
|
+
*/
|
|
1274
|
+
const IDENTITY_TTL_MS = 30 * 60 * 1000;
|
|
1275
|
+
let identityCache = { at: 0, value: new Map() };
|
|
1276
|
+
|
|
1277
|
+
/**
|
|
1278
|
+
* 读包自己声明的中文元数据(离线)。读不到返回 null —— **不猜、不翻译、不编造**。
|
|
1279
|
+
*
|
|
1280
|
+
* 顺带清掉 meta.title 里常见的那截包名:社区惯例写成
|
|
1281
|
+
* 「模型优惠时钟 (dsh-client-ui-model-clock)」,而包名在界面上另有位置,
|
|
1282
|
+
* 重复一次只会让行更挤。只在括号里含 ASCII 字母时才当它是包名(「插件(官方)」不该被砍)。
|
|
1283
|
+
*/
|
|
1284
|
+
export function localIdentity(name, dir = profileDir()) {
|
|
1285
|
+
const base = path.join(dir, "node_modules", name, "locale");
|
|
1286
|
+
for (const file of ["zh.json", "zh-CN.json"]) {
|
|
1287
|
+
try {
|
|
1288
|
+
const meta = JSON.parse(fs.readFileSync(path.join(base, file), "utf8")).meta || {};
|
|
1289
|
+
const title = typeof meta.title === "string" ? meta.title.trim() : "";
|
|
1290
|
+
if (!/[\u4e00-\u9fff]/.test(title)) continue;
|
|
1291
|
+
const cleaned = title.replace(/\s*[((][^))]*[A-Za-z@][^))]*[))]\s*$/, "").trim() || title;
|
|
1292
|
+
return { nameZh: cleaned.slice(0, 40), note: pickZh(meta.description, 80) || "" };
|
|
1293
|
+
} catch (error) {
|
|
1294
|
+
/* 没有这个文件、或不是 JSON —— 继续试下一个候选文件名 */
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
return null;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/** 站点目录里 pkgName → { nameZh, note } 的映射(一次 take=500,缓存)。 */
|
|
1301
|
+
async function fetchCatalogIdentity() {
|
|
1302
|
+
const now = Date.now();
|
|
1303
|
+
if (now - identityCache.at < IDENTITY_TTL_MS) return identityCache.value;
|
|
1304
|
+
const controller = new AbortController();
|
|
1305
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
1306
|
+
try {
|
|
1307
|
+
const response = await fetch(`${UPSTREAM}?take=500`, {
|
|
1308
|
+
headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
|
|
1309
|
+
signal: controller.signal,
|
|
1310
|
+
});
|
|
1311
|
+
if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
|
|
1312
|
+
const body = await response.json();
|
|
1313
|
+
const map = new Map();
|
|
1314
|
+
(Array.isArray(body && body.plugins) ? body.plugins : []).forEach((item) => {
|
|
1315
|
+
const pkg = item && item.installCheck && item.installCheck.pkgName;
|
|
1316
|
+
if (!pkg) return;
|
|
1317
|
+
const nameZh = typeof item.nameZh === "string" && /[\u4e00-\u9fff]/.test(item.nameZh) ? item.nameZh.trim().slice(0, 40) : "";
|
|
1318
|
+
const note = pickZh(item.tagline, 80) || pickZh(item.descriptionZh, 80) || "";
|
|
1319
|
+
if (nameZh || note) map.set(pkg, { nameZh, note });
|
|
1320
|
+
});
|
|
1321
|
+
identityCache = { at: now, value: map };
|
|
1322
|
+
return map;
|
|
1323
|
+
} catch (error) {
|
|
1324
|
+
/* 站点不可达就只靠本机 locale —— 降级,不影响更新检查本身 */
|
|
1325
|
+
return new Map();
|
|
1326
|
+
} finally {
|
|
1327
|
+
clearTimeout(timer);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/** 安装目录里的版本号;查不到返回 null(未知,不等于"没装")。 */
|
|
1332
|
+
function installedVersionOf(pkg) {
|
|
1333
|
+
const info = readInstalled(pkg);
|
|
1334
|
+
return info ? info.version : null;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
/** 一个目录条目对应的已装版本(先按 npm 包名查,退回 owner/repo),查不到就 null。 */
|
|
1338
|
+
function installedOf(item, map) {
|
|
1339
|
+
if (!item || !map) return null;
|
|
1340
|
+
return map[item.pkg || ""] || map[item.fullName || ""] || null;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/**
|
|
1344
|
+
* profile 里"已装了哪些、装的什么版本"(键为包名)。
|
|
1345
|
+
*
|
|
1346
|
+
* 用途:目录卡片上把「安装」标成「已安装 vX」—— 实测有用户对着一个早就装好的插件
|
|
1347
|
+
* 反复点「安装」,然后判定"安装不成功"(他无从知道那东西其实已经在跑了)。
|
|
1348
|
+
* 30 秒缓存:搜索是边打字边发的,不该每次都读几十个 package.json。
|
|
1349
|
+
*/
|
|
1350
|
+
let installedCache = { at: 0, value: {} };
|
|
1351
|
+
function installedMap() {
|
|
1352
|
+
const now = Date.now();
|
|
1353
|
+
if (now - installedCache.at < 30 * 1000) return installedCache.value;
|
|
1354
|
+
const dir = profileDir();
|
|
1355
|
+
const map = {};
|
|
1356
|
+
pluginCandidates(profileManifest()).forEach((row) => {
|
|
1357
|
+
const info = readInstalled(row.name, dir);
|
|
1358
|
+
if (info && info.version) map[row.name] = info.version;
|
|
1359
|
+
});
|
|
1360
|
+
installedCache = { at: now, value: map };
|
|
1361
|
+
return map;
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
/** 带并发上限的 map:保住顺序,也别把镜像打爆。 */
|
|
1365
|
+
async function mapLimit(items, limit, worker) {
|
|
1366
|
+
const results = new Array(items.length);
|
|
1367
|
+
let cursor = 0;
|
|
1368
|
+
const runners = [];
|
|
1369
|
+
for (let index = 0; index < Math.min(limit, items.length); index += 1) {
|
|
1370
|
+
runners.push((async () => {
|
|
1371
|
+
while (cursor < items.length) {
|
|
1372
|
+
/* 取号与自增都是**同步**完成的(在 await 之前),所以两个 runner 不会拿到同一个下标 */
|
|
1373
|
+
const current = cursor;
|
|
1374
|
+
cursor += 1;
|
|
1375
|
+
results[current] = await worker(items[current], current);
|
|
1376
|
+
}
|
|
1377
|
+
})());
|
|
1378
|
+
}
|
|
1379
|
+
await Promise.all(runners);
|
|
1380
|
+
return results;
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
/** 排序权重:可升级的最前,其次未知,最后已最新 —— 让「该做什么」排在最上面。 */
|
|
1384
|
+
function rankUpdate(entry) {
|
|
1385
|
+
if (entry.outdated === true) return 0;
|
|
1386
|
+
if (entry.outdated === null) return 1;
|
|
1387
|
+
return 2;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
/** 按「可升级 → 未知 → 已最新,再按包名」排序(就地排序,返回同一个数组便于断言)。 */
|
|
1391
|
+
export function sortUpdates(entries) {
|
|
1392
|
+
return (Array.isArray(entries) ? entries : []).slice().sort((a, b) => (rankUpdate(a) - rankUpdate(b)) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/**
|
|
1396
|
+
* 组装一次完整的更新检查结果:本插件自身 + 已装插件。
|
|
1397
|
+
*
|
|
1398
|
+
* 本插件**从已装列表里摘出来单独给**(self)—— 它同时出现在 profile 的 dependencies 里,
|
|
1399
|
+
* 两处都列会让人以为有两个不同的东西要升级。
|
|
1400
|
+
*/
|
|
1401
|
+
async function buildUpdates() {
|
|
1402
|
+
const dir = profileDir();
|
|
1403
|
+
const candidates = pluginCandidates(profileManifest());
|
|
1404
|
+
const installed = await mapLimit(candidates, UPDATE_CONCURRENCY, (candidate) => readInstalled(candidate.name, dir));
|
|
1405
|
+
const rows = candidates.map((candidate, index) => ({ ...candidate, info: installed[index], kind: classifySpec(candidate.spec) }));
|
|
1406
|
+
/* 本地链接的包**不参与更新检查**:它们的"版本"来自本机源码,跟 npm 上的最新版没有关系。
|
|
1407
|
+
实测本机 desktop profile 的 20 个依赖里有 11 个是这种(含本插件自己)——
|
|
1408
|
+
把它们当"可升级"列出来,只会让用户点一次、失败一次(而且方向本来就是错的)。 */
|
|
1409
|
+
const locals = rows.filter((row) => row.kind === "local").map((row) => ({ name: row.name, spec: row.spec }));
|
|
1410
|
+
const plugins = rows.filter((row) => row.kind !== "local" && row.info && row.info.plugin && row.name !== PKG_NAME);
|
|
1411
|
+
const versions = await mapLimit(plugins, UPDATE_CONCURRENCY, (row) => fetchNpmVersion(row.name));
|
|
1412
|
+
|
|
1413
|
+
/* 「这是谁」:先读本机 locale(离线、零请求),缺口再用站点目录补一次 —— 并集才完整 */
|
|
1414
|
+
const identity = new Map();
|
|
1415
|
+
plugins.forEach((row) => {
|
|
1416
|
+
const found = localIdentity(row.name, dir);
|
|
1417
|
+
if (found) identity.set(row.name, found);
|
|
1418
|
+
});
|
|
1419
|
+
if (plugins.some((row) => {
|
|
1420
|
+
const found = identity.get(row.name);
|
|
1421
|
+
return !found || !found.nameZh || !found.note;
|
|
1422
|
+
})) {
|
|
1423
|
+
const site = await fetchCatalogIdentity();
|
|
1424
|
+
plugins.forEach((row) => {
|
|
1425
|
+
const extra = site.get(row.name);
|
|
1426
|
+
if (!extra) return;
|
|
1427
|
+
const found = identity.get(row.name) || { nameZh: "", note: "" };
|
|
1428
|
+
identity.set(row.name, { nameZh: found.nameZh || extra.nameZh, note: found.note || extra.note });
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
let selfIdentity = localIdentity(PKG_NAME, dir);
|
|
1433
|
+
if (!selfIdentity || !selfIdentity.nameZh || !selfIdentity.note) {
|
|
1434
|
+
const extra = (await fetchCatalogIdentity()).get(PKG_NAME);
|
|
1435
|
+
if (extra) {
|
|
1436
|
+
selfIdentity = {
|
|
1437
|
+
nameZh: (selfIdentity && selfIdentity.nameZh) || extra.nameZh,
|
|
1438
|
+
note: (selfIdentity && selfIdentity.note) || extra.note,
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
if (!selfIdentity) selfIdentity = { nameZh: "", note: "" };
|
|
1443
|
+
|
|
1444
|
+
const selfLatest = await fetchNpmVersion(PKG_NAME);
|
|
1445
|
+
const entries = sortUpdates(plugins.map((row, index) => {
|
|
1446
|
+
const current = row.info.version;
|
|
1447
|
+
const latest = versions[index];
|
|
1448
|
+
const found = identity.get(row.name) || { nameZh: "", note: "" };
|
|
1449
|
+
return {
|
|
1450
|
+
name: row.name,
|
|
1451
|
+
/* 中文名可能为空 —— 界面回落显示包名,并明确标注「未汉化」,绝不假装有中文 */
|
|
1452
|
+
nameZh: found.nameZh,
|
|
1453
|
+
/* 说明:优先包自己/站点的中文,其次本机 package.json 的原文(英文,界面会标未汉化) */
|
|
1454
|
+
note: found.note || row.info.desc,
|
|
1455
|
+
bundled: row.bundled,
|
|
1456
|
+
/* 清单里的 spec 与它的形态(range / pinned)。界面据此说明"为什么升不动"。 */
|
|
1457
|
+
spec: row.spec,
|
|
1458
|
+
kind: row.kind,
|
|
1459
|
+
current,
|
|
1460
|
+
latest,
|
|
1461
|
+
/* 三态:任一端拿不到就不下结论(null),绝不用 false 兜底 */
|
|
1462
|
+
outdated: latest && current ? compareVersions(current, latest) < 0 : null,
|
|
1463
|
+
/* ⚠️ 用**具体版本号**(dsh-context@0.69.1),不要 `@latest`。
|
|
1464
|
+
实测(2026-10-12,桌面版 dsh 0.2.0-rc.2):
|
|
1465
|
+
dsh plugin --profile desktop add dsh-context@latest → 静默空转(pnpm.log 0 字节、版本不动)
|
|
1466
|
+
dsh plugin --profile desktop add dsh-context@0.69.1 → 成功(Done in 1.7s)
|
|
1467
|
+
既然更新检查已经知道目标版本,就没有理由再走那条空转的路。 */
|
|
1468
|
+
upgrade: latest
|
|
1469
|
+
? `dsh plugin --profile ${PROFILE} add ${row.name}@${latest}`
|
|
1470
|
+
: `dsh plugin --profile ${PROFILE} add ${row.name}@latest`,
|
|
1471
|
+
};
|
|
1472
|
+
}));
|
|
1473
|
+
|
|
1474
|
+
return {
|
|
1475
|
+
ok: true,
|
|
1476
|
+
rev: SHAPE_REV,
|
|
1477
|
+
profile: PROFILE,
|
|
1478
|
+
fetchedAt: Date.now(),
|
|
1479
|
+
self: {
|
|
1480
|
+
name: PKG_NAME,
|
|
1481
|
+
nameZh: selfIdentity.nameZh,
|
|
1482
|
+
note: selfIdentity.note,
|
|
1483
|
+
current: VERSION,
|
|
1484
|
+
latest: selfLatest,
|
|
1485
|
+
outdated: selfLatest ? compareVersions(VERSION, selfLatest) < 0 : null,
|
|
1486
|
+
/* 同已装插件:走具体版本号,`@latest` 在 dsh 这条路上是空转的(见 buildUpdates 的注释) */
|
|
1487
|
+
upgrade: selfLatest
|
|
1488
|
+
? `dsh plugin --profile ${PROFILE} add ${PKG_NAME}@${selfLatest}`
|
|
1489
|
+
: `dsh plugin --profile ${PROFILE} add ${PKG_NAME}@latest`,
|
|
1490
|
+
},
|
|
1491
|
+
plugins: entries,
|
|
1492
|
+
/* 本地链接的包(link:/file:)单列:它们不参与更新检查,但用户需要知道"它们为什么不在列表里" */
|
|
1493
|
+
locals: locals,
|
|
1494
|
+
counts: {
|
|
1495
|
+
installed: candidates.length,
|
|
1496
|
+
skipped: candidates.length - plugins.length,
|
|
1497
|
+
local: locals.length,
|
|
1498
|
+
checked: entries.length,
|
|
1499
|
+
outdated: entries.filter((entry) => entry.outdated === true).length,
|
|
1500
|
+
unknown: entries.filter((entry) => entry.outdated === null).length,
|
|
1501
|
+
},
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
|
|
639
1505
|
export function apply(ctx) {
|
|
640
1506
|
// 「分类精选」:站点 /best 专区的同源数据(月度策展,每小类 2~3 个)
|
|
641
1507
|
registerRoute(ctx, "/api/dpharness/best", async (req, res) => {
|
|
@@ -653,7 +1519,34 @@ export function apply(ctx) {
|
|
|
653
1519
|
fetchedAt: new Date(result.fetchedAt).toISOString(),
|
|
654
1520
|
month: result.month,
|
|
655
1521
|
total: result.total,
|
|
656
|
-
|
|
1522
|
+
/* 同搜索:给榜单条目也标上「已安装 vX」(那几张卡片同样有「安装」按钮) */
|
|
1523
|
+
categories: (Array.isArray(result.categories) ? result.categories : []).map((cat) => Object.assign({}, cat, {
|
|
1524
|
+
subs: (Array.isArray(cat.subs) ? cat.subs : []).map((sub) => Object.assign({}, sub, {
|
|
1525
|
+
items: (Array.isArray(sub.items) ? sub.items : []).map((item) => Object.assign({}, item, { installed: installedOf(item, installedMap()) })),
|
|
1526
|
+
})),
|
|
1527
|
+
})),
|
|
1528
|
+
});
|
|
1529
|
+
} catch (error) {
|
|
1530
|
+
sendJson(res, 502, { ok: false, error: String((error && error.message) || error) });
|
|
1531
|
+
}
|
|
1532
|
+
});
|
|
1533
|
+
|
|
1534
|
+
// 「组合方案套装」:站点 /sets 专区的同源数据(跨插件纵向组合,见 fetchSets 注释)
|
|
1535
|
+
registerRoute(ctx, "/api/dpharness/sets", async (req, res) => {
|
|
1536
|
+
if (req.method !== "GET") {
|
|
1537
|
+
res.writeHead(405, { allow: "GET" });
|
|
1538
|
+
res.end();
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
try {
|
|
1542
|
+
const result = await fetchSets();
|
|
1543
|
+
sendJson(res, 200, {
|
|
1544
|
+
ok: true,
|
|
1545
|
+
source: `${SITE}/sets`,
|
|
1546
|
+
cached: result.cached,
|
|
1547
|
+
fetchedAt: new Date(result.fetchedAt).toISOString(),
|
|
1548
|
+
total: result.total,
|
|
1549
|
+
sets: result.sets,
|
|
657
1550
|
});
|
|
658
1551
|
} catch (error) {
|
|
659
1552
|
sendJson(res, 502, { ok: false, error: String((error && error.message) || error) });
|
|
@@ -676,7 +1569,9 @@ export function apply(ctx) {
|
|
|
676
1569
|
fetchedAt: new Date(result.fetchedAt).toISOString(),
|
|
677
1570
|
query: Object.fromEntries(params),
|
|
678
1571
|
count: result.count,
|
|
679
|
-
|
|
1572
|
+
total: result.total,
|
|
1573
|
+
/* 「已装了哪些」**不进缓存**:装完要立刻在卡片上看到「已安装 vX」 */
|
|
1574
|
+
plugins: result.plugins.map((item) => Object.assign({}, item, { installed: installedOf(item, installedMap()) })),
|
|
680
1575
|
});
|
|
681
1576
|
} catch (error) {
|
|
682
1577
|
const message = error && error.name === "AbortError" ? "upstream timeout" : String((error && error.message) || error);
|
|
@@ -751,8 +1646,26 @@ export function apply(ctx) {
|
|
|
751
1646
|
return;
|
|
752
1647
|
}
|
|
753
1648
|
if (installJob.active) {
|
|
754
|
-
|
|
755
|
-
|
|
1649
|
+
const elapsed = Date.now() - installJob.startedAt;
|
|
1650
|
+
if (elapsed > INSTALL_TIMEOUT_MS + INSTALL_SETTLE_MS) {
|
|
1651
|
+
/* 早已越过「超时 + 宽限」却还标着 active ⇒ 只可能是收尾路径没跑到
|
|
1652
|
+
(宿主从旧版本热更新上来、计时器所在进程被挂起…)。这时**自愈**比让用户去
|
|
1653
|
+
重启 dsh 合理:现场实测(2026-10-14)用户因此彻底装不了任何插件,
|
|
1654
|
+
而界面上只有一句英文报错、没有任何自救入口。 */
|
|
1655
|
+
console.warn(`[dpharness] install job stuck for ${Math.round(elapsed / 1000)}s — self-healing`);
|
|
1656
|
+
forceUnlock("stale", installSeq);
|
|
1657
|
+
} else {
|
|
1658
|
+
sendJson(res, 409, {
|
|
1659
|
+
ok: false,
|
|
1660
|
+
/* 保留原文:它同时是**兼容旧客户端的兜底文案**,按 why 翻的界面读 why 就好 */
|
|
1661
|
+
error: "an install is already running",
|
|
1662
|
+
/* why 是闭集枚举:界面据此出中文,别把英文原文直接摊给用户 */
|
|
1663
|
+
why: "busy",
|
|
1664
|
+
seconds: Math.round(elapsed / 1000),
|
|
1665
|
+
job: jobView(),
|
|
1666
|
+
});
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
756
1669
|
}
|
|
757
1670
|
let input;
|
|
758
1671
|
try {
|
|
@@ -766,8 +1679,10 @@ export function apply(ctx) {
|
|
|
766
1679
|
sendJson(res, 400, { ok: false, error: "unsafe plugin target rejected" });
|
|
767
1680
|
return;
|
|
768
1681
|
}
|
|
769
|
-
|
|
770
|
-
|
|
1682
|
+
/* verb 是**闭集**:只认 add / remove,别的一律按 add 走(不接受任何未枚举的动作) */
|
|
1683
|
+
const verb = input && input.verb === "remove" ? "remove" : "add";
|
|
1684
|
+
startInstall(target, verb);
|
|
1685
|
+
sendJson(res, 202, { ok: true, target, verb, profile: PROFILE, job: jobView() });
|
|
771
1686
|
});
|
|
772
1687
|
|
|
773
1688
|
/**
|
|
@@ -806,6 +1721,87 @@ export function apply(ctx) {
|
|
|
806
1721
|
});
|
|
807
1722
|
});
|
|
808
1723
|
|
|
1724
|
+
/**
|
|
1725
|
+
* 更新日志(只读)。
|
|
1726
|
+
*
|
|
1727
|
+
* 三个字段的语义必须分开、**不能互相兜底**:
|
|
1728
|
+
* current = 本进程加载的插件版本(来自代码常量,唯一可信来源)
|
|
1729
|
+
* latest = npm 最新版;null = 没查到(≠ 已是最新)
|
|
1730
|
+
* outdated = true / false / null(null = 无从判断,例:离线)
|
|
1731
|
+
* 同一条响应里给出 upgrade 命令,并用**本机真实 profile** 拼 —— 用户不用猜 profile 名
|
|
1732
|
+
* (桌面版是 desktop 而不是 web,这个坑 2026-09-30 已经踩过一次)。
|
|
1733
|
+
*
|
|
1734
|
+
* 日志正文来自内置底稿(lib/changelog.js);仓库发过 Release 之后,
|
|
1735
|
+
* releases 会按版本号覆盖/补齐底稿(mergeChangelog 的规则写在那里)。
|
|
1736
|
+
*/
|
|
1737
|
+
registerRoute(ctx, "/api/dpharness/changelog", async (req, res) => {
|
|
1738
|
+
if (req.method !== "GET") {
|
|
1739
|
+
res.writeHead(405, { allow: "GET" });
|
|
1740
|
+
res.end();
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
const now = Date.now();
|
|
1744
|
+
if (changelogCache && now - changelogCache.at < CACHE_TTL_MS) {
|
|
1745
|
+
sendJson(res, 200, { ...changelogCache.value, cached: true });
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
// 两个外部查询互不依赖:并发发出去,任一失败都不影响另一个
|
|
1749
|
+
const [releases, latest] = await Promise.all([fetchReleases(), fetchNpmVersion(PKG_NAME)]);
|
|
1750
|
+
const value = {
|
|
1751
|
+
ok: true,
|
|
1752
|
+
rev: SHAPE_REV,
|
|
1753
|
+
current: VERSION,
|
|
1754
|
+
latest,
|
|
1755
|
+
outdated: latest ? compareVersions(VERSION, latest) < 0 : null,
|
|
1756
|
+
repo: REPO,
|
|
1757
|
+
source: releases && releases.length > 0 ? "builtin+github" : "builtin",
|
|
1758
|
+
upgrade: `dsh plugin --profile ${PROFILE} add dsh-dpharness@latest`,
|
|
1759
|
+
entries: mergeChangelog(CHANGELOG, releases),
|
|
1760
|
+
cached: false,
|
|
1761
|
+
fetchedAt: now,
|
|
1762
|
+
};
|
|
1763
|
+
changelogCache = { at: now, value };
|
|
1764
|
+
sendJson(res, 200, value);
|
|
1765
|
+
});
|
|
1766
|
+
|
|
1767
|
+
/**
|
|
1768
|
+
* 插件更新检查(只读)。
|
|
1769
|
+
*
|
|
1770
|
+
* 两件事一起回答(2026-10-12 的需求「新增检查插件更新入口,更新红点提醒能力」):
|
|
1771
|
+
* 1. 本插件自己有没有新版本(self);
|
|
1772
|
+
* 2. 用户**已安装的 dsh 插件**里,哪些有更新的版本(plugins)。
|
|
1773
|
+
*
|
|
1774
|
+
* 数据来源与代价必须写清楚:
|
|
1775
|
+
* · 「装了哪些」= profile 的 dependencies,本机磁盘读取,零网络;
|
|
1776
|
+
* · 「最新版」= 逐包问 npmmirror(本机实测 23 个依赖),故并发上限 6、整体缓存 10 分钟;
|
|
1777
|
+
* · 站点 /api/plugins **不提供版本字段**,所以没法拿目录当版本源 —— 只能逐包问 registry。
|
|
1778
|
+
* `?refresh=1` 可绕过缓存(「检查更新」按钮),但 30 秒内只放行一次,避免连点把镜像打爆。
|
|
1779
|
+
*
|
|
1780
|
+
* 三态纪律同 changelog:outdated 为 true / false / null(null = 任一端拿不到,不下结论)。
|
|
1781
|
+
*/
|
|
1782
|
+
registerRoute(ctx, "/api/dpharness/updates", async (req, res) => {
|
|
1783
|
+
if (req.method !== "GET") {
|
|
1784
|
+
res.writeHead(405, { allow: "GET" });
|
|
1785
|
+
res.end();
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
const now = Date.now();
|
|
1789
|
+
const fresh = now - updatesCache.at < UPDATE_TTL_MS;
|
|
1790
|
+
const force = readParams(req).get("refresh") === "1";
|
|
1791
|
+
if (updatesCache.value && fresh && !(force && now - updatesCache.at >= UPDATE_MIN_FORCE_MS)) {
|
|
1792
|
+
sendJson(res, 200, { ...updatesCache.value, cached: true });
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
try {
|
|
1796
|
+
const value = await buildUpdates();
|
|
1797
|
+
updatesCache = { at: Date.now(), value };
|
|
1798
|
+
sendJson(res, 200, { ...value, cached: false });
|
|
1799
|
+
} catch (error) {
|
|
1800
|
+
/* 失败必须显式报错,不能悄悄回一份空清单 —— 空清单会被界面读成「全都已是最新」 */
|
|
1801
|
+
sendJson(res, 500, { ok: false, error: String((error && error.message) || error) });
|
|
1802
|
+
}
|
|
1803
|
+
});
|
|
1804
|
+
|
|
809
1805
|
registerRoute(ctx, "/api/dpharness/meta", (req, res) => {
|
|
810
1806
|
if (req.method !== "GET") {
|
|
811
1807
|
res.writeHead(405, { allow: "GET" });
|
|
@@ -824,9 +1820,12 @@ export function apply(ctx) {
|
|
|
824
1820
|
routes: [
|
|
825
1821
|
"/api/dpharness/search",
|
|
826
1822
|
"/api/dpharness/best",
|
|
1823
|
+
"/api/dpharness/sets",
|
|
827
1824
|
"/api/dpharness/event",
|
|
828
1825
|
"/api/dpharness/install",
|
|
829
1826
|
"/api/dpharness/postinstall",
|
|
1827
|
+
"/api/dpharness/changelog",
|
|
1828
|
+
"/api/dpharness/updates",
|
|
830
1829
|
"/api/dpharness/meta",
|
|
831
1830
|
],
|
|
832
1831
|
events: Array.from(EVENT_ALLOWLIST),
|