dsh-pluginmarket-plus 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/updates.js ADDED
@@ -0,0 +1,769 @@
1
+ /**
2
+ * 「可更新」纯数据层:候选收集、检查结果合并、顺序更新队列。
3
+ *
4
+ * 这里只处理数据,不碰 Cordis 服务,也不发网络请求:
5
+ *
6
+ * - 候选收集({@link collectCandidates})只用 `pluginManager.listBundles()` 的结果加本插件缓存
7
+ * 的市场索引,按方案 §4 的规则决定哪些 bundle 能出现在「可更新」列表里。
8
+ * - 检查({@link checkCandidate})注入两个数据源:npm 包走 `listVersions()`,
9
+ * Git 包走本地索引里该包最新版本的 `source.commit`。
10
+ * - 队列({@link createUpdateQueue})是纯状态机,执行动作由调用方注入,便于单测。
11
+ *
12
+ * 方案见 `docs/05-updates-tab-plan.md` §3 / §4 / §6 / §7。
13
+ *
14
+ * @module dsh-pluginmarket-plus/lib/updates
15
+ */
16
+
17
+ /** 队列项的阶段(写进 `/updates/state` 的 `items[].stage`)。 */
18
+ export const STAGES = [
19
+ /** 已入队,还没轮到。 */
20
+ 'queued',
21
+ /** 正在检查目标版本是否可装。 */
22
+ 'checking',
23
+ /** 正在移除已安装版本(`plugin-manager/update-state` 的 removing)。 */
24
+ 'removing',
25
+ /** 正在安装目标版本。 */
26
+ 'installing',
27
+ /** 目标失败后正在装回旧版本。 */
28
+ 'restoring',
29
+ /** 成功(未必已生效,看 `restartRequired`)。 */
30
+ 'done',
31
+ /** 失败(`pluginManager.updateBundle` 抛错或返回值不可读)。 */
32
+ 'failed',
33
+ /** 被取消;正在跑的那一项走后端取消流程后落到这里。 */
34
+ 'cancelled',
35
+ ]
36
+
37
+ /**
38
+ * `plugin-manager/update-state` 的 step → 队列阶段。
39
+ * @type {Record<string, string>}
40
+ */
41
+ export const UPDATE_STEP_STAGE = {
42
+ checking: 'checking',
43
+ removing: 'removing',
44
+ installing: 'installing',
45
+ restoring: 'restoring',
46
+ }
47
+
48
+ // --- 版本比较(只用 Node 内置模块,自己实现 SemVer 比较)------------------------
49
+
50
+ /** 严格的 SemVer 解析:`major.minor.patch[-prerelease][+build]`。 */
51
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u
52
+
53
+ /**
54
+ * 解析一个版本号。
55
+ * @param {unknown} value - 候选版本字符串。
56
+ * @returns {{major: number, minor: number, patch: number, pre: string[]}|undefined} 解析结果;非法版本返回 undefined。
57
+ */
58
+ export function parseVersion(value) {
59
+ if (typeof value !== 'string') return undefined
60
+ const match = SEMVER.exec(value.trim())
61
+ if (match === null) return undefined
62
+ return {
63
+ major: Number(match[1]),
64
+ minor: Number(match[2]),
65
+ patch: Number(match[3]),
66
+ pre: match[4] === undefined ? [] : match[4].split('.'),
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 比较两个版本号(SemVer 2.0.0 的优先级规则,忽略 build 元数据)。
72
+ * @param {string} left - 左版本。
73
+ * @param {string} right - 右版本。
74
+ * @returns {number} 左大于右为 1,小于为 -1,相等为 0。
75
+ * @throws {TypeError} 任一侧不是合法版本时抛出(调用方应先用 {@link parseVersion} 判断)。
76
+ */
77
+ export function compareVersions(left, right) {
78
+ const a = parseVersion(left)
79
+ const b = parseVersion(right)
80
+ if (a === undefined || b === undefined) throw new TypeError(`不是合法的 semver 版本:${String(left)} / ${String(right)}`)
81
+ for (const key of ['major', 'minor', 'patch']) {
82
+ if (a[key] !== b[key]) return a[key] > b[key] ? 1 : -1
83
+ }
84
+ // 有先行版本号的版本低于同号正式版。
85
+ if (a.pre.length === 0 && b.pre.length === 0) return 0
86
+ if (a.pre.length === 0) return 1
87
+ if (b.pre.length === 0) return -1
88
+ const length = Math.max(a.pre.length, b.pre.length)
89
+ for (let index = 0; index < length; index++) {
90
+ const x = a.pre[index]
91
+ const y = b.pre[index]
92
+ if (x === undefined) return -1
93
+ if (y === undefined) return 1
94
+ if (x === y) continue
95
+ const numericX = /^\d+$/u.test(x)
96
+ const numericY = /^\d+$/u.test(y)
97
+ if (numericX && numericY) return Number(x) > Number(y) ? 1 : -1
98
+ // 数字标识符的优先级永远低于字母数字标识符。
99
+ if (numericX !== numericY) return numericX ? -1 : 1
100
+ return x > y ? 1 : -1
101
+ }
102
+ return 0
103
+ }
104
+
105
+ /**
106
+ * 一个版本是否带先行版本号(预发布)。
107
+ * @param {unknown} value - 版本号。
108
+ * @returns {boolean} 是预发布为 true。
109
+ */
110
+ export function isPrerelease(value) {
111
+ const parsed = parseVersion(value)
112
+ return parsed !== undefined && parsed.pre.length > 0
113
+ }
114
+
115
+ // --- Git spec 解析 --------------------------------------------------------------
116
+
117
+ /** 完整提交(小写或大写 40 位十六进制)。 */
118
+ const FULL_COMMIT = /^[0-9a-f]{40}$/iu
119
+ /** 带 scp 形式的 git 地址,例如 `git@github.com:owner/repo.git`。 */
120
+ const SCP_GIT = /^git@([^:]+):(.+)$/iu
121
+ /** `host/owner/repo` 简写。 */
122
+ const SHORTHAND_HOSTS = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org', gist: 'gist.github.com' }
123
+
124
+ /**
125
+ * 解析 `git+<url>#<commit>[&path:/dir]` 形态的 spec。
126
+ *
127
+ * 只有固定 40 位 commit 的 Git spec 才算得上「可更新」:分支、标签、范围、
128
+ * `github:owner/repo` 简写都无法在更新失败时装回原来的版本(方案 §3)。
129
+ * @param {unknown} spec - 已安装副本的 spec(`BundleInfo.source`)。
130
+ * @returns {{host: string, path: string, repository: string, commit: string, spec: string}|undefined} 解析结果;不是固定 commit 的 Git spec 时 undefined。
131
+ */
132
+ export function parseGitSpec(spec) {
133
+ if (typeof spec !== 'string') return undefined
134
+ const trimmed = spec.trim()
135
+ const hash = trimmed.indexOf('#')
136
+ if (hash === -1) return undefined
137
+ const location = trimmed.slice(0, hash)
138
+ const parameters = trimmed.slice(hash + 1).split('&')
139
+ const paths = parameters.filter(part => part.startsWith('path:'))
140
+ const others = parameters.filter(part => !part.startsWith('path:'))
141
+ // pnpm 取重复参数里最后一个,重复的 path: 或多余参数都不指向唯一仓库目录。
142
+ if (paths.length > 1 || others.length !== 1 || !FULL_COMMIT.test(others[0])) return undefined
143
+ const parsed = parseGitLocation(location)
144
+ if (parsed === undefined) return undefined
145
+ const path = (paths[0] ?? '').slice('path:'.length).replace(/^\/+|\/+$/gu, '')
146
+ return {
147
+ host: parsed.host,
148
+ path,
149
+ repository: parsed.repository,
150
+ commit: /** @type {string} */ (others[0]).toLowerCase(),
151
+ spec: trimmed,
152
+ }
153
+ }
154
+
155
+ /**
156
+ * 从一个 git 地址里取出主机与仓库路径(去掉传输方式、用户信息、`.git` 后缀、大小写差异)。
157
+ * @param {string} location - 例如 `git+https://github.com/owner/repo.git`。
158
+ * @returns {{host: string, repository: string}|undefined} 解析结果。
159
+ */
160
+ function parseGitLocation(location) {
161
+ const scp = SCP_GIT.exec(location)
162
+ if (scp !== null) {
163
+ return { host: scp[1].toLowerCase(), repository: normalizeRepository(scp[2]) }
164
+ }
165
+ let text = location.replace(/^github:/iu, `${SHORTHAND_HOSTS.github}/`)
166
+ .replace(/^gitlab:/iu, `${SHORTHAND_HOSTS.gitlab}/`)
167
+ .replace(/^bitbucket:/iu, `${SHORTHAND_HOSTS.bitbucket}/`)
168
+ .replace(/^gist:/iu, `${SHORTHAND_HOSTS.gist}/`)
169
+ text = text.replace(/^git\+/iu, '')
170
+ if (!/^[a-z][a-z0-9+.-]*:\/\//iu.test(text)) {
171
+ // github:owner/repo 形式没有协议头。
172
+ if (!/^[^/\s]+\/[^/\s]+/u.test(text)) return undefined
173
+ text = `https://${text}`
174
+ }
175
+ let url
176
+ try {
177
+ url = new URL(text)
178
+ } catch {
179
+ return undefined
180
+ }
181
+ if (url.host === '') return undefined
182
+ return { host: url.host.toLowerCase(), repository: normalizeRepository(`${url.pathname}${url.search}`) }
183
+ }
184
+
185
+ /**
186
+ * 归一化仓库路径:去掉首尾斜杠与 `.git` 后缀,去掉查询串。
187
+ * @param {string} value - 原始路径。
188
+ * @returns {string} 归一化后的 `owner/repo[/dir]`。
189
+ */
190
+ function normalizeRepository(value) {
191
+ return value.split('?')[0].replace(/^\/+|\/+$/gu, '').replace(/\.git$/iu, '').replace(/\/+$/gu, '')
192
+ }
193
+
194
+ /**
195
+ * 索引里一条 Git 版本的来源,转成可比较的形态。
196
+ * @param {{url?: unknown, commit?: unknown, path?: unknown}} source - 索引版本的 `source`。
197
+ * @returns {{host: string, repository: string, path: string, commit: string}|undefined} 归一化结果。
198
+ */
199
+ export function normalizeIndexGitSource(source) {
200
+ if (source === null || typeof source !== 'object') return undefined
201
+ const url = typeof source.url === 'string' ? source.url : undefined
202
+ const commit = typeof source.commit === 'string' ? source.commit.toLowerCase() : undefined
203
+ if (url === undefined || commit === undefined || !FULL_COMMIT.test(commit)) return undefined
204
+ const parsed = parseGitLocation(url)
205
+ if (parsed === undefined) return undefined
206
+ const path = typeof source.path === 'string' ? source.path.replace(/^\/+|\/+$/gu, '') : ''
207
+ return { host: parsed.host, repository: parsed.repository, path, commit }
208
+ }
209
+
210
+ /**
211
+ * 构造 Git 包的更新 spec。
212
+ *
213
+ * 必须与已安装副本的**仓库和子目录一致**、且固定 full commit,否则 `updateBundle` 会拒绝。
214
+ * @param {{repository: string, host: string, path: string}} origin - 已安装副本的仓库目录。
215
+ * @param {string} commit - 目标提交。
216
+ * @returns {string} `git+https://<host>/<repository>.git#<commit>[&path:/<path>]`。
217
+ */
218
+ export function buildGitSpec(origin, commit) {
219
+ const base = `git+https://${origin.host}/${origin.repository}.git#${commit}`
220
+ return origin.path === '' ? base : `${base}&path:/${origin.path}`
221
+ }
222
+
223
+ // --- 候选收集 ------------------------------------------------------------------
224
+
225
+ /**
226
+ * 索引里某一条版本的来源与发布时间(`collectCandidates` 只用到这两项)。
227
+ * @typedef {object} IndexVersion
228
+ * @property {string} version
229
+ * @property {'npm'|'git'} type
230
+ * @property {number} [publishTimestamp]
231
+ * @property {{url: string, path: string, commit: string, host: string, repository: string}} [git]
232
+ */
233
+
234
+ /**
235
+ * 该 bundle 是否带插件管理组件(`listBundles()` 会用 `readOnlyReason` 标出来)。
236
+ * @param {Record<string, unknown>} bundle - `BundleInfo`。
237
+ * @returns {boolean} 带插件管理为 true。
238
+ */
239
+ export function hasPluginManagement(bundle) {
240
+ if (bundle.readOnlyReason !== undefined) return true
241
+ // 极老或测试用的形态:patch 行里直接出现插件管理模块。
242
+ const rows = Array.isArray(bundle.rows) ? bundle.rows : []
243
+ return rows.some(row => row !== null && typeof row === 'object'
244
+ && /(?:^|[-/])(?:dsh-)?plugin-manager(?:$|[-/])/u.test(String(/** @type {Record<string, unknown>} */ (row).moduleName ?? '')))
245
+ }
246
+
247
+ /**
248
+ * 读取 bundle 的 spec(`BundleInfo.source` 在实现里可缺省)。
249
+ * @param {Record<string, unknown>} bundle - `BundleInfo`。
250
+ * @returns {string|undefined} spec。
251
+ */
252
+ function sourceOf(bundle) {
253
+ return typeof bundle.source === 'string' && bundle.source.trim() !== '' ? bundle.source : undefined
254
+ }
255
+
256
+ /**
257
+ * 判定一个 `listBundles()` 条目能否出现在「可更新」列表里,以及它的更新类型。
258
+ *
259
+ * 与方案 §4 一一对应:
260
+ *
261
+ * - `official === true`、`installed !== true`、`availability !== 'profile'`、无 `source`、
262
+ * 带插件管理组件 → 一律不显示(官方自带 bundle 跟随 DSH 版本升级)。
263
+ * - `update` 字段缺失 → 不显示;它由 `pluginManager` 的 `updateRefusal()` 计算,
264
+ * 已经把 `link:` / `file:` / `npm:` 别名 / 未固定 commit 的 Git / 非自有 registry spec
265
+ * 全都挡在外面。这里再显式判一遍同样的规则,避免上游形态变化时静默放行。
266
+ * @param {Record<string, unknown>} bundle - `BundleInfo`。
267
+ * @returns {{kind: 'npm'|'git', name: string, current: string, enabled: boolean, spec?: string, origin?: {host: string, repository: string, path: string, commit: string}}|{reason: string}} 可更新目标,或拒绝原因。
268
+ */
269
+ export function classifyBundle(bundle) {
270
+ const name = typeof bundle.name === 'string' ? bundle.name : ''
271
+ if (name === '') return { reason: 'no-name' }
272
+ if (bundle.official === true) return { reason: 'official' }
273
+ if (bundle.installed !== true) return { reason: 'not-installed' }
274
+ if (bundle.availability !== undefined && bundle.availability !== 'profile') return { reason: `availability:${String(bundle.availability)}` }
275
+ if (hasPluginManagement(bundle)) return { reason: 'plugin-management' }
276
+ const spec = sourceOf(bundle)
277
+ if (spec === undefined) return { reason: 'no-source' }
278
+ // pluginManager 的 BundleInfo.update 是 'registry' | 'git';对外契约统一用 'npm' | 'git'。
279
+ const updateKind = bundle.update
280
+ if (updateKind !== 'registry' && updateKind !== 'git') return { reason: 'not-updatable' }
281
+ const kind = updateKind === 'registry' ? 'npm' : 'git'
282
+ const current = typeof bundle.version === 'string' ? bundle.version : ''
283
+ if (current === '') return { reason: 'no-version' }
284
+ const enabled = bundle.enabled === true
285
+ if (kind === 'npm') {
286
+ // 必须是「用自身包名的 registry spec」:`npm:` 别名会把别的包装成这个名字。
287
+ if (/^npm:/u.test(spec) || /^[a-z][a-z0-9+.-]*:/iu.test(spec)) return { reason: 'not-own-name-registry-spec' }
288
+ const at = spec.indexOf('@', 1)
289
+ const specName = at === -1 ? spec : spec.slice(0, at)
290
+ const range = at === -1 ? undefined : spec.slice(at + 1)
291
+ if (specName !== name) return { reason: 'not-own-name-registry-spec' }
292
+ if (range !== undefined && range.includes(':')) return { reason: 'not-own-name-registry-spec' }
293
+ return { kind, name, current, enabled, spec }
294
+ }
295
+ const git = parseGitSpec(spec)
296
+ if (git === undefined) return { reason: 'unpinned-git-spec' }
297
+ return { kind, name, current, enabled, spec, origin: { host: git.host, repository: git.repository, path: git.path, commit: git.commit } }
298
+ }
299
+
300
+ /**
301
+ * 收集候选(只读:缓存索引 + `listBundles()`,不联网)。
302
+ *
303
+ * `latest` / `incompatible` / `prerelease` / `deprecated` 来自上一次检查的缓存结果
304
+ * (`POST /updates/check` 写入),没有缓存时 `latest` 为 null、`state` 为 `unknown`。
305
+ * 没有任何更高版本的候选(`state === 'current'`)会被剔除。
306
+ *
307
+ * @param {object} input - 输入。
308
+ * @param {Record<string, unknown>[]} input.bundles - `pluginManager.listBundles()` 的结果。
309
+ * @param {string[]} [input.indexSignatures] - 已缓存索引的签名(仅用于让结果可解释,可为空)。
310
+ * @param {Record<string, {latest?: string|null, incompatible?: unknown, prerelease?: boolean, deprecated?: string}>|undefined} [input.cached] - 上一次检查的结果,按包名索引。
311
+ * @param {{hasIndex?: boolean}} [input.indexInfo] - 本地索引是否可用;不可用时 Git 候选标 `uncheckable`。
312
+ * @param {boolean} [input.includeDisabled] - 含已禁用的插件(设置开关,默认关)。
313
+ * @param {boolean} [input.includePrerelease] - 含预发布/已废弃版本(设置开关,默认关)。
314
+ * @returns {object[]} 候选数组。
315
+ */
316
+ export function collectCandidates(input) {
317
+ const bundles = Array.isArray(input.bundles) ? input.bundles : []
318
+ const cached = input.cached ?? {}
319
+ const indexInfo = input.indexInfo ?? {}
320
+ const includeDisabled = input.includeDisabled === true
321
+ const includePrerelease = input.includePrerelease === true
322
+ const candidates = []
323
+ for (const bundle of bundles) {
324
+ if (bundle === null || typeof bundle !== 'object') continue
325
+ const classified = classifyBundle(bundle)
326
+ if (classified.kind === undefined) continue
327
+ if (classified.enabled === false && !includeDisabled) continue
328
+ const previous = cached[classified.name]
329
+ const previousState = typeof previous?.state === 'string' ? previous.state : undefined
330
+ // 检查缓存里的终态优先:已是最新的不再出现;检查失败/不可检查的原样保留,不能回落成 unknown。
331
+ if (previousState === 'current') continue
332
+ const latest = typeof previous?.latest === 'string' && previous.latest !== '' ? previous.latest : null
333
+ let state
334
+ if (previousState === 'error') {
335
+ state = 'error'
336
+ } else if (previousState === 'uncheckable') {
337
+ state = 'uncheckable'
338
+ } else {
339
+ state = latest === null ? 'unknown' : 'available'
340
+ if (latest !== null && classified.kind === 'npm') {
341
+ try {
342
+ if (compareVersions(latest, classified.current) <= 0) state = 'current'
343
+ } catch {
344
+ state = 'unknown'
345
+ }
346
+ }
347
+ }
348
+ if (state === 'current') continue
349
+ const prerelease = previous?.prerelease === true || (latest !== null && isPrerelease(latest))
350
+ const deprecated = typeof previous?.deprecated === 'string' && previous.deprecated !== '' ? previous.deprecated : null
351
+ if (state === 'available' && (prerelease || deprecated !== null) && !includePrerelease) {
352
+ // 目标版本是预发布/已废弃:开关关着时降级为「暂不推荐」,仍显示但不勾选。
353
+ state = 'skipped'
354
+ }
355
+ let reason = typeof previous?.reason === 'string' && previous.reason !== '' ? previous.reason : null
356
+ if (classified.kind === 'git' && indexInfo.hasIndex !== true && state !== 'error') {
357
+ // 本地没有索引:Git 包无法比提交,标记不可检查并把原因给界面。
358
+ state = 'uncheckable'
359
+ if (reason === null) reason = 'index-miss'
360
+ }
361
+ candidates.push({
362
+ name: classified.name,
363
+ current: classified.current,
364
+ latest,
365
+ kind: classified.kind,
366
+ state,
367
+ enabled: classified.enabled,
368
+ incompatible: previous?.incompatible ?? null,
369
+ prerelease,
370
+ deprecated,
371
+ // 检查失败/不可检查的原因:界面「检查失败」筛选与展开详情都依赖它。
372
+ error: typeof previous?.error === 'string' && previous.error !== '' ? previous.error : null,
373
+ reason,
374
+ ...classified.spec === undefined ? {} : { spec: classified.spec },
375
+ ...classified.kind === 'git' ? { origin: classified.origin } : {},
376
+ })
377
+ }
378
+ return candidates
379
+ }
380
+
381
+ // --- 检查 ----------------------------------------------------------------------
382
+
383
+ /**
384
+ * 从索引版本列表里挑指定仓库目录的最新 Git 提交。
385
+ * @param {IndexVersion[]} versions - 该包在索引里的版本(可以来自多份索引的合并结果)。
386
+ * @param {{host: string, repository: string, path: string}} origin - 已安装副本的仓库目录。
387
+ * @returns {{commit: string, version: string}|undefined} 最新提交;没有匹配的仓库目录时 undefined。
388
+ */
389
+ export function latestGitFromIndex(versions, origin) {
390
+ let best
391
+ for (const version of versions) {
392
+ if (version === null || typeof version !== 'object' || version.type !== 'git' || version.git === undefined) continue
393
+ if (version.git.host !== origin.host || version.git.repository !== origin.repository) continue
394
+ if (version.git.path !== origin.path) continue
395
+ if (best === undefined || isGreaterVersion(version, best)) best = { commit: version.git.commit, version: version.version, publishTimestamp: version.publishTimestamp ?? 0 }
396
+ }
397
+ return best
398
+ }
399
+
400
+ /**
401
+ * 两条索引版本里,`candidate` 是否比 `best` 更新。
402
+ *
403
+ * 索引版本按 semver 降序排列,正常情况下第一条就是最新;同一版本的多个提交、
404
+ * 或 semver 不可比时用发布时间兜底,保证总有一个确定答案。
405
+ * @param {IndexVersion} candidate - 待比较的版本。
406
+ * @param {{commit: string, version: string, publishTimestamp?: number}} best - 当前最佳。
407
+ * @returns {boolean} 候选更新时为 true。
408
+ */
409
+ function isGreaterVersion(candidate, best) {
410
+ if (candidate.git === undefined) return false
411
+ if (candidate.git.commit === best.commit) return false
412
+ const left = parseVersion(candidate.version)
413
+ const right = parseVersion(best.version)
414
+ if (left !== undefined && right !== undefined) {
415
+ try {
416
+ const compare = compareVersions(candidate.version, best.version)
417
+ if (compare !== 0) return compare > 0
418
+ } catch {
419
+ // 落到发布时间比较。
420
+ }
421
+ }
422
+ return (candidate.publishTimestamp ?? 0) > (best.publishTimestamp ?? 0)
423
+ }
424
+
425
+ /**
426
+ * 检查一个候选的目标版本。
427
+ *
428
+ * npm 包:`listVersions()` 是权威来源(含兼容性、标签、废弃标记);
429
+ * Git 包:从本地索引里该仓库目录的最新 `source.commit` 解析,索引里没有该包时标记不可检查。
430
+ *
431
+ * @param {object} candidate - {@link collectCandidates} 返回的候选。
432
+ * @param {object} dependencies - 注入的数据源。
433
+ * @param {(name: string) => Promise<unknown>} dependencies.listVersions - `pluginManager.listVersions`。
434
+ * @param {(name: string, origin: {host: string, repository: string, path: string}) => {commit: string, version: string}|undefined} dependencies.latestGit - 从本地索引解析最新提交。
435
+ * @param {boolean} [dependencies.includePrerelease] - 含预发布/已废弃版本。
436
+ * @returns {Promise<object>} 检查结果(可直接合并进候选与 `/updates` 响应)。
437
+ */
438
+ export async function checkCandidate(candidate, dependencies) {
439
+ const includePrerelease = dependencies.includePrerelease === true
440
+ if (candidate === null || typeof candidate !== 'object' || typeof candidate.name !== 'string') {
441
+ return { name: '', state: 'error', latest: null, error: 'invalid-candidate' }
442
+ }
443
+ const base = {
444
+ name: candidate.name,
445
+ current: typeof candidate.current === 'string' ? candidate.current : '',
446
+ kind: candidate.kind === 'git' ? 'git' : 'npm',
447
+ }
448
+ try {
449
+ if (base.kind === 'git') {
450
+ if (candidate.origin === undefined) {
451
+ return { ...base, state: 'uncheckable', latest: null, reason: 'unpinned-git-spec' }
452
+ }
453
+ const found = dependencies.latestGit(candidate.name, candidate.origin)
454
+ if (found === undefined) {
455
+ return { ...base, state: 'uncheckable', latest: null, reason: 'index-miss' }
456
+ }
457
+ const current = typeof candidate.current === 'string' ? candidate.current : ''
458
+ // 提交不同就算有更新:索引里版本号没变也可能推了新提交(内容不同)。
459
+ if (found.commit === candidate.origin.commit) return { ...base, state: 'current', latest: null, commit: found.commit }
460
+ return {
461
+ ...base,
462
+ state: 'available',
463
+ // Git 包的目标是提交;版本号只是给界面看的(真正安装的是 `spec` 里固定的 commit)。
464
+ latest: found.version,
465
+ commit: found.commit,
466
+ spec: buildGitSpec(candidate.origin, found.commit),
467
+ incompatible: null,
468
+ prerelease: false,
469
+ deprecated: null,
470
+ }
471
+ }
472
+ const listing = await dependencies.listVersions(base.name)
473
+ if (listing === null || typeof listing !== 'object' || listing.status !== 'listed') {
474
+ return {
475
+ ...base,
476
+ state: 'error',
477
+ latest: null,
478
+ error: listing !== null && typeof listing === 'object' && typeof listing.problem === 'string' ? listing.problem : 'not-updatable',
479
+ }
480
+ }
481
+ const versions = Array.isArray(listing.versions) ? listing.versions : []
482
+ const usable = versions.filter(version => version !== null && typeof version === 'object'
483
+ && parseVersion(version.version) !== undefined && version.bundle !== false)
484
+ if (usable.length === 0) return { ...base, state: 'current', latest: null }
485
+ const target = usable[0]
486
+ let state = 'available'
487
+ if (target.prerelease === true || target.deprecated !== undefined) {
488
+ if (!includePrerelease) state = 'skipped'
489
+ }
490
+ return {
491
+ ...base,
492
+ state,
493
+ latest: target.version,
494
+ incompatible: target.incompatible ?? null,
495
+ prerelease: target.prerelease === true,
496
+ deprecated: typeof target.deprecated === 'string' && target.deprecated !== '' ? target.deprecated : null,
497
+ registry: typeof listing.registry === 'string' || listing.registry === null ? listing.registry : undefined,
498
+ }
499
+ } catch (error) {
500
+ return { ...base, state: 'error', latest: null, error: error instanceof Error ? error.message : String(error) }
501
+ }
502
+ }
503
+
504
+ /**
505
+ * 批量检查候选。
506
+ * @param {object} input - 输入。
507
+ * @param {object[]} input.candidates - {@link collectCandidates} 的结果。
508
+ * @param {string[]} [input.names] - 只检查这些包名;省略时全部检查。
509
+ * @param {object} input.dependencies - 同 {@link checkCandidate}。
510
+ * @returns {Promise<{checked: object[], skipped: string[], unknown: string[]}>} 结果与未命中的包名。
511
+ */
512
+ export async function checkCandidates(input) {
513
+ const all = Array.isArray(input.candidates) ? input.candidates : []
514
+ const wanted = Array.isArray(input.names) && input.names.length > 0 ? new Set(input.names) : undefined
515
+ const targets = wanted === undefined ? all : all.filter(candidate => wanted.has(candidate.name))
516
+ const unknown = wanted === undefined ? [] : [...wanted].filter(name => !all.some(candidate => candidate.name === name))
517
+ const skipped = all.filter(candidate => wanted !== undefined && !wanted.has(candidate.name)).map(candidate => candidate.name)
518
+ const checked = await Promise.all(targets.map(candidate => checkCandidate(candidate, input.dependencies)))
519
+ return { checked, skipped, unknown }
520
+ }
521
+
522
+ // --- 顺序更新队列 ---------------------------------------------------------------
523
+
524
+ /** 队列项对外的形态(写进 `/updates/state` 的 `items[]`)。 */
525
+ /**
526
+ * @typedef {object} QueueItem
527
+ * @property {string} name
528
+ * @property {string} current
529
+ * @property {string} latest
530
+ * @property {string} version
531
+ * @property {'npm'|'git'} kind
532
+ * @property {string} [spec]
533
+ * @property {string} requestId
534
+ * @property {string} stage
535
+ * @property {boolean} success
536
+ * @property {boolean} failed
537
+ * @property {boolean} restartRequired
538
+ * @property {boolean} cancelled
539
+ * @property {string|null} error
540
+ * @property {object|null} restore
541
+ * @property {number} startedAt
542
+ * @property {number|null} endedAt
543
+ */
544
+
545
+ /**
546
+ * 把 `ManagementError` 压成一句能显示给用户的失败原因。
547
+ *
548
+ * 优先级:`diagnostic`(最具体)→ `code`(`incompatible-version` 时附上具体
549
+ * `incompatible[].name@version`)→ `message` → `application:<application>`。
550
+ * @param {unknown} error - `updateBundle().result.error`。
551
+ * @param {string|undefined} application - `result.application`。
552
+ * @returns {string} 失败原因。
553
+ */
554
+ function describeUpdateError(error, application) {
555
+ if (error !== null && typeof error === 'object') {
556
+ const value = /** @type {Record<string, unknown>} */ (error)
557
+ const diagnostic = typeof value.diagnostic === 'string' ? value.diagnostic.trim() : ''
558
+ if (diagnostic !== '') return diagnostic
559
+ const code = typeof value.code === 'string' ? value.code : ''
560
+ if (code === 'incompatible-version' && Array.isArray(value.incompatible)) {
561
+ const rejected = value.incompatible.map((entry) => {
562
+ const item = entry !== null && typeof entry === 'object' ? /** @type {Record<string, unknown>} */ (entry) : {}
563
+ const name = typeof item.name === 'string' ? item.name : ''
564
+ const version = typeof item.version === 'string' ? item.version : ''
565
+ return name === '' ? '' : `${name}@${version === '' ? '?' : version}`
566
+ }).filter(entry => entry !== '')
567
+ return rejected.length === 0 ? code : `${code}: ${rejected.join(', ')}`
568
+ }
569
+ if (code !== '') {
570
+ const message = typeof value.message === 'string' ? value.message.trim() : ''
571
+ return message === '' || message === code ? code : `${code}: ${message}`
572
+ }
573
+ const message = typeof value.message === 'string' ? value.message.trim() : ''
574
+ if (message !== '') return message
575
+ }
576
+ if (typeof application === 'string' && application !== '') return `application:${application}`
577
+ return 'unknown-outcome'
578
+ }
579
+
580
+ /**
581
+ * 把一个 `pluginManager.updateBundle()` 的结果拍平成队列项要的字段。
582
+ *
583
+ * `success` / `failed` / `restartRequired` / `restore` 是契约字段,另外保留 `result`
584
+ * 供界面展开看诊断;`restore` 非空表示目标版本安装失败后已经装回旧版本。
585
+ * @param {unknown} outcome - `updateBundle()` 的返回值。
586
+ * @returns {{success: boolean, failed: boolean, restartRequired: boolean, restore: object|null, error: string|null, result: unknown}} 拍平结果。
587
+ */
588
+ export function flattenUpdateOutcome(outcome) {
589
+ if (outcome === null || typeof outcome !== 'object') {
590
+ return { success: false, failed: true, restartRequired: false, restore: null, error: 'updateBundle returned no result', result: outcome }
591
+ }
592
+ const value = /** @type {Record<string, unknown>} */ (outcome)
593
+ const result = value.result !== null && typeof value.result === 'object' ? /** @type {Record<string, unknown>} */ (value.result) : undefined
594
+ const application = result?.application
595
+ const restore = value.restore !== null && typeof value.restore === 'object' ? /** @type {object} */ (value.restore) : null
596
+ const success = application === 'applied'
597
+ const restartRequired = application === 'restart-required'
598
+ const cancelled = application === 'cancelled'
599
+ const error = cancelled
600
+ ? 'cancelled'
601
+ : success || restartRequired
602
+ ? null
603
+ : describeUpdateError(result?.error, typeof application === 'string' ? application : undefined)
604
+ return { success: success || restartRequired, failed: !success && !restartRequired && !cancelled, restartRequired, restore, error, result: outcome }
605
+ }
606
+
607
+ /**
608
+ * 创建一个顺序更新队列(纯状态机,不自己发请求)。
609
+ *
610
+ * 执行动作由调用方通过 `runItem` 注入(通常是 `pluginManager.updateBundle`):
611
+ * 单项抛错或返回失败结果都只标记该项失败,**继续下一项**;`stop()` 之后队列停在新项之前,
612
+ * 正在跑的那一项由调用方按后端取消流程结束。
613
+ *
614
+ * @param {object} options - 选项。
615
+ * @param {object[]} options.items - 要更新的项:`{name, current, latest, kind, spec?}`。
616
+ * @param {(item: object) => Promise<unknown>} options.runItem - 执行一项;返回值交给 {@link flattenUpdateOutcome}。
617
+ * @param {(message: string) => void} [options.onError] - 单项失败时的回调(用于写日志)。
618
+ * @param {(name: string) => string} [options.requestIdFor] - 为一项生成 requestId;默认 `updates-<序号>-<时间戳>`。
619
+ * @returns {{start: () => Promise<object>, stop: () => void, isStopped: () => boolean, isRunning: () => boolean, snapshot: () => object, setStage: (name: string, stage: string) => boolean, requestIdOf: (name: string) => string|undefined}} 队列句柄。
620
+ */
621
+ export function createUpdateQueue(options) {
622
+ const inputs = Array.isArray(options.items) ? options.items : []
623
+ const runItem = options.runItem
624
+ const onError = options.onError ?? (() => {})
625
+ const requestIdFor = options.requestIdFor ?? ((name, index) => `updates-${String(index)}-${name}-${String(Date.now())}`)
626
+ const startedAt = Date.now()
627
+ /** @type {QueueItem[]} */
628
+ const items = inputs.map((item, index) => ({
629
+ name: String(item.name),
630
+ current: typeof item.current === 'string' ? item.current : '',
631
+ latest: typeof item.latest === 'string' ? item.latest : '',
632
+ version: typeof item.version === 'string' ? item.version : typeof item.latest === 'string' ? item.latest : '',
633
+ kind: item.kind === 'git' ? 'git' : 'npm',
634
+ ...item.spec === undefined ? {} : { spec: item.spec },
635
+ requestId: requestIdFor(String(item.name), index),
636
+ stage: 'queued',
637
+ success: false,
638
+ failed: false,
639
+ restartRequired: false,
640
+ cancelled: false,
641
+ error: null,
642
+ restore: null,
643
+ startedAt: 0,
644
+ endedAt: null,
645
+ }))
646
+ let stopped = false
647
+ let running = false
648
+ /** 当前正在跑的下标;-1 表示没有。 */
649
+ let active = -1
650
+ let finished = false
651
+ const summary = () => ({
652
+ total: items.length,
653
+ success: items.filter(item => item.success).length,
654
+ failed: items.filter(item => item.failed).length,
655
+ cancelled: items.filter(item => item.cancelled).length,
656
+ // 「需重启」是成功的一种:单独计数,界面汇总要显示。
657
+ restartRequired: items.filter(item => item.restartRequired).length,
658
+ skipped: items.filter(item => item.cancelled).length,
659
+ pending: items.filter(item => !item.success && !item.failed && !item.cancelled).length,
660
+ })
661
+
662
+ /**
663
+ * 把一项标记为取消。
664
+ * @param {QueueItem} item - 队列项。
665
+ * @param {string|null} [reason] - 取消前已经拿到的失败诊断。
666
+ * @returns {void}
667
+ */
668
+ function markCancelled(item, reason) {
669
+ item.cancelled = true
670
+ item.success = false
671
+ item.failed = false
672
+ item.restartRequired = false
673
+ item.error = item.error ?? reason ?? 'cancelled'
674
+ item.stage = 'cancelled'
675
+ item.endedAt = Date.now()
676
+ }
677
+
678
+ return {
679
+ /** 依次执行所有项;每项失败都继续下一项。 */
680
+ async start() {
681
+ if (running) return { requestIds: items.map(item => item.requestId), items, summary: summary(), running: true, stopped }
682
+ running = true
683
+ for (let index = 0; index < items.length; index++) {
684
+ const item = items[index]
685
+ if (stopped) {
686
+ markCancelled(item)
687
+ continue
688
+ }
689
+ active = index
690
+ item.stage = 'checking'
691
+ item.startedAt = Date.now()
692
+ /** @type {unknown} */
693
+ let outcome
694
+ try {
695
+ outcome = await runItem(item)
696
+ } catch (error) {
697
+ outcome = undefined
698
+ item.error = error instanceof Error ? error.message : String(error)
699
+ }
700
+ const flat = outcome === undefined && item.error !== null
701
+ ? { success: false, failed: true, restartRequired: false, restore: null, error: item.error, result: null }
702
+ : flattenUpdateOutcome(outcome)
703
+ if (stopped && !flat.success) {
704
+ // 被取消的那一项:成功的结果照常记下,没成功的落到取消。
705
+ item.restore = flat.restore
706
+ item.result = flat.result
707
+ markCancelled(item, flat.error)
708
+ } else {
709
+ item.success = flat.success
710
+ item.failed = flat.failed
711
+ item.restartRequired = flat.restartRequired
712
+ item.error = flat.error
713
+ item.restore = flat.restore
714
+ item.result = flat.result
715
+ item.stage = flat.success ? 'done' : 'failed'
716
+ }
717
+ item.endedAt = Date.now()
718
+ if (item.failed) onError(`${item.name}: ${flat.error ?? 'failed'}`)
719
+ active = -1
720
+ }
721
+ finished = true
722
+ running = false
723
+ return { requestIds: items.map(item => item.requestId), items, summary: summary(), running: false, stopped }
724
+ },
725
+ /** 停止队列:当前项交给调用方的取消流程,后面的项直接标记取消。 */
726
+ stop() {
727
+ stopped = true
728
+ },
729
+ /** @returns {boolean} 是否已请求停止。 */
730
+ isStopped() {
731
+ return stopped
732
+ },
733
+ /** @returns {boolean} 是否还有项在跑。 */
734
+ isRunning() {
735
+ return running
736
+ },
737
+ /** @returns {boolean} 是否全部走完(成功、失败或取消)。 */
738
+ isFinished() {
739
+ return finished
740
+ },
741
+ /** @returns {number} 当前正在跑的下标;-1 表示没有。 */
742
+ activeIndex() {
743
+ return active
744
+ },
745
+ /** 更新某项的阶段(来自 `plugin-manager/update-state`)。 */
746
+ setStage(name, stage) {
747
+ const item = items.find(entry => entry.name === name)
748
+ if (item === undefined || typeof stage !== 'string') return false
749
+ if (['queued', 'done', 'failed', 'cancelled'].includes(item.stage)) return false
750
+ item.stage = stage
751
+ return true
752
+ },
753
+ /** @param {string} name - 包名。 @returns {string|undefined} 该项的 requestId。 */
754
+ requestIdOf(name) {
755
+ return items.find(item => item.name === name)?.requestId
756
+ },
757
+ /** @returns {object} 队列快照(`/updates/state` 的 `queue` 字段)。 */
758
+ snapshot() {
759
+ return {
760
+ startedAt,
761
+ running,
762
+ stopped,
763
+ finished,
764
+ summary: summary(),
765
+ items: items.map(item => ({ ...item })),
766
+ }
767
+ },
768
+ }
769
+ }