dsh-modpack-kit 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,566 @@
1
+ /**
2
+ * dsh-modpack —— Host 侧。
3
+ *
4
+ * 只做四件事:把本机状况喂给页面、在内存里打包、在安装前把包拆开看清楚、调官方 CLI 装。
5
+ * 所有网络请求走 lib/registry 的白名单与体积上限;所有文件写入落在 <DSH_HOME>/dsh-modpack。
6
+ */
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { randomBytes } from 'node:crypto'
10
+ import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
11
+ import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
12
+ import { downloadPackage, npmMetadata, fetchLimited, relativeTime } from './lib/registry.mjs'
13
+ import { buildPack, PackRefused } from './lib/pack.mjs'
14
+ import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
15
+ import { checkCompatibility } from './lib/compat.mjs'
16
+ import { classifyPlugin } from './lib/classify.mjs'
17
+ import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
18
+ import { parseYaml } from './lib/yamlish.mjs'
19
+ import { readPatch } from './lib/profile.mjs'
20
+ import { buildReadme, pluginSummary } from './lib/manifest.mjs'
21
+
22
+ const VERSION = '0.1.0'
23
+ const MAX_JSON_BODY = 1024 * 1024
24
+ const PENDING_TTL = 30 * 60 * 1000
25
+ const PENDING_MAX = 4
26
+ const PENDING_BYTES = 512 * 1024 * 1024
27
+
28
+ const json = (res, code, obj) => {
29
+ res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
30
+ res.end(JSON.stringify(obj))
31
+ }
32
+
33
+ const readBody = (req, limit = MAX_JSON_BODY) => new Promise((resolve, reject) => {
34
+ let size = 0
35
+ const chunks = []
36
+ req.on('data', (chunk) => {
37
+ size += chunk.length
38
+ if (size > limit) { reject(Object.assign(new Error('请求体过大'), { statusCode: 413 })); req.destroy(); return }
39
+ chunks.push(chunk)
40
+ })
41
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
42
+ req.on('error', reject)
43
+ })
44
+
45
+ const asJson = (text, fallback) => {
46
+ try { return JSON.parse(text) } catch { return fallback }
47
+ }
48
+
49
+ export default {
50
+ name: 'dsh-modpack-kit',
51
+ inject: ['webServer'],
52
+ apply(ctx) {
53
+ let config = loadConfig()
54
+ let pending = new Map()
55
+ const disposers = []
56
+ const log = (...args) => { try { console.log('[dsh-modpack-kit]', ...args) } catch {} }
57
+
58
+ const profileDir = () => pathsFor(config).profile
59
+
60
+ const snapshot = () => {
61
+ const dir = profileDir()
62
+ let installed = []
63
+ let version = ''
64
+ let bundles = []
65
+ let error = ''
66
+ try {
67
+ installed = listInstalled(dir)
68
+ version = dshVersion(dir)
69
+ bundles = readBundles(readProfilePackage(dir))
70
+ } catch (e) {
71
+ error = String((e && e.message) || e)
72
+ }
73
+ let catalog = null
74
+ try { catalog = catalogSummary(config) } catch {}
75
+ // 词条分类以插件市场为准;市场目录里没有的(本机私有插件)才退回本地猜测
76
+ let marketCategories = {}
77
+ try { marketCategories = categoryMapFor(config, installed.map((p) => p.name)) } catch {}
78
+ return {
79
+ ok: !error,
80
+ error,
81
+ version,
82
+ platform: process.platform,
83
+ node: process.version,
84
+ electron: process.versions.electron || '',
85
+ dshVersion: version,
86
+ pluginVersion: VERSION,
87
+ profile: profileName(config),
88
+ paths: pathsFor(config),
89
+ catalog,
90
+ placements: {
91
+ settings: config.showInSettings !== false,
92
+ sidebar: config.showInSidebar !== false,
93
+ pluginsTab: config.showInPluginsTab === true,
94
+ },
95
+ installedTotal: installed.length,
96
+ installed: installed.filter((p) => p.isPlugin).map((p) => ({
97
+ name: p.name,
98
+ version: p.version,
99
+ description: p.description || '',
100
+ category: marketCategories[p.name] || classifyPlugin({ name: p.name, description: p.description || '' }).id,
101
+ dirName: p.dirName,
102
+ isBundle: p.isBundle,
103
+ hasClient: p.hasClient,
104
+ hasPatch: p.hasPatch,
105
+ size: p.size,
106
+ })),
107
+ market: (() => {
108
+ const hit = installed.find((p) => p.name === 'dshmarket' || p.name === '@dsh-market/client')
109
+ return { installed: Boolean(hit), name: hit ? hit.name : 'dshmarket', version: hit ? hit.version : '' }
110
+ })(),
111
+ bundled: bundles,
112
+ config,
113
+ defaults: DEFAULT_CONFIG,
114
+ history: readHistory().slice(-12).reverse(),
115
+ }
116
+ }
117
+
118
+ function trusted(req) {
119
+ const host = String(req.headers?.host ?? '').toLowerCase()
120
+ const h = host.startsWith('[') ? host.slice(0, host.indexOf(']') + 1) : host.split(':')[0]
121
+ if (h === '127.0.0.1' || h === 'localhost' || h === '[::1]' || h === '::1') return true
122
+ try {
123
+ const conn = ctx.get('connection')
124
+ if (conn && typeof conn.isTrusted === 'function') return conn.isTrusted(req) === true
125
+ } catch {}
126
+ return false
127
+ }
128
+
129
+ function fenced(req, res) {
130
+ if (!trusted(req)) { json(res, 403, { ok: false, error: '不受信任的访问来源' }); return true }
131
+ try {
132
+ const conn = ctx.get('connection')
133
+ if (conn && typeof conn.requestRejection === 'function') {
134
+ const code = conn.requestRejection(req)
135
+ if (code !== undefined && code !== null && code !== false) {
136
+ res.statusCode = typeof code === 'number' ? code : 403
137
+ res.end()
138
+ return true
139
+ }
140
+ }
141
+ } catch {}
142
+ return false
143
+ }
144
+
145
+ function route(pathname, handler) {
146
+ disposers.push(ctx.webServer.register({
147
+ kind: 'exact',
148
+ path: pathname,
149
+ handler: async (req, res) => {
150
+ if (fenced(req, res)) return
151
+ try {
152
+ await handler(req, res)
153
+ } catch (error) {
154
+ const code = error && error.statusCode ? error.statusCode : 500
155
+ try { json(res, code, { ok: false, error: String((error && error.message) || error) }) } catch {}
156
+ }
157
+ },
158
+ }))
159
+ }
160
+
161
+ const needPost = (req, res) => {
162
+ if (req.method === 'POST') return true
163
+ json(res, 405, { ok: false, error: '只接受 POST' })
164
+ return false
165
+ }
166
+
167
+ function pendingBytes() {
168
+ let total = 0
169
+ for (const item of pending.values()) total += item.buffer ? item.buffer.length : 0
170
+ return total
171
+ }
172
+
173
+ function rememberPending(fileName, payload) {
174
+ const size = payload && payload.buffer ? payload.buffer.length : 0
175
+ // 按条数与总字节双重淘汰:4 个 256MB 的包不该常驻 1GB
176
+ while (pending.size > 0 && (pending.size >= PENDING_MAX || pendingBytes() + size > PENDING_BYTES)) {
177
+ const oldest = [...pending.entries()].sort((a, b) => a[1].at - b[1].at)[0]
178
+ pending.delete(oldest[0])
179
+ }
180
+ const token = randomBytes(12).toString('hex')
181
+ pending.set(token, { at: Date.now(), fileName, ...payload })
182
+ return token
183
+ }
184
+
185
+ function sweeper() {
186
+ const now = Date.now()
187
+ for (const [token, item] of pending) if (now - item.at > PENDING_TTL) pending.delete(token)
188
+ }
189
+
190
+ const installedOrEmpty = () => {
191
+ try { return listInstalled(profileDir()) } catch { return [] }
192
+ }
193
+
194
+ const compatFor = (manifest) => checkCompatibility(manifest.plugins, {
195
+ installed: installedOrEmpty(),
196
+ dshVersion: (() => { try { return dshVersion(profileDir()) } catch { return '' } })(),
197
+ nodeVersion: process.versions.node,
198
+ config,
199
+ })
200
+
201
+ // —— 概览 ——
202
+ route('/dsh-modpack-kit/api/status', async (req, res) => {
203
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
204
+ json(res, 200, snapshot())
205
+ })
206
+
207
+ // —— 设置 ——
208
+ route('/dsh-modpack-kit/api/settings', async (req, res) => {
209
+ if (req.method === 'GET') { json(res, 200, { ok: true, config, defaults: DEFAULT_CONFIG }); return }
210
+ if (!needPost(req, res)) return
211
+ const body = asJson(await readBody(req), null)
212
+ if (!body || typeof body !== 'object') { json(res, 400, { ok: false, error: '请求体不是对象' }); return }
213
+ const patch = body.patch && typeof body.patch === 'object' ? body.patch : body
214
+ const next = { ...config }
215
+ for (const key of Object.keys(DEFAULT_CONFIG)) {
216
+ if (Object.prototype.hasOwnProperty.call(patch, key)) next[key] = patch[key]
217
+ }
218
+ // 三处显示位全关 = 插件没有入口了,拦掉
219
+ if (next.showInSettings === false && next.showInSidebar === false && next.showInPluginsTab === false) {
220
+ json(res, 400, { ok: false, error: '三处显示至少留一处,否则就没有入口能关回来了' })
221
+ return
222
+ }
223
+ config = saveConfig(next)
224
+ json(res, 200, { ok: true, config })
225
+ })
226
+
227
+ // —— 插件目录:分类、词条、分页搜索都照插件市场的来 ——
228
+ // 首屏只要「已装 + 分类」,不再整份目录下发;搜索走服务端分页,一次一页。
229
+ route('/dsh-modpack-kit/api/catalog', async (req, res) => {
230
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
231
+ const installedList = installedOrEmpty().filter((p) => p.isPlugin).map((p) => ({
232
+ name: p.name, version: p.version, isBundle: p.isBundle, hasClient: p.hasClient, description: p.description || '',
233
+ }))
234
+ let catalog = null
235
+ try { catalog = catalogSummary(config) } catch (e) { catalog = { present: false, error: String((e && e.message) || e) } }
236
+ json(res, 200, { ok: true, catalog, installed: installedList, categories: catalog ? catalog.categories : [] })
237
+ })
238
+
239
+ route('/dsh-modpack-kit/api/catalog/status', async (req, res) => {
240
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
241
+ try {
242
+ const summary = catalogSummary(config)
243
+ // 没有或者过期了就在后台自己去补,不让页面等
244
+ if (!summary.present || summary.stale) ensureCatalog(false)
245
+ json(res, 200, { ok: true, ...summary, pageSize: config.catalogPageSize, refreshHours: config.catalogRefreshHours })
246
+ } catch (e) {
247
+ json(res, 500, { ok: false, error: String((e && e.message) || e) })
248
+ }
249
+ })
250
+
251
+ route('/dsh-modpack-kit/api/catalog/lookup', async (req, res) => {
252
+ if (!needPost(req, res)) return
253
+ const body = asJson(await readBody(req), {}) || {}
254
+ const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string').slice(0, 400) : []
255
+ try {
256
+ json(res, 200, { ok: true, items: lookupPlugins(config, names) })
257
+ } catch (e) {
258
+ json(res, 200, { ok: false, error: String((e && e.message) || e), items: {} })
259
+ }
260
+ })
261
+
262
+ route('/dsh-modpack-kit/api/catalog/sync', async (req, res) => {
263
+ if (!needPost(req, res)) return
264
+ const body = asJson(await readBody(req), {}) || {}
265
+ const hours = Math.max(1, Number(config.catalogRefreshHours) || 24)
266
+ const result = await syncCatalog(config, { force: body.force === true, maxAgeMs: hours * 3600 * 1000 })
267
+ if (result.ok && !result.skipped) appendLog(`目录同步 ${result.count} 条(${result.source},${Math.round((result.ms || 0) / 100) / 10}s)`)
268
+ json(res, result.ok ? 200 : 502, { ...result, catalog: (() => { try { return catalogSummary(config) } catch { return null } })() })
269
+ })
270
+
271
+ route('/dsh-modpack-kit/api/catalog/search', async (req, res) => {
272
+ if (!needPost(req, res)) return
273
+ const body = asJson(await readBody(req), {}) || {}
274
+ const localPlugins = installedOrEmpty().filter((p) => p.isPlugin)
275
+ const localCategories = categoryMapFor(config, localPlugins.map((p) => p.name))
276
+ const installed = localPlugins.map((p) => ({
277
+ name: p.name, version: p.version, description: p.description || '',
278
+ // 和市场侧统一用同一套 23 类,否则按 theme/memory 筛时本机独有的插件会被漏掉
279
+ category: localCategories[p.name] || classifyPlugin({ name: p.name, description: p.description || '' }).id,
280
+ }))
281
+ try {
282
+ json(res, 200, searchCatalog(config, {
283
+ query: body.query,
284
+ category: body.category,
285
+ page: body.page,
286
+ pageSize: body.pageSize,
287
+ sort: body.sort,
288
+ installed,
289
+ }))
290
+ } catch (e) {
291
+ json(res, 500, { ok: false, error: String((e && e.message) || e), items: [] })
292
+ }
293
+ })
294
+
295
+
296
+ // —— 查某个包的可用版本 ——
297
+ route('/dsh-modpack-kit/api/versions', async (req, res) => {
298
+ if (!needPost(req, res)) return
299
+ const body = asJson(await readBody(req), {})
300
+ const name = String(body.name || '')
301
+ try {
302
+ const { meta, registry } = await npmMetadata(name, config)
303
+ const versions = Object.keys((meta && meta.versions) || {})
304
+ .map((v) => ({ version: v, time: (meta.time && meta.time[v]) || '', deprecated: Boolean(meta.versions[v] && meta.versions[v].deprecated) }))
305
+ .reverse()
306
+ json(res, 200, { ok: true, name, registry, versions: versions.slice(0, 60), relative: relativeTime })
307
+ } catch (e) {
308
+ json(res, 200, { ok: false, error: String((e && e.message) || e) })
309
+ }
310
+ })
311
+
312
+ // —— 打包 ——
313
+ route('/dsh-modpack-kit/api/pack', async (req, res) => {
314
+ if (!needPost(req, res)) return
315
+ const body = asJson(await readBody(req), {})
316
+ const selection = Array.isArray(body.selection) ? body.selection : []
317
+ if (selection.length === 0) { json(res, 400, { ok: false, error: '没有选择任何插件' }); return }
318
+ const options = body.options && typeof body.options === 'object' ? body.options : {}
319
+ const dir = profileDir()
320
+ const installed = installedOrEmpty()
321
+ try {
322
+ const result = await buildPack({
323
+ selection: selection.map((item) => ({
324
+ name: String(item.name || ''),
325
+ source: item.source === 'npm' ? 'npm' : 'profile',
326
+ spec: item.spec ? String(item.spec) : '',
327
+ mode: item.mode === 'local' ? 'local' : item.mode === 'base' ? 'base' : undefined,
328
+ download: (spec) => downloadPackage(String(item.name || ''), spec || item.spec || '', config),
329
+ })),
330
+ options: {
331
+ includePayload: options.includePayload !== false,
332
+ includeConfig: options.includeConfig !== false,
333
+ includeLocalEdits: options.includeLocalEdits === true,
334
+ confirmLicense: options.confirmLicense === true,
335
+ force: options.force === true,
336
+ keepLocal: options.keepLocal !== false,
337
+ // 扫描是强制的,客户端传什么都不认
338
+ scanBeforePack: true,
339
+ name: String(options.name || 'DSH 整合包'),
340
+ description: String(options.description || ''),
341
+ author: String(options.author || ''),
342
+ license: String(options.license || ''),
343
+ homepage: String(options.homepage || ''),
344
+ extensions: options.extensions && typeof options.extensions === 'object' ? options.extensions : {},
345
+ },
346
+ context: {
347
+ config,
348
+ profileDir: dir,
349
+ dshVersion: (() => { try { return dshVersion(dir) } catch { return '' } })(),
350
+ installed,
351
+ pluginVersion: VERSION,
352
+ extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
353
+ parsePatch: parseYaml,
354
+ patchText: readPatch(dir),
355
+ },
356
+ })
357
+ const token = rememberPending(result.fileName, { buffer: result.buffer, manifest: result.manifest, report: result.report, scan: result.scan })
358
+ appendHistory({ at: new Date().toISOString(), kind: 'pack', name: result.manifest.name, format: result.manifest.format, plugins: result.manifest.plugins.map((p) => p.name + '@' + p.version), size: result.size, high: result.scan.counts.high }, config.historyLimit)
359
+ json(res, 200, {
360
+ ok: true,
361
+ token,
362
+ fileName: result.fileName,
363
+ size: result.size,
364
+ manifest: result.manifest,
365
+ scan: result.scan,
366
+ report: result.report,
367
+ notes: result.notes,
368
+ compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: (() => { try { return dshVersion(dir) } catch { return '' } })(), nodeVersion: process.versions.node, config }),
369
+ })
370
+ } catch (error) {
371
+ if (error instanceof PackRefused) {
372
+ json(res, 200, { ok: false, refused: true, error: error.message, scan: error.scan })
373
+ return
374
+ }
375
+ json(res, 200, { ok: false, error: String((error && error.message) || error) })
376
+ }
377
+ })
378
+
379
+ // —— 下载 / 落盘 ——
380
+ route('/dsh-modpack-kit/api/download', async (req, res) => {
381
+ if (!needPost(req, res)) return
382
+ const body = asJson(await readBody(req), {})
383
+ const item = pending.get(String(body.token || ''))
384
+ if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
385
+ const safeName = String(body.fileName || item.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
386
+ res.writeHead(200, {
387
+ 'Content-Type': 'application/octet-stream',
388
+ 'Content-Disposition': 'attachment; filename="' + safeName + '"',
389
+ 'Content-Length': item.buffer.length,
390
+ 'Cache-Control': 'no-store',
391
+ })
392
+ res.end(item.buffer)
393
+ })
394
+
395
+ route('/dsh-modpack-kit/api/save', async (req, res) => {
396
+ if (!needPost(req, res)) return
397
+ const body = asJson(await readBody(req), {})
398
+ const item = pending.get(String(body.token || ''))
399
+ if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
400
+ const paths = pathsFor(config)
401
+ ensureDir(paths.packs)
402
+ const fileName = slugify(body.fileName || item.fileName.replace(/\.dshpack$/u, ''), 'pack') + '.dshpack'
403
+ const target = path.join(paths.packs, fileName)
404
+ fs.writeFileSync(target, item.buffer)
405
+ pending.delete(String(body.token || ''))
406
+ json(res, 200, { ok: true, path: target, size: item.buffer.length })
407
+ })
408
+
409
+ route('/dsh-modpack-kit/api/packs', async (req, res) => {
410
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
411
+ const dir = pathsFor(config).packs
412
+ const items = []
413
+ try {
414
+ for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
415
+ if (!dirent.isFile() || !dirent.name.endsWith('.dshpack')) continue
416
+ const stat = fs.statSync(path.join(dir, dirent.name))
417
+ items.push({ name: dirent.name, size: stat.size, mtime: stat.mtime.toISOString() })
418
+ }
419
+ } catch {}
420
+ items.sort((a, b) => (a.mtime < b.mtime ? 1 : -1))
421
+ json(res, 200, { ok: true, dir, items })
422
+ })
423
+
424
+ async function inspectInput(body) {
425
+ if (body.url) {
426
+ const buffer = await readPackFromUrl(String(body.url), config, fetchLimited)
427
+ return inspectPackBuffer(buffer, { config, force: body.force === true, scanBeforeInstall: config.scanBeforeInstall !== false, extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
428
+ }
429
+ if (body.token) {
430
+ const item = pending.get(String(body.token))
431
+ if (!item) throw new Error('打包结果已过期,请重新打包')
432
+ return inspectPackBuffer(item.buffer, { config, force: body.force === true, scanBeforeInstall: config.scanBeforeInstall !== false, extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
433
+ }
434
+ if (body.file) {
435
+ const target = path.isAbsolute(String(body.file)) ? String(body.file) : path.join(pathsFor(config).packs, path.basename(String(body.file)))
436
+ if (!target.endsWith('.dshpack')) throw new Error('只读取 .dshpack 文件')
437
+ return inspectPackBuffer(fs.readFileSync(target), { config, force: body.force === true, scanBeforeInstall: config.scanBeforeInstall !== false, extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
438
+ }
439
+ throw new Error('需要 url、token 或 file 之一')
440
+ }
441
+
442
+ // —— 预览 ——
443
+ route('/dsh-modpack-kit/api/inspect', async (req, res) => {
444
+ if (!needPost(req, res)) return
445
+ const body = asJson(await readBody(req), {})
446
+ try {
447
+ const inspected = await inspectInput(body)
448
+ const compat = compatFor(inspected.manifest)
449
+ json(res, 200, {
450
+ ok: true,
451
+ manifest: inspected.manifest,
452
+ integrity: inspected.integrity,
453
+ scan: inspected.scan,
454
+ report: inspected.report,
455
+ blockingReasons: inspected.blockingReasons,
456
+ notes: inspected.notes,
457
+ compat,
458
+ readme: buildReadme(inspected.manifest),
459
+ })
460
+ } catch (error) {
461
+ json(res, 200, { ok: false, error: String((error && error.message) || error) })
462
+ }
463
+ })
464
+
465
+ // —— 安装 ——
466
+ route('/dsh-modpack-kit/api/install', async (req, res) => {
467
+ if (!needPost(req, res)) return
468
+ const body = asJson(await readBody(req), {})
469
+ const options = {
470
+ force: body.force === true,
471
+ keepLocal: body.keepLocal !== false,
472
+ applyConfig: body.applyConfig !== false,
473
+ dryRun: body.dryRun === true,
474
+ // 是否登记 bundle:请求里给了就听请求的,没给就听设置里的 enableOnInstall(默认关)。
475
+ enableBundles: typeof body.enableBundles === 'boolean' ? body.enableBundles : config.enableOnInstall === true,
476
+ }
477
+ try {
478
+ const inspected = await inspectInput(body)
479
+ if (inspected.blockingReasons.length > 0 && !options.force) {
480
+ const refused = new InstallRefused(inspected.blockingReasons.join(';'), inspected.scan)
481
+ json(res, 200, { ok: false, refused: true, error: refused.message, integrity: inspected.integrity, scan: inspected.scan, report: inspected.report })
482
+ return
483
+ }
484
+ const result = await installPack({
485
+ manifest: inspected.manifest,
486
+ entries: inspected.entries,
487
+ config,
488
+ options,
489
+ context: {
490
+ profileDir: profileDir(),
491
+ resolveSource: async (plugin, packRoot) => {
492
+ const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
493
+ const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
494
+ ensureDir(target)
495
+ for (const entry of downloaded.entries) {
496
+ const dest = path.join(target, entry.name)
497
+ if (!path.resolve(dest).startsWith(path.resolve(target) + path.sep)) continue
498
+ ensureDir(path.dirname(dest))
499
+ fs.writeFileSync(dest, entry.data)
500
+ }
501
+ appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry)
502
+ return target
503
+ },
504
+ },
505
+ })
506
+ appendHistory({ at: new Date().toISOString(), kind: 'install', name: inspected.manifest.name, format: inspected.manifest.format, ok: result.ok, pack: inspected.manifest.name, actions: result.actions.length }, config.historyLimit)
507
+ json(res, 200, { ok: result.ok, ...result, manifest: inspected.manifest, scan: inspected.scan, report: inspected.report, integrity: inspected.integrity })
508
+ } catch (error) {
509
+ json(res, 200, { ok: false, error: String((error && error.message) || error) })
510
+ }
511
+ })
512
+
513
+ // —— 历史 ——
514
+ route('/dsh-modpack-kit/api/history', async (req, res) => {
515
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
516
+ json(res, 200, { ok: true, items: readHistory().slice().reverse() })
517
+ })
518
+
519
+ route('/dsh-modpack-kit/api/plugin-summary', async (req, res) => {
520
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
521
+ const installed = installedOrEmpty()
522
+ json(res, 200, { ok: true, items: installed.map((p) => ({ name: p.name, version: p.version, size: p.size, isBundle: p.isBundle, hasClient: p.hasClient })) })
523
+ })
524
+
525
+ // —— 目录:启动后自己补一次(不阻塞启动);太旧了在问状态时补一次 ——
526
+ let catalogJob = null
527
+ let lastAutoTry = 0
528
+ const ensureCatalog = (force) => {
529
+ if (catalogJob) return catalogJob
530
+ // 自动尝试十分钟内只来一次,避免没网时每个请求都去敲一遍
531
+ if (force !== true && Date.now() - lastAutoTry < 10 * 60 * 1000) return Promise.resolve({ ok: false, skipped: true })
532
+ if (force !== true) lastAutoTry = Date.now()
533
+ const hours = Math.max(1, Number(config.catalogRefreshHours) || 24)
534
+ catalogJob = syncCatalog(config, { force: force === true, maxAgeMs: hours * 3600 * 1000 })
535
+ .then((result) => {
536
+ if (result && result.ok && !result.skipped) {
537
+ appendLog(`目录自动更新 ${result.count} 条(${result.source},${Math.round((result.ms || 0) / 100) / 10}s)`)
538
+ } else if (result && !result.ok) {
539
+ log('catalog sync failed:', result.error)
540
+ }
541
+ return result
542
+ })
543
+ .catch((error) => {
544
+ log('catalog sync failed:', String((error && error.message) || error))
545
+ return { ok: false, error: String((error && error.message) || error) }
546
+ })
547
+ .finally(() => { catalogJob = null })
548
+ return catalogJob
549
+ }
550
+
551
+ log('routes ready')
552
+ // 起来就把目录补一次;没有网也不影响其它功能,失败只写日志
553
+ if (process.env.DSH_MODPACK_OFFLINE !== '1') ensureCatalog(false).catch(() => {})
554
+ ctx.effect(() => {
555
+ const timer = setInterval(sweeper, 60 * 1000)
556
+ if (typeof timer.unref === 'function') timer.unref()
557
+ return () => {
558
+ clearInterval(timer)
559
+ pending.clear()
560
+ for (const dispose of disposers) { try { dispose() } catch {} }
561
+ }
562
+ }, 'dsh-modpack-kit:routes')
563
+ },
564
+ }
565
+
566
+ export { pluginSummary }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * 分类:插件市场有分区,本插件照同一套分类给「本机已装」和「市场目录」打标签,
3
+ * 让两边在同一张列表里能按类筛。纯字符串匹配,无网络、无副作用。
4
+ *
5
+ * 想加分类:往 CATEGORIES 加一条,再把关键词塞进 RULES;客户端 client.js 顶部的
6
+ * CATEGORY_LABELS 只用来显示名字,两边 id 必须一致。
7
+ *
8
+ * 匹配规则(2026-11-15 修):英文词按词边界匹配,避免 'ai' 命中 'detail'、'ui' 命中
9
+ * 'build' 这类误判;中文词直接子串匹配。市场数据里带了 category/分区字段时优先采信。
10
+ */
11
+
12
+ export const CATEGORIES = [
13
+ { id: 'ui', label: '界面与外观' },
14
+ { id: 'tool', label: '效率与工具' },
15
+ { id: 'ai', label: 'AI 与模型' },
16
+ { id: 'dev', label: '开发与调试' },
17
+ { id: 'media', label: '媒体与内容' },
18
+ { id: 'net', label: '网络与数据' },
19
+ { id: 'pack', label: '打包与分发' },
20
+ { id: 'other', label: '其它' },
21
+ ]
22
+
23
+ const RULES = [
24
+ { id: 'pack', words: ['modpack', 'installer', '插件市场', 'plugin market', 'marketplace', 'catalog', '整合包', '打包', '安装器'] },
25
+ { id: 'ui', words: ['ui', 'theme', 'themes', 'skin', 'wallpaper', 'icon', 'sidebar', 'panel', 'layout', 'font', 'mascot', 'widget', '界面', '外观', '主题', '图标', '侧栏', '面板', '字体', '配色', '壁纸', '桌宠', '桌面', '挂件', 'locale', 'i18n', '语言'] },
26
+ { id: 'ai', words: ['llm', 'model', 'gpt', 'claude', 'prompt', 'embedding', 'agent skills', 'skill deck', '技能', '技能包', '模型', '智能体', '推理', '记忆', '上下文'] },
27
+ { id: 'dev', words: ['dev', 'debug', 'log', 'logs', 'lint', 'test', 'tests', 'code', 'git', 'trace', 'profiler', 'sandbox', '调试', '开发', '日志', '测试', '代码', '编译', '性能', '检查'] },
28
+ { id: 'media', words: ['image', 'images', 'video', 'music', 'audio', 'media', 'bili', 'bilibili', 'subtitle', 'danmaku', 'screenshot', '图片', '视频', '音乐', '音频', '媒体', '字幕', '弹幕', '截图', 'B站'] },
29
+ { id: 'net', words: ['http', 'api', 'proxy', 'sync', 'storage', 'database', 'webhook', 'sse', 'socket', 'websocket', 'mcp', 'network', '网络', '代理', '同步', '存储', '数据库', '连接'] },
30
+ { id: 'tool', words: ['tool', 'tools', 'command', 'search', 'todo', 'note', 'notes', 'schedule', 'clipboard', 'calculator', 'shortcut', '工具', '效率', '快捷', '命令', '搜索', '待办', '笔记', '日程', '剪贴板', '计算'] },
31
+ ]
32
+
33
+ const ALIASES = {
34
+ ui: 'ui', theme: 'ui', themes: 'ui', appearance: 'ui', style: 'ui', wallpaper: 'ui',
35
+ tool: 'tool', tools: 'tool', utility: 'tool', utilities: 'tool', productivity: 'tool', efficiency: 'tool',
36
+ ai: 'ai', ai_agent: 'ai', model: 'ai', models: 'ai', llm: 'ai', agent: 'ai', memory: 'ai', context: 'ai',
37
+ dev: 'dev', developer: 'dev', development: 'dev', debug: 'dev', devtools: 'dev', testing: 'dev',
38
+ media: 'media', content: 'media', image: 'media', images: 'media', video: 'media', audio: 'media',
39
+ net: 'net', network: 'net', networking: 'net', data: 'net', sync: 'net', storage: 'net', api: 'net',
40
+ pack: 'pack', bundle: 'pack', bundles: 'pack', modpack: 'pack', market: 'pack', install: 'pack', distribution: 'pack',
41
+ other: 'other', misc: 'other',
42
+ }
43
+
44
+ // 同分时的偏好:越具体的主题越优先,避免 'agent' 这类泛词把什么都吃成 AI
45
+ const TIE_PRIORITY = { media: 7, dev: 6, ui: 5, net: 4, tool: 3, ai: 2, pack: 1, other: 0 }
46
+
47
+ const ASCII_WORD = /^[\x20-\x7e]+$/
48
+ const escapeRe = (w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
49
+
50
+ /** 英文按词边界(允许复数 s/es),中文按子串 */
51
+ function hit(hay, word) {
52
+ const w = String(word || '').toLowerCase()
53
+ if (!w) return false
54
+ if (!ASCII_WORD.test(w)) return hay.includes(w)
55
+ const pattern = w.length <= 2
56
+ ? `(^|[^a-z0-9])${escapeRe(w)}([^a-z0-9]|$)`
57
+ : `(^|[^a-z0-9])${escapeRe(w)}(s|es)?([^a-z0-9]|$)`
58
+ return new RegExp(pattern, 'i').test(hay)
59
+ }
60
+
61
+ const asList = (value) => (Array.isArray(value) ? value.map((x) => String(x).toLowerCase()) : [])
62
+
63
+ /**
64
+ * @param {{name?: string, title?: string, description?: string, tags?: string[], category?: string}} meta
65
+ * @returns {{id: string, label: string, reason: string}}
66
+ */
67
+ export function classifyPlugin(meta) {
68
+ const name = String(meta?.name || '').toLowerCase()
69
+ const title = String(meta?.title || '').toLowerCase()
70
+ const rest = [String(meta?.description || '').toLowerCase(), ...asList(meta?.tags), String(meta?.category || '').toLowerCase()].join(' ')
71
+
72
+ let best = null
73
+ for (const rule of RULES) {
74
+ // 每个字段只计一次,避免 'tool' 与 'tools' 同时命中把分数翻倍
75
+ let score = 0
76
+ const hits = []
77
+ for (const [field, weight] of [[name, 5], [title, 3], [rest, 1]]) {
78
+ const matched = rule.words.filter((word) => hit(field, word))
79
+ if (!matched.length) continue
80
+ matched.sort((a, b) => b.length - a.length)
81
+ hits.push(...matched)
82
+ score += weight
83
+ }
84
+ const better = !best
85
+ || score > best.score
86
+ || (score === best.score && hits.length > best.hits.length)
87
+ || (score === best.score && hits.length === best.hits.length && (TIE_PRIORITY[rule.id] || 0) > (TIE_PRIORITY[best.id] || 0))
88
+ if (score > 0 && better) best = { id: rule.id, score, hits }
89
+ }
90
+
91
+ // 市场数据里明确给了分区:优先采信,但仍要求上面没有更硬的证据(名字命中)
92
+ const byAlias = ALIASES[String(meta?.category || '').toLowerCase().trim()]
93
+ if (byAlias && (!best || best.score < 5)) {
94
+ const label = (CATEGORIES.find((c) => c.id === byAlias) || { label: '其它' }).label
95
+ return { id: byAlias, label, reason: '市场分区:' + meta.category }
96
+ }
97
+
98
+ if (!best) return { id: 'other', label: '其它', reason: '没有命中分类关键词' }
99
+ const label = (CATEGORIES.find((c) => c.id === best.id) || { label: '其它' }).label
100
+ return { id: best.id, label, reason: '命中:' + best.hits.slice(0, 3).join('、') }
101
+ }
102
+
103
+ export function categoryLabel(id) {
104
+ return (CATEGORIES.find((c) => c.id === id) || { label: '其它' }).label
105
+ }