dsh-modpack-kit 0.2.4 → 0.3.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.
@@ -0,0 +1,461 @@
1
+ /**
2
+ * @file lib/plugin-graph.mjs
3
+ * @role 只用「声明」拼插件树与兼容树:本插件 → 附属小插件 → 路由;依赖 → 谁要求什么版本
4
+ * @sub 读宿主 package.json, 读附属小插件清单, 读已装插件的声明, 算兼容判定, 排成列
5
+ * @exports api:buildPluginTree, buildCompatTree, readDeclarations, SUB_FILES
6
+ * @uses lib/subplugins.mjs(清单从那儿统一读), lib/profile.mjs(listInstalled)
7
+ * @reads 插件根 package.json、<dir>/manifest.json、<profile>/node_modules 下每个包的 package.json(只读)
8
+ * @writes 不写任何文件
9
+ * @risk 这里按「声明」判兼容,不跑代码;声明说谎(比如写了支持的版本其实不支持)这边发现不了,只能如实标注 unknown
10
+ * @touch 加附属小插件 → 同步 lib/subplugins.mjs 的 SUBPLUGINS 表;改判定口径 → 同步 client.js 的插件树图例与 test/run.mjs
11
+ * @since 0.3.0
12
+ */
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+ import { SUBPLUGINS, readSubManifests } from './subplugins.mjs'
16
+ import { satisfies, parseVersion } from './semver.mjs'
17
+
18
+ export const SUB_FILES = SUBPLUGINS.map((item) => item.dir)
19
+
20
+ function readJson(file, fallback = null) {
21
+ try {
22
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
23
+ } catch {
24
+ return fallback
25
+ }
26
+ }
27
+
28
+ /** 读本插件自己的声明(package.json + 附属小插件清单)。 */
29
+ export function readDeclarations(root, profileDir, config = {}) {
30
+ const pkg = readJson(path.join(root, 'package.json'), {}) || {}
31
+ const subs = []
32
+ for (const manifest of readSubManifests(root)) {
33
+ const enabled = manifest.configKey ? config[manifest.configKey] !== false : true
34
+ subs.push({ ...manifest, enabled })
35
+ }
36
+ let installed = []
37
+ if (profileDir) {
38
+ try {
39
+ installed = readInstalledPackages(profileDir)
40
+ } catch {
41
+ installed = []
42
+ }
43
+ }
44
+ return { pkg, subs, installed }
45
+ }
46
+
47
+ // 已装插件的声明:只读 package.json 里那几个字段,不碰源码,几百个包也是毫秒级
48
+ // 已装包的声明读一次就够:node_modules 的 mtime 没变就复用上次的结果(增删插件会改它)。
49
+ // 插件树一次请求要拿几十个包的声明,没有这层缓存时每次都要 stat + read 几百个 package.json。
50
+ const installedMemo = new Map()
51
+ const INSTALLED_TTL = 5000
52
+
53
+ function readInstalledPackages(profileDir) {
54
+ const modules = path.join(profileDir, 'node_modules')
55
+ const out = []
56
+ let entries = []
57
+ let stamp = ''
58
+ try {
59
+ const stat = fs.statSync(modules)
60
+ stamp = String(stat.mtimeMs) + '|' + String(stat.size)
61
+ } catch {
62
+ return out
63
+ }
64
+ const memo = installedMemo.get(modules)
65
+ if (memo && memo.stamp === stamp && Date.now() - memo.at < INSTALLED_TTL) return memo.value
66
+ try {
67
+ entries = fs.readdirSync(modules, { withFileTypes: true })
68
+ } catch {
69
+ return out
70
+ }
71
+ const push = (dir, nameFromScope) => {
72
+ const file = path.join(dir, 'package.json')
73
+ const pkg = readJson(file)
74
+ if (!pkg || !pkg.name) return
75
+ if (!String(pkg.name).startsWith('dsh') && !String(pkg.name).startsWith('@dsh') && !pkg.dsh) return
76
+ out.push({
77
+ name: pkg.name || nameFromScope,
78
+ version: String(pkg.version || ''),
79
+ dir,
80
+ dsh: pkg.dsh || null,
81
+ engines: pkg.engines || {},
82
+ peer: pkg.peerDependencies || {},
83
+ deps: Object.keys(pkg.dependencies || {}),
84
+ depSpecs: pkg.dependencies || {},
85
+ description: String(pkg.description || '').slice(0, 160),
86
+ })
87
+ }
88
+ for (const entry of entries) {
89
+ if (!entry.isDirectory()) continue
90
+ if (entry.name.startsWith('.')) continue
91
+ if (entry.name.startsWith('@')) {
92
+ const scopeDir = path.join(modules, entry.name)
93
+ let inner = []
94
+ try {
95
+ inner = fs.readdirSync(scopeDir, { withFileTypes: true })
96
+ } catch {
97
+ inner = []
98
+ }
99
+ for (const child of inner) {
100
+ if (child.isDirectory()) push(path.join(scopeDir, child.name), entry.name + '/' + child.name)
101
+ }
102
+ continue
103
+ }
104
+ push(path.join(modules, entry.name), entry.name)
105
+ }
106
+ installedMemo.set(modules, { stamp, at: Date.now(), value: out })
107
+ return out
108
+ }
109
+
110
+ // 「声明里的支持范围」判定:只比范围,不试跑。
111
+ function versionVerdict(range, actual) {
112
+ const text = String(range || '').trim()
113
+ const parsed = parseVersion(actual)
114
+ if (!text) return { ok: null, reason: '声明里没写要求' }
115
+ if (!parsed) return { ok: null, reason: '读不到已装版本' }
116
+ const version = String(actual).trim()
117
+ try {
118
+ if (satisfies(version, text)) return { ok: true, reason: version + ' ∈ ' + text }
119
+ return { ok: false, reason: version + ' ∉ ' + text }
120
+ } catch {
121
+ return { ok: null, reason: '范围看不懂:' + text }
122
+ }
123
+ }
124
+
125
+ /** 候选插件:先摆已装的,再摆市场里没装但支持的(市场目录由调用方传进来,这里不碰网络)。 */
126
+ export function listTreeCandidates(root, profileDir, config = {}, market = null) {
127
+ const { pkg, installed } = readDeclarations(root, profileDir, config)
128
+ const selfName = String(pkg.name || 'dsh-modpack-kit')
129
+ const seen = new Set([selfName])
130
+ const items = [
131
+ {
132
+ name: selfName,
133
+ title: selfName,
134
+ version: String(pkg.version || ''),
135
+ installed: true,
136
+ self: true,
137
+ category: '本插件',
138
+ description: String(pkg.description || '').slice(0, 160),
139
+ },
140
+ ]
141
+ for (const item of installed) {
142
+ if (seen.has(item.name)) continue
143
+ seen.add(item.name)
144
+ items.push({
145
+ name: item.name,
146
+ title: item.name,
147
+ version: item.version,
148
+ installed: true,
149
+ self: false,
150
+ category: '',
151
+ description: item.description,
152
+ requires: (item.deps || []).length + Object.keys(item.peer || {}).length,
153
+ missing: (item.deps || []).filter((name) => name !== selfName && !installed.some((other) => other.name === name)).length,
154
+ })
155
+ }
156
+ const installedCount = items.length
157
+ const rows = market && Array.isArray(market.plugins) ? market.plugins : []
158
+ for (const row of rows) {
159
+ const name = row && row.name ? String(row.name) : ''
160
+ if (!name || seen.has(name)) continue
161
+ seen.add(name)
162
+ items.push({
163
+ name,
164
+ title: String(row.title || name),
165
+ version: String(row.version || ''),
166
+ installed: false,
167
+ self: false,
168
+ category: String(row.category || ''),
169
+ description: String(row.description || '').slice(0, 160),
170
+ requires: 0,
171
+ missing: 0,
172
+ })
173
+ }
174
+ return {
175
+ items,
176
+ total: items.length,
177
+ installedCount,
178
+ marketListed: rows.length,
179
+ }
180
+ }
181
+
182
+ /** 把「一个名字」翻成声明记录:本插件、已装插件都从这里取。 */
183
+ function recordOf(name, self, installed) {
184
+ if (self && self.name === name) return self
185
+ return installed.find((item) => item.name === name) || null
186
+ }
187
+
188
+ /**
189
+ * 相关性树:勾中的每个插件当一根,往两边展开——
190
+ * 它要什么(dependencies / peer)、谁要它(被依赖)、它自己还挂了什么(附属小插件与接口)。
191
+ * 兼容判定只比声明,不跑别人的代码。
192
+ */
193
+ // 右侧详情的统一口径(顺序也是给人读的顺序):
194
+ // 版本要求 → 要求方 → 已装版本 → 树来源 → 是否安装
195
+ const relationDetail = ({ range, from, installedVersion, chain, installed }) => ({
196
+ '版本要求': range ? String(range) : '无来源',
197
+ '要求方': from ? String(from) : '无来源',
198
+ '已装版本': installedVersion ? String(installedVersion) : '无',
199
+ '树来源': chain ? String(chain) : '(勾选它自己)',
200
+ '是否安装': installed ? '是' : '否',
201
+ })
202
+
203
+ export function buildRelations(root, profileDir, config = {}, names = []) {
204
+ const { pkg, subs, installed } = readDeclarations(root, profileDir, config)
205
+ const self = {
206
+ name: String(pkg.name || 'dsh-modpack-kit'),
207
+ version: String(pkg.version || ''),
208
+ dir: root,
209
+ dsh: pkg.dsh || null,
210
+ engines: pkg.engines || {},
211
+ peer: pkg.peerDependencies || {},
212
+ deps: Object.keys(pkg.dependencies || {}),
213
+ depSpecs: pkg.dependencies || {},
214
+ description: String(pkg.description || '').slice(0, 160),
215
+ }
216
+ const pool = [self].concat(installed.filter((item) => item.name !== self.name))
217
+ const picked = []
218
+ for (const raw of Array.isArray(names) ? names : []) {
219
+ const name = String(raw || '').trim()
220
+ if (!name || picked.includes(name)) continue
221
+ picked.push(name)
222
+ }
223
+ if (!picked.length) picked.push(self.name)
224
+ const roots = picked.slice(0, 12)
225
+
226
+ const nodes = []
227
+ const edges = []
228
+ const seenNodes = new Set()
229
+ const counts = { plugins: 0, deps: 0, peers: 0, dependents: 0, subplugins: 0, routes: 0, warn: 0, unknown: 0 }
230
+ const pushNode = (node) => {
231
+ if (seenNodes.has(node.id)) return node
232
+ seenNodes.add(node.id)
233
+ nodes.push(node)
234
+ return node
235
+ }
236
+ const pushEdge = (from, to, kind, label) => edges.push({ from, to, kind, label })
237
+
238
+ for (const name of roots) {
239
+ const record = recordOf(name, self, installed)
240
+ const isSelf = name === self.name
241
+ const installedHere = Boolean(record)
242
+ const compat = installedHere ? 'ok' : 'unknown'
243
+ if (compat === 'unknown') counts.unknown += 1
244
+ counts.plugins += 1
245
+ const rootId = 'plugin:' + name
246
+ // 它自己的前置条件(依赖 + 版本要求),根节点上直接列出来:
247
+ // 「勾了它,它还要什么」应该是第一眼能看到的,而不是要一个个点节点去翻。
248
+ const requires = record
249
+ ? (record.deps || []).map((depName) => ({
250
+ kind: 'dep',
251
+ name: depName,
252
+ range: String((record.depSpecs || {})[depName] || ''),
253
+ installed: installed.some((item) => item.name === depName),
254
+ })).concat(Object.entries(record.peer || {}).map(([peerName, range]) => ({
255
+ kind: 'peer',
256
+ name: peerName,
257
+ range: String(range),
258
+ installed: installed.some((item) => item.name === peerName) || self.name === peerName,
259
+ })))
260
+ : []
261
+ const missingRequires = requires.filter((item) => !item.installed)
262
+ const requiresText = requires.length
263
+ ? '前置 ' + requires.length + ' 项' + (missingRequires.length ? ' · 缺 ' + missingRequires.length + ' 项' : ' · 都在本机')
264
+ : '没写前置条件'
265
+ pushNode({
266
+ id: rootId,
267
+ kind: 'plugin',
268
+ col: 0,
269
+ label: name,
270
+ sub: (record ? 'v' + record.version : '没装') + ' · ' + requiresText,
271
+ version: record ? record.version : '',
272
+ compat,
273
+ requires,
274
+ missingRequires: missingRequires.map((item) => item.name),
275
+ requiresText,
276
+ detail: {
277
+ 名字: name,
278
+ 前置条件: requires.length
279
+ ? requires.map((item) => (item.kind === 'peer' ? '版本要求 ' : '依赖 ') + item.name + (item.range ? ' ' + item.range : '') + (item.installed ? '' : '(本机没有)')).join(String.fromCharCode(10))
280
+ : '没写前置条件',
281
+ 已装版本: record ? String(record.version) : '无',
282
+ 是否安装: record ? '是' : '否',
283
+ 树来源: '(勾选它自己)',
284
+ 简介: (record && record.description) || '',
285
+ 目录: record && record.dir ? record.dir : '不在本机',
286
+ 引擎: record && record.engines && record.engines.node ? 'Node ' + record.engines.node : '没写',
287
+ 清单补丁: record && record.dsh && record.dsh.bundle && record.dsh.bundle.patch ? record.dsh.bundle.patch : '无',
288
+ 客户端: record && record.dsh && record.dsh.client ? String(record.dsh.client.platform || '有') : '无',
289
+ },
290
+ })
291
+ if (!record) {
292
+ // 市场里有、本机没有:没有声明可读,只能给一层「装了什么依赖都不知道」的占位
293
+ continue
294
+ }
295
+ // 它要什么
296
+ for (const depName of record.deps || []) {
297
+ const spec = String((record.depSpecs || {})[depName] || '')
298
+ const depRecord = installed.find((item) => item.name === depName)
299
+ const depId = 'dep:' + depName
300
+ const verdict = versionVerdict(spec, depRecord ? depRecord.version : '')
301
+ const bad = verdict.ok === false
302
+ if (bad) counts.warn += 1
303
+ if (verdict.ok === null) counts.unknown += 1
304
+ counts.deps += 1
305
+ pushNode({
306
+ id: depId,
307
+ kind: 'dep',
308
+ col: 1,
309
+ label: depName,
310
+ sub: depRecord ? 'v' + depRecord.version : '没装',
311
+ compat: bad ? 'warn' : depRecord ? 'ok' : 'unknown',
312
+ detail: relationDetail({
313
+ range: spec,
314
+ from: name,
315
+ installedVersion: depRecord ? depRecord.version : '',
316
+ chain: name + ' → ' + depName,
317
+ installed: Boolean(depRecord),
318
+ }),
319
+ })
320
+ pushEdge(rootId, depId, 'requires', '依赖')
321
+ }
322
+ // 它要求什么版本
323
+ for (const [peerName, range] of Object.entries(record.peer || {})) {
324
+ const hit = installed.find((item) => item.name === peerName) || (self.name === peerName ? self : null)
325
+ const verdict = versionVerdict(range, hit ? hit.version : '')
326
+ const bad = verdict.ok === false
327
+ if (bad) counts.warn += 1
328
+ if (verdict.ok === null) counts.unknown += 1
329
+ counts.peers += 1
330
+ const peerId = 'peer:' + peerName
331
+ pushNode({
332
+ id: peerId,
333
+ kind: 'peer',
334
+ col: 1,
335
+ label: peerName,
336
+ sub: range,
337
+ compat: bad ? 'warn' : verdict.ok ? 'ok' : 'unknown',
338
+ detail: {
339
+ ...relationDetail({
340
+ range,
341
+ from: name,
342
+ installedVersion: hit ? hit.version : '',
343
+ chain: name + ' → ' + peerName,
344
+ installed: Boolean(hit),
345
+ }),
346
+ 判定: verdict.reason,
347
+ },
348
+ })
349
+ pushEdge(rootId, peerId, 'requires', bad ? '不满足' : '要求')
350
+ }
351
+ // 谁要它
352
+ for (const other of pool) {
353
+ if (other.name === name) continue
354
+ const wants = Object.prototype.hasOwnProperty.call(other.depSpecs || {}, name) || Object.prototype.hasOwnProperty.call(other.peer || {}, name)
355
+ if (!wants) continue
356
+ const range = String((other.peer || {})[name] || (other.depSpecs || {})[name] || '')
357
+ const verdict = versionVerdict(range, record.version)
358
+ const bad = verdict.ok === false
359
+ if (bad) counts.warn += 1
360
+ counts.dependents += 1
361
+ const userId = 'user:' + other.name
362
+ pushNode({
363
+ id: userId,
364
+ kind: 'user',
365
+ col: 1,
366
+ label: other.name,
367
+ sub: range || 'v' + other.version,
368
+ compat: bad ? 'warn' : verdict.ok ? 'ok' : 'unknown',
369
+ detail: {
370
+ ...relationDetail({
371
+ range: range || '',
372
+ from: other.name,
373
+ installedVersion: other.version || '',
374
+ chain: other.name + ' → ' + name,
375
+ installed: true,
376
+ }),
377
+ 说明: '这一条是反过来的:它在用勾中的插件',
378
+ 判定: verdict.reason,
379
+ },
380
+ })
381
+ pushEdge(userId, rootId, 'uses', bad ? '不满足' : '用')
382
+ }
383
+ // 只有本插件才有附属小插件与接口可展开
384
+ if (isSelf) {
385
+ for (const sub of subs) {
386
+ const subId = 'sub:' + sub.id
387
+ counts.subplugins += 1
388
+ pushNode({
389
+ id: subId,
390
+ kind: 'subplugin',
391
+ col: 2,
392
+ label: sub.name || sub.id,
393
+ sub: 'apiVersion ' + (Number(sub.apiVersion) || 1),
394
+ compat: sub.enabled === false ? 'unknown' : 'ok',
395
+ detail: {
396
+ 标识: sub.id,
397
+ apiVersion: String(sub.apiVersion || ''),
398
+ 运行方式: sub.standalone === false ? '随主体' : '可独立运行',
399
+ 开关: sub.configKey || '无',
400
+ 状态: sub.enabled === false ? '已关闭' : '开启',
401
+ },
402
+ })
403
+ pushEdge(rootId, subId, 'owns', '附属')
404
+ for (const route of sub.routes || []) {
405
+ counts.routes += 1
406
+ const routeId = 'route:' + route
407
+ pushNode({
408
+ id: routeId,
409
+ kind: 'route',
410
+ col: 3,
411
+ label: route.replace(/^\/dsh-modpack-kit\/api/u, '/api'),
412
+ sub: sub.id,
413
+ detail: { 完整路径: route, 归属: sub.name || sub.id, 方法: '见 docs/CODE-MAP.md' },
414
+ })
415
+ pushEdge(subId, routeId, 'provides', '提供')
416
+ }
417
+ }
418
+ }
419
+ }
420
+ return {
421
+ kind: 'relations',
422
+ roots: roots.map((name) => 'plugin:' + name),
423
+ nodes,
424
+ edges,
425
+ counts: { ...counts, nodes: nodes.length, edges: edges.length },
426
+ legend: [
427
+ { kind: 'plugin', text: '勾中的插件(根)' },
428
+ { kind: 'dep', text: '它声明的依赖' },
429
+ { kind: 'peer', text: '它对别人的版本要求' },
430
+ { kind: 'user', text: '谁在用它(被依赖)' },
431
+ { kind: 'subplugin', text: '附属小插件(虚线框 = 关系,不是同级插件)' },
432
+ { kind: 'route', text: '对外接口' },
433
+ ],
434
+ }
435
+ }
436
+
437
+ /** 兼容视图:从相关性树里筛出带判定的那些,单独成一棵树给「只看兼容」用。 */
438
+ export function compatOf(relations) {
439
+ const keep = new Set(['plugin', 'dep', 'peer', 'user'])
440
+ const nodes = relations.nodes.filter((node) => keep.has(node.kind))
441
+ const ids = new Set(nodes.map((node) => node.id))
442
+ const edges = relations.edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to))
443
+ return {
444
+ kind: 'compat',
445
+ roots: relations.roots,
446
+ nodes,
447
+ edges,
448
+ counts: {
449
+ nodes: nodes.length,
450
+ edges: edges.length,
451
+ ok: nodes.filter((node) => node.compat === 'ok').length,
452
+ warn: nodes.filter((node) => node.compat === 'warn').length,
453
+ unknown: nodes.filter((node) => node.compat === 'unknown').length,
454
+ },
455
+ legend: [
456
+ { kind: 'ok', text: '声明满足' },
457
+ { kind: 'warn', text: '声明不满足(未必坏,但要知道)' },
458
+ { kind: 'unknown', text: '声明看不懂或没装' },
459
+ ],
460
+ }
461
+ }