dsh-pluginmarket-plus 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1270 @@
1
+ /**
2
+ * dsh-pluginmarket-plus —— 插件市场索引本地缓存(Host 半边)。
3
+ *
4
+ * ## 它解决什么问题
5
+ *
6
+ * 官方插件市场(插件页 → 发现)由 `pluginMarket` 服务读取索引源,单次抓取限时
7
+ * 15 秒、失败不落盘。真实的索引动辄 1–8 MB,从这里访问 `cdn.dsh.so` 要 80 秒、
8
+ * `api.dshfind.com` 要 18 秒,于是「搜索不出来 / 索引超时」。本插件在后台用更长
9
+ * 的时间窗把索引抓下来、写到本地磁盘,再通过本机 HTTP 路由提供一份镜像;把发现页
10
+ * 的索引源换成本地镜像后,抓取是毫秒级的,搜索不再超时。
11
+ *
12
+ * ## 组成
13
+ *
14
+ * - 磁盘缓存:`<profile>/.pluginmarket-plus/index-<id>.json` + `state.json`。
15
+ * - 定时刷新:默认每 4 小时一次(可关、可调);启动时补一次过期/缺失的源。
16
+ * - 本地镜像:`http://127.0.0.1:<port>/pluginmarket-plus/index/<id>.json`。
17
+ * 这份路由必须免登录——`pluginMarket` 是在 Host 进程里用裸 `fetch` 取索引的。
18
+ * - 设置页桥:`/api/pluginmarket-plus/*`(经 `connection.fetch`,仅 owner 可访问)。
19
+ * - 发现页接管:把 `plugin-market` 的 `indexes` 在「上游地址」和「本地镜像」之间
20
+ * 切换;只替换已经缓存成功的源,没缓存成功的继续保持直连。
21
+ *
22
+ * @module dsh-pluginmarket-plus
23
+ */
24
+
25
+ import { join, resolve } from 'node:path'
26
+ import z from '@deepseek-ai/schemastery'
27
+ import { CacheStore, sourceId } from './store.js'
28
+ import { fetchIndex, indexTitle, messageOf } from './refresh.js'
29
+ import { buildGitSpec, checkCandidates, collectCandidates, createUpdateQueue, latestGitFromIndex, parseGitSpec, UPDATE_STEP_STAGE } from './updates.js'
30
+
31
+ /** 包名(Client 模块 id 必须与它一致)。 */
32
+ export const name = 'dsh-pluginmarket-plus'
33
+
34
+ /** 本地镜像路由前缀。 */
35
+ export const MIRROR_PATH = '/pluginmarket-plus/index'
36
+
37
+ /** 公开状态路由(只读,便于排查问题)。 */
38
+ const PUBLIC_STATUS_PATH = '/pluginmarket-plus/status.json'
39
+
40
+ /** 设置页桥前缀。 */
41
+ const API_PREFIX = '/api/pluginmarket-plus'
42
+
43
+ /** 镜像 id 的路径匹配。 */
44
+ const MIRROR_ID = /^\/pluginmarket-plus\/index\/([a-f0-9]{16})\.json$/u
45
+
46
+ /** 最长 7 天的刷新间隔,避免 setTimeout 溢出。 */
47
+ const MAX_INTERVAL_HOURS = 168
48
+
49
+ /** 配置。面板上可改的字段都声明为 volatile,修改后无需重载插件。 */
50
+ export const Config = z.object({
51
+ /** 要缓存的索引源;留空时自动接管「发现」页当前配置的源。 */
52
+ sources: z.array(z.string()).default([]).volatile(),
53
+ /** 是否按间隔自动刷新。 */
54
+ autoRefresh: z.boolean().default(true).volatile(),
55
+ /** 自动刷新间隔(小时)。 */
56
+ refreshIntervalHours: z.number().min(0.25).max(MAX_INTERVAL_HOURS).default(4).volatile(),
57
+ /** 是否让「发现」页优先使用本地镜像。 */
58
+ managePluginMarket: z.boolean().default(true).volatile(),
59
+ /** 单次抓取超时(毫秒)。索引很大,默认给到 2 分钟。 */
60
+ fetchTimeoutMs: z.natural().min(1000).default(120000),
61
+ /** 单个索引正文上限(字节)。 */
62
+ maxBytes: z.natural().min(1).default(64 * 1024 * 1024),
63
+ /** 失败重试次数。 */
64
+ retries: z.natural().min(0).max(5).default(2),
65
+ /** 缓存目录,相对 profile 目录。 */
66
+ cacheDir: z.string().default('.pluginmarket-plus'),
67
+ /** 「可更新」列表是否包含已禁用的插件(默认关)。 */
68
+ updatesIncludeDisabled: z.boolean().default(false).volatile(),
69
+ /** 「可更新」列表是否包含预发布 / 已废弃版本(默认关)。 */
70
+ updatesIncludePrerelease: z.boolean().default(false).volatile(),
71
+ /** 「可更新」列表是否显示「检查失败」的项(默认关)。 */
72
+ updatesShowFailed: z.boolean().default(false).volatile(),
73
+ })
74
+
75
+ /**
76
+ * 读取一个可能是 volatile 引用的配置值。
77
+ * @param {unknown} value - 配置字段(普通值或 `{ get() }` 引用)。
78
+ * @param {unknown} fallback - 引用缺失时的回退值。
79
+ * @returns {unknown} 当前值。
80
+ */
81
+ function live(value, fallback) {
82
+ if (value !== null && typeof value === 'object' && typeof (/** @type {{ get?: unknown }} */ (value).get) === 'function') {
83
+ return /** @type {{ get: () => unknown }} */ (value).get()
84
+ }
85
+ return value ?? fallback
86
+ }
87
+
88
+ /**
89
+ * 读取正在运行的 DSH 版本,供版本豁免使用(豁免是「精确 包@版本 × DSH 版本」的)。
90
+ *
91
+ * 优先用官方 `getDshRuntimeVersion()`;它不在本插件的解析范围内时退回读 DSH 安装的
92
+ * `package.json`。两条路都走不通时返回 undefined,由调用方要求请求体带上 `runtimeVersion`。
93
+ * @returns {Promise<string|undefined>} DSH 版本,或 undefined。
94
+ */
95
+ async function detectRuntimeVersion() {
96
+ try {
97
+ const boot = await import('@deepseek-ai/dsh-app-boot')
98
+ const version = boot?.getDshRuntimeVersion?.()
99
+ if (typeof version === 'string' && version.trim() !== '') return version.trim()
100
+ } catch {
101
+ // 本插件不在 DSH 安装的解析范围内:继续用下面的兜底。
102
+ }
103
+ try {
104
+ const { createRequire } = await import('node:module')
105
+ const require = createRequire(import.meta.url)
106
+ const version = require('@deepseek-ai/dsh/package.json')?.version
107
+ if (typeof version === 'string' && version.trim() !== '') return version.trim()
108
+ } catch {
109
+ // DSH 安装不在解析范围内。
110
+ }
111
+ return undefined
112
+ }
113
+
114
+ /**
115
+ * 归一化源列表:只保留 http(s) 绝对地址、去重、保持顺序。
116
+ * @param {unknown} list - 原始列表。
117
+ * @returns {string[]} 归一化后的地址。
118
+ */
119
+ function normalizeSources(list) {
120
+ if (!Array.isArray(list)) return []
121
+ const urls = []
122
+ for (const item of list) {
123
+ if (typeof item !== 'string') continue
124
+ const text = item.trim()
125
+ if (text === '') continue
126
+ let url
127
+ try {
128
+ url = new URL(text).href
129
+ } catch {
130
+ continue
131
+ }
132
+ if (!url.startsWith('http://') && !url.startsWith('https://')) continue
133
+ if (!urls.includes(url)) urls.push(url)
134
+ }
135
+ return urls
136
+ }
137
+
138
+ /**
139
+ * 从一个地址里读出镜像 id。
140
+ * @param {string} url - 任意地址。
141
+ * @returns {string|undefined} 镜像 id;不是本插件的镜像地址时为 undefined。
142
+ */
143
+ export function mirrorIdOf(url) {
144
+ try {
145
+ const pathname = new URL(url).pathname
146
+ return MIRROR_ID.exec(pathname)?.[1]
147
+ } catch {
148
+ return undefined
149
+ }
150
+ }
151
+
152
+ /**
153
+ * 构造某个源的本地镜像地址。
154
+ * @param {string} origin - 本机 Web 服务根地址,例如 `http://127.0.0.1:3080`。
155
+ * @param {string} url - 上游索引地址。
156
+ * @returns {string} 镜像地址。
157
+ */
158
+ export function mirrorUrl(origin, url) {
159
+ return `${origin}${MIRROR_PATH}/${sourceId(url)}.json`
160
+ }
161
+
162
+ /**
163
+ * 两个地址列表是否等价(顺序敏感)。
164
+ * @param {string[]} left - 列表一。
165
+ * @param {string[]} right - 列表二。
166
+ * @returns {boolean} 等价时为 true。
167
+ */
168
+ function sameList(left, right) {
169
+ return left.length === right.length && left.every((value, index) => value === right[index])
170
+ }
171
+
172
+ /**
173
+ * 读 JSON 请求体。
174
+ * @param {Request} request - Fetch 请求。
175
+ * @returns {Promise<Record<string, unknown>>} 解析后的对象;空体返回 {}。
176
+ */
177
+ async function readJsonBody(request) {
178
+ const text = await request.text()
179
+ if (text.trim() === '') return {}
180
+ const parsed = JSON.parse(text)
181
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
182
+ ? /** @type {Record<string, unknown>} */ (parsed)
183
+ : {}
184
+ }
185
+
186
+ /**
187
+ * 构造 JSON 响应。
188
+ * @param {unknown} payload - 响应体。
189
+ * @param {number} [status] - HTTP 状态码。
190
+ * @returns {Response} Fetch 响应。
191
+ */
192
+ function jsonResponse(payload, status = 200) {
193
+ return new Response(JSON.stringify(payload), {
194
+ status,
195
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
196
+ })
197
+ }
198
+
199
+ /**
200
+ * 插件主函数。
201
+ * @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
202
+ * @param {z.infer<typeof Config>} config - 插件配置。
203
+ * @returns {void}
204
+ */
205
+ export function apply(ctx, config) {
206
+ const profileDir = ctx.get('profileContext')?.dir ?? process.env.DSH_PROFILE_DIR ?? process.cwd()
207
+ const cacheDir = resolve(profileDir, String(live(config.cacheDir, '.pluginmarket-plus')))
208
+ const store = new CacheStore(cacheDir)
209
+
210
+ /** @type {import('@deepseek-ai/cordis').Context|undefined} */
211
+ let webService
212
+ /** @type {any} */
213
+ let marketService
214
+ /** @type {Map<string, Promise<unknown>>} */
215
+ const inflight = new Map()
216
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
217
+ let refreshTimer
218
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
219
+ let bootTimer
220
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
221
+ let marketChangeTimer
222
+ let nextRefreshAt = 0
223
+ let marketError = null
224
+ /** 本插件最近一次写进「发现」页的完整列表,用来识别“这是我自己写的”事件。 */
225
+ let lastWrittenIndexes = []
226
+
227
+ /** @type {any} `pluginManager` 服务;执行更新与版本豁免都靠它。 */
228
+ let pluginManager
229
+ /** @type {Map<string, Record<string, unknown>>} 上一次 `POST /updates/check` 的结果,按包名索引(内存缓存,不落盘)。 */
230
+ const checkCache = new Map()
231
+ /** @type {Map<string, {chunks: string[], bytes: number, exits: (number|null)[]}>} 每个 requestId 的 pnpm 日志尾部。 */
232
+ const logTails = new Map()
233
+ /** 每个 requestId 保留的最大日志字节数与行数。 */
234
+ const LOG_TAIL_BYTES = 16 * 1024
235
+ const LOG_TAIL_CHUNKS = 80
236
+ /** @type {ReturnType<typeof createUpdateQueue>|undefined} 正在跑或最近跑完的更新队列。 */
237
+ let updateQueue
238
+ /** 同步「正在准备队列」闩锁:startUpdates 里任何 await 之前就置位,避免并发 apply 钻空子。 */
239
+ let updatesStarting = false
240
+ /** @type {object|undefined} 最近一次更新队列的结果快照。 */
241
+ let lastUpdateRun
242
+ /** 最近一次检查的完成时间。 */
243
+ let checkedAt = null
244
+ /**
245
+ * 「可更新」三个开关的内存兜底值。
246
+ *
247
+ * 正常情况下它们写进插件的 volatile 配置(`settings.mutate`)后立即生效;profile 还没有本插件
248
+ * 的配置条目、或 Settings 不可用时写入会失败,此时至少让本次进程内的开关立刻可用,并在响应里
249
+ * 如实报告 `saved: false`。
250
+ * @type {Map<string, boolean>}
251
+ */
252
+ const updatesOverrides = new Map()
253
+
254
+ const entryId = ctx.fiber?.entry?.options?.id
255
+ const logger = {
256
+ info: (/** @type {string} */ message, /** @type {unknown} */ detail) => ctx.logger?.info?.(`dsh-pluginmarket-plus: ${message}`, detail),
257
+ warn: (/** @type {string} */ message, /** @type {unknown} */ detail) => ctx.logger?.warn?.(`dsh-pluginmarket-plus: ${message}`, detail),
258
+ }
259
+
260
+ /**
261
+ * 当前生效的源:配置里写了就用配置,否则用自动接管时记住的列表。
262
+ * @returns {string[]} 源列表。
263
+ */
264
+ function effectiveSources() {
265
+ const configured = normalizeSources(live(config.sources, []))
266
+ if (configured.length > 0) return configured
267
+ return normalizeSources(store.sources)
268
+ }
269
+
270
+ /**
271
+ * 本机 Web 服务根地址;服务尚未 listen 时返回空串。
272
+ * @returns {string} 例如 `http://127.0.0.1:3080`。
273
+ */
274
+ function origin() {
275
+ try {
276
+ return webService?.getOrigin?.() ?? ''
277
+ } catch {
278
+ return ''
279
+ }
280
+ }
281
+
282
+ /**
283
+ * 通过 Settings 服务写本插件自己的配置字段。
284
+ * @param {Record<string, unknown>} patch - 要写入的字段。
285
+ * @returns {Promise<boolean>} 是否写入成功。
286
+ */
287
+ async function writeConfig(patch) {
288
+ const settings = ctx.get('settings')
289
+ if (settings === undefined || entryId === undefined) return false
290
+ try {
291
+ const descriptors = settings.describe()
292
+ const descriptor = Array.isArray(descriptors) ? descriptors.find(item => item?.ns === entryId) : undefined
293
+ const ops = Object.entries(patch).map(([key, value]) => ({ op: 'set', path: [key], value }))
294
+ if (ops.length === 0) return true
295
+ await settings.mutate(entryId, ops, descriptor?.revision)
296
+ return true
297
+ } catch (error) {
298
+ logger.warn(`保存配置失败:${messageOf(error)}`)
299
+ return false
300
+ }
301
+ }
302
+
303
+ // --- 「可更新」数据(方案 §3 / §4 / §6 / §7)--------------------------------
304
+
305
+ /**
306
+ * 读一个「可更新」开关的当前值。
307
+ *
308
+ * 正常路径写进插件的 volatile 配置后立即生效;`settings.mutate` 不可用时(profile 还没有本插件
309
+ * 的配置条目)写入会失败,此时用内存兜底值,至少让本次进程内的开关立刻可用。
310
+ * @param {'updatesIncludeDisabled'|'updatesIncludePrerelease'|'updatesShowFailed'} key - 开关名。
311
+ * @returns {boolean} 开关状态。
312
+ */
313
+ function updatesSwitch(key) {
314
+ const override = updatesOverrides.get(key)
315
+ if (typeof override === 'boolean') return override
316
+ return live(config[key], false) === true
317
+ }
318
+
319
+ /**
320
+ * 本地索引查询表的单次请求缓存:同一请求里 `listBundles()` + 每个 Git 候选各查一次,
321
+ * 没必要重复解析几 MB 的 JSON。
322
+ * @returns {ReturnType<CacheStore['cachedIndex']>} 查询表。
323
+ */
324
+ function indexLookup() {
325
+ try {
326
+ return store.cachedIndex()
327
+ } catch (error) {
328
+ logger.warn(`读取本地索引失败:${messageOf(error)}`)
329
+ return { signature: '', size: 0, names: new Map() }
330
+ }
331
+ }
332
+
333
+ /**
334
+ * 从本地索引里取某个包在指定仓库目录下的最新提交。
335
+ * @param {ReturnType<CacheStore['cachedIndex']>} lookup - 查询表。
336
+ * @param {string} name - 包名。
337
+ * @param {{host: string, repository: string, path: string}} origin - 已安装副本的仓库目录。
338
+ * @returns {{commit: string, version: string, publishTimestamp: number}|undefined} 最新提交;索引里没有时 undefined。
339
+ */
340
+ function gitFromIndex(lookup, name, origin) {
341
+ return latestGitFromIndex(lookup.names.get(name) ?? [], origin)
342
+ }
343
+
344
+ /**
345
+ * 收集候选:`listBundles()` + 本地索引 + 上一次检查的结果。
346
+ * @returns {Promise<{candidates: object[], checkedAt: number|null, indexLevel: object}>} 候选与索引摘要。
347
+ */
348
+ async function candidatesPayload() {
349
+ const manager = pluginManager
350
+ /** @type {Record<string, unknown>[]} */
351
+ let bundles = []
352
+ let bundlesError = null
353
+ if (manager === undefined) {
354
+ bundlesError = 'plugin-manager-unavailable'
355
+ } else {
356
+ try {
357
+ bundles = await manager.listBundles()
358
+ } catch (error) {
359
+ bundlesError = messageOf(error)
360
+ }
361
+ }
362
+ const lookup = indexLookup()
363
+ const includeDisabled = updatesSwitch('updatesIncludeDisabled')
364
+ const includePrerelease = updatesSwitch('updatesIncludePrerelease')
365
+ const candidates = collectCandidates({
366
+ bundles,
367
+ cached: Object.fromEntries(checkCache),
368
+ indexInfo: { hasIndex: lookup.size > 0 },
369
+ includeDisabled,
370
+ includePrerelease,
371
+ })
372
+ return {
373
+ candidates,
374
+ checkedAt,
375
+ indexLevel: { sources: store.cachedIds().length, packages: lookup.size, error: bundlesError },
376
+ }
377
+ }
378
+
379
+ /** 停止队列并把正在跑的那一项交给后端取消流程。 */
380
+ async function cancelUpdates() {
381
+ const queue = updateQueue
382
+ if (queue === undefined) return { ok: true, cancelled: 'not-running' }
383
+ const active = queue.activeIndex()
384
+ queue.stop()
385
+ if (active < 0) return { ok: true, cancelled: 'not-running' }
386
+ const snapshot = queue.snapshot()
387
+ const item = snapshot.items[active]
388
+ if (item === undefined || pluginManager === undefined || typeof pluginManager.cancelInstall !== 'function') {
389
+ return { ok: true, cancelled: 'not-running' }
390
+ }
391
+ try {
392
+ const outcome = await pluginManager.cancelInstall(item.requestId)
393
+ // cancelInstall 只保证「进程退出且文件已还原」;completed 的结果不会被保留,
394
+ // 所以紧随其后的 waitForInstall 兜底确认一次。
395
+ if (outcome?.status === 'cancelled' && typeof pluginManager.waitForInstall === 'function') {
396
+ try {
397
+ await pluginManager.waitForInstall(item.requestId)
398
+ } catch {
399
+ // 请求已经结束,这里不需要再做什么。
400
+ }
401
+ }
402
+ return { ok: true, cancelled: outcome?.status ?? 'unknown', name: item.name }
403
+ } catch (error) {
404
+ logger.warn(`取消更新失败:${messageOf(error)}`)
405
+ return { ok: false, cancelled: 'failed', message: messageOf(error) }
406
+ }
407
+ }
408
+
409
+ /**
410
+ * 给一个包授予版本豁免(需要用户显式接受风险)。
411
+ * @param {string} packageVersion - 精确的 `包@版本`。
412
+ * @param {string|undefined} runtimeVersion - 精确的 DSH 版本。
413
+ * @returns {Promise<object>} 结果。
414
+ */
415
+ async function grantExemption(packageVersion, runtimeVersion) {
416
+ if (pluginManager === undefined || typeof pluginManager.setVersionExemption !== 'function') {
417
+ return { ok: false, error: 'plugin-manager-unavailable' }
418
+ }
419
+ const runtime = typeof runtimeVersion === 'string' && runtimeVersion.trim() !== ''
420
+ ? runtimeVersion.trim()
421
+ : await detectRuntimeVersion()
422
+ if (runtime === undefined) return { ok: false, error: 'runtime-version-unknown' }
423
+ try {
424
+ const outcome = await pluginManager.setVersionExemption(packageVersion, runtime, true, true)
425
+ return { ok: true, runtimeVersion: runtime, result: outcome }
426
+ } catch (error) {
427
+ return { ok: false, error: 'exempt-failed', message: messageOf(error) }
428
+ }
429
+ }
430
+
431
+ /**
432
+ * 安排一次后台顺序更新;同一时刻只跑一个队列。
433
+ *
434
+ * 进入函数先同步占住闩锁(之后才允许 await),所以两个并发的 `POST /updates/apply`
435
+ * 一定有一个拿到 409 `update-running`,不会都成功入队。
436
+ * @param {object[]} items - 请求体里的项。
437
+ * @returns {Promise<object>} 结果。
438
+ */
439
+ async function startUpdates(items) {
440
+ if (updatesStarting || (updateQueue !== undefined && updateQueue.isRunning())) {
441
+ return { ok: false, error: 'update-running' }
442
+ }
443
+ updatesStarting = true
444
+ try {
445
+ const lookup = indexLookup()
446
+ /** @type {object[]} */
447
+ const planned = []
448
+ for (const item of items) {
449
+ const name = typeof item.name === 'string' ? item.name : ''
450
+ if (name === '') return { ok: false, error: 'invalid-item', message: '缺少包名' }
451
+ const checked = checkCache.get(name)
452
+ const kind = item.kind === 'git' || (checked?.kind === 'git') ? 'git' : 'npm'
453
+ const current = typeof checked?.current === 'string' ? checked.current : typeof item.current === 'string' ? item.current : ''
454
+ let latest = typeof checked?.latest === 'string' ? checked.latest : ''
455
+ // registry 更新永远用 name@version:真实 pluginManager 的 checkRegistryUpdate 只要收到
456
+ // spec 就 invalid-spec 拒绝,所以 registry 项即使请求体带了 spec 也必须忽略。
457
+ let spec = kind === 'git' && typeof item.spec === 'string' && item.spec !== '' ? item.spec : undefined
458
+ let commit = kind === 'git' && typeof item.commit === 'string' ? item.commit : undefined
459
+ if (kind === 'git') {
460
+ // Git 包必须给出固定 40 位 commit 的 spec;没有就从本地索引补,补不出来就说清缺什么。
461
+ let origin
462
+ if (spec !== undefined) origin = parseGitSpec(spec)
463
+ if (origin === undefined) {
464
+ const candidate = (await candidatesPayload()).candidates.find(entry => entry.name === name)
465
+ origin = candidate?.origin
466
+ }
467
+ const found = origin === undefined ? undefined : gitFromIndex(lookup, name, origin)
468
+ const itemCommit = typeof item.commit === 'string' ? item.commit.toLowerCase() : ''
469
+ if (/^[0-9a-f]{40}$/u.test(itemCommit) && origin !== undefined) {
470
+ commit = itemCommit
471
+ latest = latest === '' ? itemCommit : latest
472
+ spec = buildGitSpec(origin, itemCommit)
473
+ } else if (found !== undefined && origin !== undefined) {
474
+ commit = found.commit
475
+ latest = found.version
476
+ spec = buildGitSpec(origin, found.commit)
477
+ }
478
+ if (typeof spec !== 'string' || spec === '') {
479
+ return { ok: false, error: 'not-checkable', message: `${name} 的 Git 提交不在本地索引里,先点「检查更新」` }
480
+ }
481
+ if (latest === '') latest = commit ?? ''
482
+ } else if (latest === '') {
483
+ return { ok: false, error: 'not-checked', message: `${name} 还没有检查到目标版本,先点「检查更新」` }
484
+ }
485
+ planned.push({
486
+ name,
487
+ version: latest,
488
+ kind,
489
+ current,
490
+ latest,
491
+ ...kind === 'git' && spec !== undefined ? { spec } : {},
492
+ ...commit === undefined ? {} : { commit },
493
+ })
494
+ }
495
+ if (planned.length === 0) return { ok: false, error: 'empty-items' }
496
+ const queue = createUpdateQueue({
497
+ items: planned,
498
+ onError: message => logger.warn(`更新失败:${message}`),
499
+ runItem: async (item) => {
500
+ if (pluginManager === undefined || typeof pluginManager.updateBundle !== 'function') {
501
+ throw new Error('plugin-manager-unavailable')
502
+ }
503
+ // 契约:updateBundle(name, version, {requestId, spec?});spec 只属于 Git 包。
504
+ const options = item.kind === 'git' && item.spec !== undefined
505
+ ? { requestId: item.requestId, spec: item.spec }
506
+ : { requestId: item.requestId }
507
+ return pluginManager.updateBundle(item.name, item.version, options)
508
+ },
509
+ })
510
+ updateQueue = queue
511
+ lastUpdateRun = undefined
512
+ queue.start().then((run) => {
513
+ lastUpdateRun = {
514
+ ...run,
515
+ finishedAt: Date.now(),
516
+ items: undefined,
517
+ }
518
+ void syncMarket().catch(() => {})
519
+ }).catch(error => logger.warn(`更新队列异常结束:${messageOf(error)}`))
520
+ return {
521
+ ok: true,
522
+ requestId: 'updates',
523
+ requestIds: queue.snapshot().items.map(item => item.requestId),
524
+ items: queue.snapshot().items,
525
+ }
526
+ } catch (error) {
527
+ logger.warn(`准备更新队列失败:${messageOf(error)}`)
528
+ return { ok: false, error: 'apply-failed', message: messageOf(error) }
529
+ } finally {
530
+ updatesStarting = false
531
+ }
532
+ }
533
+
534
+ /**
535
+ * 队列状态(含每项阶段与 pnpm 日志尾部)。
536
+ * @returns {object} 状态对象。
537
+ */
538
+ function updatesStatePayload() {
539
+ const queue = updateQueue
540
+ if (queue === undefined) {
541
+ return {
542
+ ok: true,
543
+ running: updatesStarting,
544
+ starting: updatesStarting,
545
+ queue: null,
546
+ items: [],
547
+ logs: [],
548
+ lastRun: lastUpdateRun ?? null,
549
+ checkedAt,
550
+ }
551
+ }
552
+ const snapshot = queue.snapshot()
553
+ const activeIndex = queue.activeIndex()
554
+ const active = activeIndex >= 0 ? snapshot.items[activeIndex] : undefined
555
+ const logs = active === undefined ? [] : (logTails.get(active.requestId)?.chunks ?? [])
556
+ return {
557
+ ok: true,
558
+ running: snapshot.running || updatesStarting,
559
+ starting: updatesStarting,
560
+ stopped: snapshot.stopped,
561
+ finished: snapshot.finished,
562
+ summary: snapshot.summary,
563
+ active: active?.name ?? null,
564
+ activeRequestId: active?.requestId ?? null,
565
+ items: snapshot.items,
566
+ logs,
567
+ lastRun: lastUpdateRun ?? null,
568
+ checkedAt,
569
+ }
570
+ }
571
+
572
+ /**
573
+ * 记录 pnpm 日志尾部(按 requestId 保留最后若干行)。
574
+ * @param {{requestId?: unknown, text?: unknown, stream?: unknown, exitCode?: unknown}} chunk - `plugin-manager/install-log` 的载荷。
575
+ * @returns {void}
576
+ */
577
+ function recordLog(chunk) {
578
+ const requestId = typeof chunk?.requestId === 'string' ? chunk.requestId : undefined
579
+ if (requestId === undefined) return
580
+ const entry = logTails.get(requestId) ?? { chunks: [], bytes: 0, exits: [] }
581
+ const text = typeof chunk.text === 'string' ? chunk.text : ''
582
+ const stream = chunk.stream === 'stderr' ? 'stderr' : 'stdout'
583
+ for (const line of text.split(/\r?\n/u)) {
584
+ if (line.trim() === '') continue
585
+ entry.chunks.push(stream === 'stderr' ? `! ${line}` : line)
586
+ entry.bytes += Buffer.byteLength(line) + 1
587
+ }
588
+ if (typeof chunk.exitCode === 'number' || chunk.exitCode === null) entry.exits.push(chunk.exitCode)
589
+ while (entry.chunks.length > LOG_TAIL_CHUNKS) {
590
+ entry.bytes -= Buffer.byteLength(entry.chunks[0]) + 1
591
+ entry.chunks.shift()
592
+ }
593
+ while (entry.bytes > LOG_TAIL_BYTES && entry.chunks.length > 1) {
594
+ entry.bytes -= Buffer.byteLength(entry.chunks[0]) + 1
595
+ entry.chunks.shift()
596
+ }
597
+ logTails.set(requestId, entry)
598
+ }
599
+
600
+ /**
601
+ * 当前每个源的展示状态。
602
+ * @returns {object[]} 状态数组。
603
+ */
604
+ function sourceStatuses() {
605
+ const base = origin()
606
+ const hours = Number(live(config.refreshIntervalHours, 4))
607
+ const intervalMs = hours * 3600_000
608
+ return effectiveSources().map((url) => {
609
+ const id = sourceId(url)
610
+ const entry = store.entry(id)
611
+ const hasBody = store.hasBody(id)
612
+ const refreshing = inflight.has(id)
613
+ const ageMs = typeof entry?.fetchedAt === 'number' ? Date.now() - entry.fetchedAt : undefined
614
+ /** @type {'ok'|'stale'|'empty'|'error'} */
615
+ let state
616
+ if (!hasBody) state = 'empty'
617
+ else if (entry?.error) state = 'error'
618
+ else if (ageMs !== undefined && intervalMs > 0 && ageMs > intervalMs) state = 'stale'
619
+ else state = 'ok'
620
+ return {
621
+ id,
622
+ url,
623
+ mirrorUrl: base === '' ? '' : mirrorUrl(base, url),
624
+ state,
625
+ refreshing,
626
+ fetchedAt: entry?.fetchedAt ?? null,
627
+ ageMs: ageMs ?? null,
628
+ bytes: entry?.bytes ?? null,
629
+ plugins: entry?.plugins ?? null,
630
+ title: indexTitle(entry?.title),
631
+ error: entry?.error ?? null,
632
+ errorAt: entry?.errorAt ?? null,
633
+ }
634
+ })
635
+ }
636
+
637
+ /**
638
+ * 汇总状态(公开状态路由与设置页共用)。
639
+ * @returns {object} 状态对象。
640
+ */
641
+ function statusPayload() {
642
+ /** @type {string[]} */
643
+ let indexes = []
644
+ /** @type {{url: string, title: string, error: string|null}[]} */
645
+ let summaries = []
646
+ if (marketService !== undefined) {
647
+ try {
648
+ const listed = marketService.listIndexes()
649
+ indexes = listed.map((item) => item.url)
650
+ summaries = listed.map(item => ({ url: item.url, title: indexTitle(item.title), error: item.error ?? null }))
651
+ } catch {
652
+ indexes = []
653
+ summaries = []
654
+ }
655
+ }
656
+ return {
657
+ ok: true,
658
+ origin: origin(),
659
+ mirrorBase: origin() === '' ? '' : `${origin()}${MIRROR_PATH}`,
660
+ cacheDir,
661
+ entryId: entryId ?? null,
662
+ nextRefreshAt: nextRefreshAt || null,
663
+ config: {
664
+ autoRefresh: live(config.autoRefresh, true) !== false,
665
+ refreshIntervalHours: Number(live(config.refreshIntervalHours, 4)),
666
+ managePluginMarket: live(config.managePluginMarket, true) !== false,
667
+ updatesIncludeDisabled: updatesSwitch('updatesIncludeDisabled'),
668
+ updatesIncludePrerelease: updatesSwitch('updatesIncludePrerelease'),
669
+ updatesShowFailed: updatesSwitch('updatesShowFailed'),
670
+ fetchTimeoutMs: Number(config.fetchTimeoutMs ?? 120000),
671
+ maxBytes: Number(config.maxBytes ?? 64 * 1024 * 1024),
672
+ retries: Number(config.retries ?? 2),
673
+ },
674
+ sources: sourceStatuses(),
675
+ pluginMarket: {
676
+ available: marketService !== undefined,
677
+ managed: indexes.some(url => mirrorIdOf(url) !== undefined),
678
+ indexes,
679
+ summaries,
680
+ error: marketError,
681
+ },
682
+ writable: ctx.get('settings') !== undefined && entryId !== undefined,
683
+ }
684
+ }
685
+
686
+ /**
687
+ * 刷新一个源;同一源并发调用共享一次抓取。
688
+ * @param {string} url - 上游索引地址。
689
+ * @returns {Promise<unknown>} 抓取结果。
690
+ */
691
+ function refreshOne(url) {
692
+ const id = sourceId(url)
693
+ const running = inflight.get(id)
694
+ if (running !== undefined) return running
695
+ const promise = (async () => {
696
+ const startedAt = Date.now()
697
+ try {
698
+ const fetched = await fetchIndex(url, {
699
+ timeoutMs: Number(config.fetchTimeoutMs ?? 120000),
700
+ maxBytes: Number(config.maxBytes ?? 64 * 1024 * 1024),
701
+ retries: Number(config.retries ?? 2),
702
+ })
703
+ store.writeBody(id, fetched.bytes)
704
+ store.update(id, {
705
+ url,
706
+ fetchedAt: Date.now(),
707
+ bytes: fetched.bytes.byteLength,
708
+ plugins: fetched.plugins,
709
+ title: fetched.title,
710
+ error: null,
711
+ })
712
+ logger.info(`已缓存 ${url}`, { bytes: fetched.bytes.byteLength, plugins: fetched.plugins, ms: Date.now() - startedAt })
713
+ return fetched
714
+ } catch (error) {
715
+ store.update(id, { url, error: messageOf(error), errorAt: Date.now() })
716
+ logger.warn(`抓取失败 ${url}`, { error: messageOf(error) })
717
+ throw error
718
+ } finally {
719
+ store.save()
720
+ inflight.delete(id)
721
+ }
722
+ })()
723
+ inflight.set(id, promise)
724
+ return promise
725
+ }
726
+
727
+ /**
728
+ * 刷新若干源;不传 urls 时刷新全部。
729
+ * @param {{urls?: string[]}} [options] - 目标源。
730
+ * @returns {Promise<{url: string, ok: boolean, error?: string}[]>} 每个源的结果。
731
+ */
732
+ async function refreshMany(options = {}) {
733
+ const sources = effectiveSources()
734
+ const targets = options.urls === undefined ? sources : sources.filter(url => options.urls?.includes(url))
735
+ if (targets.length === 0) return []
736
+ const results = await Promise.allSettled(targets.map(url => refreshOne(url)))
737
+ await syncMarket()
738
+ return results.map((result, index) => ({
739
+ url: targets[index],
740
+ ok: result.status === 'fulfilled',
741
+ ...(result.status === 'rejected' ? { error: messageOf(result.reason) } : {}),
742
+ }))
743
+ }
744
+
745
+ /**
746
+ * 只刷新缺失或已过期的源(启动时用,避免每次启动都全量下载)。
747
+ * @returns {Promise<void>} 完成。
748
+ */
749
+ async function refreshDue() {
750
+ const hours = Number(live(config.refreshIntervalHours, 4))
751
+ const intervalMs = hours * 3600_000
752
+ const due = effectiveSources().filter((url) => {
753
+ const id = sourceId(url)
754
+ if (!store.hasBody(id)) return true
755
+ const fetchedAt = store.entry(id)?.fetchedAt
756
+ return typeof fetchedAt !== 'number' || Date.now() - fetchedAt > intervalMs
757
+ })
758
+ if (due.length > 0) await refreshMany({ urls: due })
759
+ }
760
+
761
+ /**
762
+ * 把「发现」页的索引源同步为本地镜像(只替换已缓存成功的源)。
763
+ * @param {boolean} [ensureAll] - 为 true 时把本插件清单里、发现页还没有的源补进去
764
+ * (在缓存插件页新增源时用)。
765
+ * @returns {Promise<void>} 完成。
766
+ */
767
+ async function syncMarket(ensureAll = false) {
768
+ if (marketService === undefined) return
769
+ if (live(config.managePluginMarket, true) === false) return
770
+ const base = origin()
771
+ if (base === '') return
772
+ try {
773
+ const current = marketService.listIndexes().map((item) => item.url)
774
+ const sources = effectiveSources()
775
+ const known = new Set(sources)
776
+ /** 已出现在发现页列表里的上游地址,避免 ensureAll 重复追加。 */
777
+ const seen = new Set()
778
+ /** @type {string[]} */
779
+ const desired = []
780
+ for (const url of current) {
781
+ const mirror = mirrorIdOf(url)
782
+ if (mirror !== undefined) {
783
+ const upstream = store.entry(mirror)?.url ?? sources.find(source => sourceId(source) === mirror)
784
+ // 镜像对应的源已经不存在(被移除或清单丢了):直接把它从列表里去掉,
785
+ // 而不是留下一个可能 404 的地址。
786
+ if (upstream === undefined) continue
787
+ seen.add(upstream)
788
+ if (known.has(upstream)) desired.push(store.hasBody(mirror) ? mirrorUrl(base, upstream) : upstream)
789
+ else desired.push(upstream)
790
+ continue
791
+ }
792
+ seen.add(url)
793
+ desired.push(known.has(url) && store.hasBody(sourceId(url)) ? mirrorUrl(base, url) : url)
794
+ }
795
+ if (ensureAll) {
796
+ for (const url of sources) {
797
+ if (seen.has(url)) continue
798
+ desired.push(store.hasBody(sourceId(url)) ? mirrorUrl(base, url) : url)
799
+ }
800
+ }
801
+ if (sameList(current, desired)) {
802
+ marketError = null
803
+ return
804
+ }
805
+ lastWrittenIndexes = desired.slice()
806
+ await marketService.setIndexes(desired)
807
+ marketError = null
808
+ logger.info('已更新「发现」页索引源', { indexes: desired })
809
+ } catch (error) {
810
+ marketError = messageOf(error)
811
+ logger.warn(`更新「发现」页索引源失败:${marketError}`)
812
+ }
813
+ }
814
+
815
+ /**
816
+ * 把「发现」页的索引源还原成上游地址。
817
+ * @returns {Promise<void>} 完成。
818
+ */
819
+ async function restoreMarket() {
820
+ if (marketService === undefined) return
821
+ try {
822
+ const current = marketService.listIndexes().map((item) => item.url)
823
+ const desired = current.map((url) => {
824
+ const mirror = mirrorIdOf(url)
825
+ if (mirror === undefined) return url
826
+ return store.entry(mirror)?.url ?? url
827
+ })
828
+ if (sameList(current, desired)) return
829
+ lastWrittenIndexes = desired.slice()
830
+ await marketService.setIndexes(desired)
831
+ marketError = null
832
+ logger.info('已还原「发现」页索引源', { indexes: desired })
833
+ } catch (error) {
834
+ marketError = messageOf(error)
835
+ logger.warn(`还原「发现」页索引源失败:${marketError}`)
836
+ }
837
+ }
838
+
839
+ /**
840
+ * 从「发现」页当前配置里接管还没有镜像的上游地址。
841
+ * @returns {Promise<void>} 完成。
842
+ */
843
+ async function adoptFromMarket() {
844
+ if (marketService === undefined) return
845
+ const configured = normalizeSources(live(config.sources, []))
846
+ if (configured.length > 0) return
847
+ const remembered = normalizeSources(store.sources)
848
+ if (remembered.length > 0) {
849
+ // 之前已经接管过:把上游清单补写进配置,避免缓存目录丢失后无法还原。
850
+ await writeConfig({ sources: remembered })
851
+ return
852
+ }
853
+ let current = []
854
+ try {
855
+ current = marketService.listIndexes().map((item) => item.url)
856
+ } catch {
857
+ return
858
+ }
859
+ const upstreams = current.filter(url => mirrorIdOf(url) === undefined)
860
+ const normalized = normalizeSources(upstreams)
861
+ if (normalized.length === 0) return
862
+ store.sources = normalized
863
+ store.save()
864
+ // 上游清单同时写进插件配置:即使缓存目录被清掉,也知道该回到哪些地址。
865
+ await writeConfig({ sources: normalized })
866
+ logger.info('已接管「发现」页索引源', { sources: normalized })
867
+ }
868
+
869
+ /**
870
+ * 把「发现」页上的增删同步回本插件的源清单。
871
+ *
872
+ * 用户在发现页自己加了一个原始索引地址 → 收进清单并立刻缓存,缓存成功后再换成镜像;
873
+ * 用户删掉一个镜像 → 对应上游也从清单和磁盘里移除。本插件自己写索引源时列表与
874
+ * `lastWrittenIndexes` 相同,直接跳过,避免来回抖动。
875
+ * @returns {Promise<void>} 完成。
876
+ */
877
+ async function reconcileFromMarket() {
878
+ if (marketService === undefined) return
879
+ let current = []
880
+ try {
881
+ current = marketService.listIndexes().map((item) => item.url)
882
+ } catch {
883
+ return
884
+ }
885
+ if (sameList(current, lastWrittenIndexes)) return
886
+ const previous = effectiveSources()
887
+ /** @type {string[]} */
888
+ const upstreams = []
889
+ for (const url of current) {
890
+ const mirror = mirrorIdOf(url)
891
+ if (mirror === undefined) {
892
+ upstreams.push(url)
893
+ continue
894
+ }
895
+ const upstream = store.entry(mirror)?.url ?? previous.find(source => sourceId(source) === mirror)
896
+ if (upstream !== undefined) upstreams.push(upstream)
897
+ }
898
+ const next = normalizeSources(upstreams)
899
+ const added = next.filter(url => !previous.includes(url))
900
+ const removed = previous.filter(url => !next.includes(url))
901
+ if (added.length === 0 && removed.length === 0) return
902
+ store.sources = next
903
+ for (const url of removed) store.remove(sourceId(url))
904
+ store.save()
905
+ await writeConfig({ sources: next })
906
+ if (added.length > 0) await refreshMany({ urls: added })
907
+ else await syncMarket()
908
+ logger.info('已同步「发现」页的索引源变更', { added, removed })
909
+ }
910
+
911
+ /** 重新安排下一次自动刷新。 */
912
+ function schedule() {
913
+ if (refreshTimer !== undefined) clearTimeout(refreshTimer)
914
+ refreshTimer = undefined
915
+ nextRefreshAt = 0
916
+ if (live(config.autoRefresh, true) === false) return
917
+ const hours = Number(live(config.refreshIntervalHours, 4))
918
+ if (!Number.isFinite(hours) || hours <= 0) return
919
+ const delay = Math.min(Math.max(hours * 3600_000, 60_000), MAX_INTERVAL_HOURS * 3600_000)
920
+ nextRefreshAt = Date.now() + delay
921
+ refreshTimer = setTimeout(() => {
922
+ void refreshMany().catch(error => logger.warn(`定时刷新失败:${messageOf(error)}`)).finally(schedule)
923
+ }, delay)
924
+ }
925
+
926
+ // --- 公开镜像路由(必须免登录:pluginMarket 在 Host 进程里裸 fetch)---------
927
+ ctx.inject(['webServer'], (webCtx) => {
928
+ webService = webCtx.webServer
929
+ webCtx.effect(() => webCtx.webServer.register({
930
+ kind: 'prefix',
931
+ path: MIRROR_PATH,
932
+ async handler(req, res) {
933
+ const method = req.method ?? 'GET'
934
+ if (method !== 'GET' && method !== 'HEAD') {
935
+ res.writeHead(405, { allow: 'GET, HEAD' })
936
+ res.end()
937
+ return
938
+ }
939
+ const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
940
+ const id = MIRROR_ID.exec(pathname)?.[1]
941
+ const body = id === undefined ? undefined : store.readBody(id)
942
+ if (body === undefined) {
943
+ const message = id === undefined ? 'unknown mirror id' : 'index is not cached yet'
944
+ res.writeHead(503, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
945
+ res.end(method === 'HEAD' ? undefined : JSON.stringify({ error: message }))
946
+ return
947
+ }
948
+ res.writeHead(200, {
949
+ 'content-type': 'application/json; charset=utf-8',
950
+ 'content-length': String(body.byteLength),
951
+ 'cache-control': 'no-store',
952
+ 'x-pluginmarket-plus': 'cached',
953
+ })
954
+ res.end(method === 'HEAD' ? undefined : body)
955
+ },
956
+ }), 'dsh-pluginmarket-plus: mirror route')
957
+
958
+ webCtx.effect(() => webCtx.webServer.register({
959
+ kind: 'exact',
960
+ path: PUBLIC_STATUS_PATH,
961
+ async handler(req, res) {
962
+ const body = JSON.stringify(statusPayload())
963
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': String(Buffer.byteLength(body)) })
964
+ res.end(req.method === 'HEAD' ? undefined : body)
965
+ },
966
+ }), 'dsh-pluginmarket-plus: status route')
967
+ })
968
+
969
+ // --- 设置页 API(经 connection,只有 owner 浏览器能访问)-------------------
970
+ ctx.inject(['connection'], (connCtx) => {
971
+ /**
972
+ * @param {string} path - `/api/...` 路径。
973
+ * @param {('GET'|'POST')[]} methods - 允许的方法。
974
+ * @param {(request: Request) => Promise<Response>} fetch - 处理函数。
975
+ */
976
+ const route = (path, methods, handler) => {
977
+ connCtx.effect(() => connCtx.connection.fetch.register({
978
+ path,
979
+ methods,
980
+ requestBody: 'buffered',
981
+ fetch: handler,
982
+ }), `dsh-pluginmarket-plus: ${path}`)
983
+ }
984
+
985
+ route(`${API_PREFIX}/status`, ['GET'], async () => jsonResponse(statusPayload()))
986
+
987
+ route(`${API_PREFIX}/refresh`, ['POST'], async (request) => {
988
+ try {
989
+ const body = await readJsonBody(request)
990
+ const url = typeof body.url === 'string' ? body.url : undefined
991
+ if (url !== undefined && !effectiveSources().includes(url)) {
992
+ return jsonResponse({ ok: false, error: 'unknown-source', message: `未配置的源:${url}` }, 400)
993
+ }
994
+ const results = await refreshMany(url === undefined ? {} : { urls: [url] })
995
+ return jsonResponse({ ok: true, results, status: statusPayload() })
996
+ } catch (error) {
997
+ return jsonResponse({ ok: false, error: 'refresh-failed', message: messageOf(error) }, 500)
998
+ }
999
+ })
1000
+
1001
+ route(`${API_PREFIX}/settings`, ['POST'], async (request) => {
1002
+ try {
1003
+ const body = await readJsonBody(request)
1004
+ /** @type {Record<string, unknown>} */
1005
+ const patch = {}
1006
+ /** @type {string[]} */
1007
+ let added = []
1008
+ if (typeof body.autoRefresh === 'boolean') patch.autoRefresh = body.autoRefresh
1009
+ if (body.refreshIntervalHours !== undefined) {
1010
+ const hours = Number(body.refreshIntervalHours)
1011
+ if (!Number.isFinite(hours) || hours < 0.25 || hours > MAX_INTERVAL_HOURS) {
1012
+ return jsonResponse({ ok: false, error: 'invalid-interval', message: '刷新间隔需在 0.25–168 小时之间' }, 400)
1013
+ }
1014
+ patch.refreshIntervalHours = hours
1015
+ }
1016
+ if (typeof body.managePluginMarket === 'boolean') patch.managePluginMarket = body.managePluginMarket
1017
+ if (typeof body.updatesIncludeDisabled === 'boolean') patch.updatesIncludeDisabled = body.updatesIncludeDisabled
1018
+ if (typeof body.updatesIncludePrerelease === 'boolean') patch.updatesIncludePrerelease = body.updatesIncludePrerelease
1019
+ if (typeof body.updatesShowFailed === 'boolean') patch.updatesShowFailed = body.updatesShowFailed
1020
+ if (body.sources !== undefined) {
1021
+ const next = normalizeSources(body.sources)
1022
+ const previous = effectiveSources()
1023
+ const removed = previous.filter(url => !next.includes(url))
1024
+ added = next.filter(url => !previous.includes(url))
1025
+ store.sources = next
1026
+ for (const url of removed) store.remove(sourceId(url))
1027
+ store.save()
1028
+ patch.sources = next
1029
+ }
1030
+ const saved = await writeConfig(patch)
1031
+ // 写配置失败(profile 还没有本插件条目 / Settings 不可用)时,至少让这些开关在本次
1032
+ // 进程内立刻生效;响应里的 `saved: false` 会如实告诉界面没有落盘。
1033
+ for (const key of ['updatesIncludeDisabled', 'updatesIncludePrerelease', 'updatesShowFailed']) {
1034
+ if (typeof patch[key] !== 'boolean') continue
1035
+ const effective = live(config[key], undefined)
1036
+ if (saved && effective === patch[key]) updatesOverrides.delete(key)
1037
+ else updatesOverrides.set(key, patch[key])
1038
+ }
1039
+ if (added.length > 0) await refreshMany({ urls: added })
1040
+ if (patch.managePluginMarket === false) await restoreMarket()
1041
+ else if (patch.managePluginMarket === true || patch.sources !== undefined) await syncMarket(patch.sources !== undefined)
1042
+ schedule()
1043
+ return jsonResponse({ ok: true, saved, status: statusPayload() })
1044
+ } catch (error) {
1045
+ return jsonResponse({ ok: false, error: 'settings-failed', message: messageOf(error) }, 500)
1046
+ }
1047
+ })
1048
+
1049
+ route(`${API_PREFIX}/market`, ['POST'], async (request) => {
1050
+ try {
1051
+ const body = await readJsonBody(request)
1052
+ const action = typeof body.action === 'string' ? body.action : 'apply'
1053
+ if (action === 'restore') await restoreMarket()
1054
+ else await syncMarket(true)
1055
+ return jsonResponse({ ok: true, status: statusPayload() })
1056
+ } catch (error) {
1057
+ return jsonResponse({ ok: false, error: 'market-failed', message: messageOf(error) }, 500)
1058
+ }
1059
+ })
1060
+
1061
+ // --- 「可更新」桥(owner-only;方案 §6)----------------------------------
1062
+
1063
+ // 候选列表:只读缓存,不联网。`state` 是 `available / skipped / current / uncheckable / unknown / error`。
1064
+ route(`${API_PREFIX}/updates`, ['GET'], async () => {
1065
+ try {
1066
+ const payload = await candidatesPayload()
1067
+ return jsonResponse({
1068
+ ok: true,
1069
+ candidates: payload.candidates,
1070
+ checkedAt: payload.checkedAt,
1071
+ index: payload.indexLevel,
1072
+ config: {
1073
+ includeDisabled: updatesSwitch('updatesIncludeDisabled'),
1074
+ includePrerelease: updatesSwitch('updatesIncludePrerelease'),
1075
+ showFailed: updatesSwitch('updatesShowFailed'),
1076
+ },
1077
+ running: updatesStarting || (updateQueue?.isRunning() ?? false),
1078
+ })
1079
+ } catch (error) {
1080
+ return jsonResponse({ ok: false, error: 'updates-failed', message: messageOf(error) }, 500)
1081
+ }
1082
+ })
1083
+
1084
+ // 权威检查:registry → listVersions();git → 本地索引里的最新 commit。
1085
+ route(`${API_PREFIX}/updates/check`, ['POST'], async (request) => {
1086
+ try {
1087
+ const body = await readJsonBody(request)
1088
+ const names = Array.isArray(body.names) ? body.names.filter(name => typeof name === 'string') : undefined
1089
+ const payload = await candidatesPayload()
1090
+ const includePrerelease = updatesSwitch('updatesIncludePrerelease')
1091
+ const lookup = indexLookup()
1092
+ if (lookup.size === 0) {
1093
+ // 索引缺失时 Git 包标记不可检查且不报错;registry 包照样能用 registry 查。
1094
+ logger.info('本地索引为空,Git 包本次标记为不可检查')
1095
+ }
1096
+ const result = await checkCandidates({
1097
+ candidates: payload.candidates,
1098
+ names,
1099
+ dependencies: {
1100
+ includePrerelease,
1101
+ listVersions: async (name) => {
1102
+ if (pluginManager === undefined || typeof pluginManager.listVersions !== 'function') {
1103
+ return { status: 'refused', problem: 'not-updatable', reason: 'plugin-manager-unavailable', attempts: [] }
1104
+ }
1105
+ return pluginManager.listVersions(name)
1106
+ },
1107
+ latestGit: (name, origin) => gitFromIndex(lookup, name, origin),
1108
+ },
1109
+ })
1110
+ for (const entry of result.checked) checkCache.set(entry.name, entry)
1111
+ checkedAt = Date.now()
1112
+ const refreshed = await candidatesPayload()
1113
+ return jsonResponse({
1114
+ ok: true,
1115
+ checked: result.checked,
1116
+ skipped: result.skipped,
1117
+ unknown: result.unknown,
1118
+ candidates: refreshed.candidates,
1119
+ checkedAt,
1120
+ })
1121
+ } catch (error) {
1122
+ return jsonResponse({ ok: false, error: 'check-failed', message: messageOf(error) }, 500)
1123
+ }
1124
+ })
1125
+
1126
+ // 入队顺序更新:立刻返回,后台逐个 updateBundle;进度看 /updates/state。
1127
+ route(`${API_PREFIX}/updates/apply`, ['POST'], async (request) => {
1128
+ try {
1129
+ const body = await readJsonBody(request)
1130
+ const raw = Array.isArray(body.items) ? body.items : []
1131
+ const items = raw.filter(item => item !== null && typeof item === 'object')
1132
+ if (items.length === 0) {
1133
+ return jsonResponse({ ok: false, error: 'no-items', message: '请求体 items 为空' }, 400)
1134
+ }
1135
+ const started = await startUpdates(items)
1136
+ if (started.ok !== true) {
1137
+ const status = started.error === 'update-running'
1138
+ ? 409
1139
+ : started.error === 'plugin-manager-unavailable' ? 503 : started.error === 'apply-failed' ? 500 : 400
1140
+ return jsonResponse(started, status)
1141
+ }
1142
+ return jsonResponse({ ok: true, started: true, requestIds: started.requestIds, items: started.items })
1143
+ } catch (error) {
1144
+ return jsonResponse({ ok: false, error: 'apply-failed', message: messageOf(error) }, 500)
1145
+ }
1146
+ })
1147
+
1148
+ // 队列进度:每项阶段(来自 plugin-manager/update-state)与当前项的 pnpm 日志尾部。
1149
+ route(`${API_PREFIX}/updates/state`, ['GET'], async () => jsonResponse(updatesStatePayload()))
1150
+
1151
+ // 取消:停队列 + 取消当前项。
1152
+ route(`${API_PREFIX}/updates/cancel`, ['POST'], async () => {
1153
+ try {
1154
+ const result = await cancelUpdates()
1155
+ return jsonResponse({ ...result, state: updatesStatePayload() }, result.ok === true ? 200 : 500)
1156
+ } catch (error) {
1157
+ return jsonResponse({ ok: false, error: 'cancel-failed', message: messageOf(error) }, 500)
1158
+ }
1159
+ })
1160
+
1161
+ // 版本豁免:必须显式 acceptRisk === true。
1162
+ route(`${API_PREFIX}/updates/exempt`, ['POST'], async (request) => {
1163
+ try {
1164
+ const body = await readJsonBody(request)
1165
+ const packageName = typeof body.package === 'string' ? body.package.trim() : ''
1166
+ const version = typeof body.version === 'string' ? body.version.trim() : ''
1167
+ if (packageName === '' || version === '') {
1168
+ return jsonResponse({ ok: false, error: 'invalid-request', message: '需要 package 与 version' }, 400)
1169
+ }
1170
+ if (body.acceptRisk !== true) {
1171
+ return jsonResponse({ ok: false, error: 'risk-not-accepted', message: '授予版本豁免需要显式接受风险(acceptRisk: true)' }, 400)
1172
+ }
1173
+ const result = await grantExemption(`${packageName}@${version}`, typeof body.runtimeVersion === 'string' ? body.runtimeVersion : undefined)
1174
+ if (result.ok !== true) {
1175
+ const status = result.error === 'plugin-manager-unavailable' ? 503 : result.error === 'runtime-version-unknown' ? 409 : 500
1176
+ return jsonResponse(result, status)
1177
+ }
1178
+ return jsonResponse(result)
1179
+ } catch (error) {
1180
+ return jsonResponse({ ok: false, error: 'exempt-failed', message: messageOf(error) }, 500)
1181
+ }
1182
+ })
1183
+ })
1184
+
1185
+ // --- 发现页服务:接管已有索引源、首次补缓存、定时刷新 ----------------------
1186
+ ctx.inject(['pluginMarket'], (marketCtx) => {
1187
+ marketService = marketCtx.pluginMarket
1188
+ void (async () => {
1189
+ await adoptFromMarket()
1190
+ await reconcileFromMarket()
1191
+ await syncMarket()
1192
+ await refreshDue()
1193
+ schedule()
1194
+ })().catch(error => logger.warn(`接管「发现」页索引源失败:${messageOf(error)}`))
1195
+ })
1196
+
1197
+ // --- 更新执行引擎:复用 pluginManager,进度来自它的事件(方案 §1.1 / §6)----
1198
+ ctx.inject(['pluginManager'], (managerCtx) => {
1199
+ pluginManager = managerCtx.pluginManager
1200
+ /** @type {Array<() => void>} */
1201
+ const disposers = []
1202
+
1203
+ // 每项的阶段:plugin-manager/update-state 的 checking → removing → installing → restoring。
1204
+ disposers.push(managerCtx.on('plugin-manager/update-state', (/** @type {{requestId?: string, step?: string}} */ progress) => {
1205
+ const queue = updateQueue
1206
+ if (queue === undefined || progress === null || typeof progress !== 'object') return
1207
+ const stage = progress.step === undefined ? undefined : UPDATE_STEP_STAGE[progress.step]
1208
+ if (stage === undefined || typeof progress.requestId !== 'string') return
1209
+ const item = queue.snapshot().items.find(entry => entry.requestId === progress.requestId)
1210
+ if (item !== undefined) queue.setStage(item.name, stage)
1211
+ }))
1212
+
1213
+ // pnpm 日志尾部:按 requestId 保留最后若干行,供 /updates/state 展开。
1214
+ disposers.push(managerCtx.on('plugin-manager/install-log', (/** @type {object} */ chunk) => recordLog(chunk)))
1215
+
1216
+ // 一次操作结束后,还在跑的队列保留日志;跑完了就清掉,下一次从干净的一轮开始。
1217
+ disposers.push(managerCtx.on('plugin-manager/changed', () => {
1218
+ if (updateQueue?.isRunning() === true) return
1219
+ if (lastUpdateRun !== undefined) logTails.clear()
1220
+ }))
1221
+
1222
+ ctx.effect(() => () => {
1223
+ for (const dispose of disposers) {
1224
+ try {
1225
+ dispose()
1226
+ } catch {
1227
+ // 已经随 fiber 一起释放。
1228
+ }
1229
+ }
1230
+ pluginManager = undefined
1231
+ }, 'dsh-pluginmarket-plus: update listeners')
1232
+ })
1233
+
1234
+ // 用户在「发现 → 索引源」里增删时,跟随同步(防抖,忽略本插件自己的写入)。
1235
+ ctx.on('plugin-market/changed', () => {
1236
+ if (marketChangeTimer !== undefined) clearTimeout(marketChangeTimer)
1237
+ marketChangeTimer = setTimeout(() => {
1238
+ marketChangeTimer = undefined
1239
+ void reconcileFromMarket().catch(error => logger.warn(`同步索引源失败:${messageOf(error)}`))
1240
+ }, 600)
1241
+ })
1242
+
1243
+ // 启动后补一次缺失/过期的缓存;此时 Web 服务与插件市场服务都已就位。
1244
+ bootTimer = setTimeout(() => {
1245
+ void refreshDue()
1246
+ .catch(error => logger.warn(`启动刷新失败:${messageOf(error)}`))
1247
+ .finally(schedule)
1248
+ }, 2000)
1249
+
1250
+ // 配置热更新后重新排期。
1251
+ ctx.on('loader/volatile-update', () => {
1252
+ schedule()
1253
+ })
1254
+
1255
+ ctx.effect(() => () => {
1256
+ if (refreshTimer !== undefined) clearTimeout(refreshTimer)
1257
+ if (bootTimer !== undefined) clearTimeout(bootTimer)
1258
+ if (marketChangeTimer !== undefined) clearTimeout(marketChangeTimer)
1259
+ // 卸载/停用时尽量把「发现」页的索引源还原成上游地址,避免留下指向已消失
1260
+ // 本地镜像的死链。失败也不影响卸载。
1261
+ if (live(config.managePluginMarket, true) !== false) {
1262
+ try {
1263
+ const current = marketService?.listIndexes?.().map((item) => item.url) ?? []
1264
+ if (current.some(url => mirrorIdOf(url) !== undefined)) void restoreMarket()
1265
+ } catch {
1266
+ // 服务已先一步销毁时忽略。
1267
+ }
1268
+ }
1269
+ }, 'dsh-pluginmarket-plus: timers')
1270
+ }