dsh-modpack-kit 0.1.8 → 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/index.js CHANGED
@@ -7,19 +7,20 @@
7
7
  import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import { randomBytes } from 'node:crypto'
10
- import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
10
+ import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, clearHistory, removeHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
11
11
  import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
12
- import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime } from './lib/registry.mjs'
12
+ import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime, probeRegistry } from './lib/registry.mjs'
13
13
  import { buildPack, PackRefused } from './lib/pack.mjs'
14
14
  import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
15
15
  import { checkCompatibility } from './lib/compat.mjs'
16
+ import { readMarketGroups, groupViews } from './lib/groups.mjs'
16
17
  import { classifyPlugin } from './lib/classify.mjs'
17
18
  import { groupFindings } from './lib/scan.mjs'
18
19
  import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
19
20
  import { parseYaml } from './lib/yamlish.mjs'
20
21
  import { readPatch } from './lib/profile.mjs'
21
22
  import { buildReadme } from './lib/manifest.mjs'
22
- import { sendJson as json, readBody, readRawBody, asJson, MAX_JSON_BODY, MAX_DROP_BODY } from './lib/http.mjs'
23
+ import { sendJson as json, readBody, readRawBody, readJsonBody, MAX_JSON_BODY, MAX_DROP_BODY } from './lib/http.mjs'
23
24
 
24
25
  const VERSION = (() => {
25
26
  try { return JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version || '0.0.0' } catch { return '0.0.0' }
@@ -58,6 +59,20 @@ export default {
58
59
  // 词条分类以插件市场为准;市场目录里没有的(本机私有插件)才退回本地猜测
59
60
  let marketCategories = {}
60
61
  try { marketCategories = categoryMapFor(config, installed.map((p) => p.name)) } catch {}
62
+ // 只列 profile 直接声明的插件;插件自带的内部子包由父包带进来,单独列出会被重复打包
63
+ const direct = installed.filter((p) => p.isPlugin && p.isDirect)
64
+ // 插件市场的分组(只读人家 profile 下的 state.json):整理信息,不决定启用状态
65
+ let groups = []
66
+ let ungrouped = direct.map((p) => p.name)
67
+ let groupSource = 'none'
68
+ try {
69
+ const market = readMarketGroups(dir)
70
+ const views = groupViews(direct, market)
71
+ // 分组只用来整理与批量勾选,不再在组头算兼容:装之前的兼容检查有单独的列表
72
+ groups = views.groups.map((group) => ({ name: group.name, members: group.members, missing: group.missing }))
73
+ ungrouped = views.ungrouped
74
+ groupSource = market.present ? 'market' : 'none'
75
+ } catch {}
61
76
  return {
62
77
  ok: !error,
63
78
  error,
@@ -81,7 +96,7 @@ export default {
81
96
  installedOrphans: installed.filter((p) => !p.isDirect && p.isOrphan).length,
82
97
  // 只列 profile 直接声明的插件;插件自带的内部子包(如壁纸引擎的 fonts/fx/glass…)由父包带进来,
83
98
  // 单独列出来会被重复打包、重复安装。
84
- installed: installed.filter((p) => p.isPlugin && p.isDirect).map((p) => ({
99
+ installed: direct.map((p) => ({
85
100
  name: p.name,
86
101
  version: p.version,
87
102
  description: p.description || '',
@@ -92,6 +107,10 @@ export default {
92
107
  hasPatch: p.hasPatch,
93
108
  size: p.size,
94
109
  })),
110
+ // 插件市场的分组:只是「哪些插件一起看」的整理信息,默认勾选逻辑完全不变
111
+ groups,
112
+ ungrouped,
113
+ groupSource,
95
114
  market: (() => {
96
115
  const hit = installed.find((p) => p.name === 'dshmarket' || p.name === '@dsh-market/client')
97
116
  return { installed: Boolean(hit), name: hit ? hit.name : 'dshmarket', version: hit ? hit.version : '' }
@@ -179,6 +198,73 @@ export default {
179
198
  try { return listInstalled(profileDir()) } catch { return [] }
180
199
  }
181
200
 
201
+ // 三种策略能不能选:按「这次勾了哪些插件」实时算,客户端拿去做卡片灰显与原因弹窗;
202
+ // 打包时也再算一遍,挡住「界面上换了插件、策略却没跟着变」的情况。
203
+ const computePlan = (selection) => {
204
+ const installed = installedOrEmpty()
205
+ // spec 可能是 名字@版本,也可能是纯版本;统一抠出版本号再判能不能按版本装
206
+ const versionOf = (item, entry) => {
207
+ const spec = String(item.spec || '')
208
+ const fromSpec = spec.includes('@') && !spec.startsWith('@') ? spec.slice(spec.lastIndexOf('@') + 1) : spec
209
+ const candidates = [item.version, fromSpec, entry && entry.version]
210
+ for (const value of candidates) {
211
+ const text = String(value || '')
212
+ if (/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(text) && text !== '0.0.0') return text
213
+ }
214
+ return ''
215
+ }
216
+ const rows = selection.map((item) => {
217
+ const name = String(item.name || '')
218
+ const entry = installed.find((p) => p.name === name)
219
+ const version = versionOf(item, entry)
220
+ const local = Boolean(entry)
221
+ const market = item.source === 'npm' || item.source === 'market'
222
+ const custom = item.choice === 'custom'
223
+ return { name, version, semver: Boolean(version), local, market, custom }
224
+ })
225
+ const noCode = rows.filter((r) => !r.local && r.market)
226
+ const noVersion = rows.filter((r) => !r.semver)
227
+ const customRows = rows.filter((r) => r.custom)
228
+ const names = (list) => list.slice(0, 6).map((r) => r.name).join('、') + (list.length > 6 ? ' 等 ' + list.length + ' 个' : '')
229
+ const liteBlockers = []
230
+ if (noVersion.length) liteBlockers.push({ kind: 'version', text: '这些插件没有确定的版本号,安装时找不到对应的包:' + names(noVersion) })
231
+ if (customRows.length) liteBlockers.push({ kind: 'config', text: '给这些插件选了「自定义配置」,轻量包只记版本、带不走配置与数据:' + names(customRows) + '(改回「插件预设」,或换完整包 / 混合包)' })
232
+ const hybridBlockers = []
233
+ const noCodeNoVersion = noVersion.filter((r) => !r.local)
234
+ if (noCodeNoVersion.length) hybridBlockers.push({ kind: 'version', text: '这些插件没有确定的版本号,本机又没装、取不到代码:' + names(noCodeNoVersion) })
235
+ const strategies = [
236
+ {
237
+ id: 'full',
238
+ title: '完整包(懒人包)',
239
+ online: false,
240
+ ok: true,
241
+ reason: '',
242
+ blockers: [],
243
+ note: '插件本体一起装进包,不联网也能装;有网时优先按市场版本装(profile 依赖是 ^版本,插件市场认成市场版),离线才退回包内副本、显示本地安装。允许带自定义配置与数据。',
244
+ },
245
+ {
246
+ id: 'lite',
247
+ title: '仅下载码(轻量包)',
248
+ online: true,
249
+ ok: liteBlockers.length === 0,
250
+ reason: liteBlockers.map((b) => b.text).join(';'),
251
+ blockers: liteBlockers,
252
+ note: '只记 名字@版本,体积最小;安装时必须联网从市场取包,不带自定义配置与数据。',
253
+ },
254
+ {
255
+ id: 'hybrid',
256
+ title: '混合包(轻量为主 + 必要的完整)',
257
+ online: true,
258
+ ok: hybridBlockers.length === 0,
259
+ reason: hybridBlockers.map((b) => b.text).join(';'),
260
+ blockers: hybridBlockers,
261
+ note: '能按版本装的就只记 名字@版本(安装时联网取包);没有确定版本、或者要带走本机改动的插件,连代码一起打进来(这部分安装时不用联网)。配置/数据/补丁片段照样带。',
262
+ },
263
+ ]
264
+ if (noCode.length > 0) strategies[0].note += '(其中 ' + names(noCode) + ' 本机没有代码,打包时要联网取一次)'
265
+ return { strategies, plugins: rows, counts: { selected: rows.length, custom: customRows.length, noVersion: noVersion.length, localOnly: rows.filter((r) => r.local).length } }
266
+ }
267
+
182
268
  const compatFor = (manifest) => checkCompatibility(manifest.plugins, {
183
269
  installed: installedOrEmpty(),
184
270
  dshVersion: (() => { try { return dshVersion(profileDir()) } catch { return '' } })(),
@@ -196,7 +282,7 @@ export default {
196
282
  route('/dsh-modpack-kit/api/settings', async (req, res) => {
197
283
  if (req.method === 'GET') { json(res, 200, { ok: true, config, defaults: DEFAULT_CONFIG }); return }
198
284
  if (!needPost(req, res)) return
199
- const body = asJson(await readBody(req), null)
285
+ const body = await readJsonBody(req, null)
200
286
  if (!body || typeof body !== 'object') { json(res, 400, { ok: false, error: '请求体不是对象' }); return }
201
287
  const patch = body.patch && typeof body.patch === 'object' ? body.patch : body
202
288
  const next = { ...config }
@@ -238,7 +324,7 @@ export default {
238
324
 
239
325
  route('/dsh-modpack-kit/api/catalog/lookup', async (req, res) => {
240
326
  if (!needPost(req, res)) return
241
- const body = asJson(await readBody(req), {}) || {}
327
+ const body = await readJsonBody(req)
242
328
  const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string').slice(0, 400) : []
243
329
  try {
244
330
  json(res, 200, { ok: true, items: lookupPlugins(config, names) })
@@ -249,7 +335,7 @@ export default {
249
335
 
250
336
  route('/dsh-modpack-kit/api/catalog/sync', async (req, res) => {
251
337
  if (!needPost(req, res)) return
252
- const body = asJson(await readBody(req), {}) || {}
338
+ const body = await readJsonBody(req)
253
339
  const hours = Math.max(1, Number(config.catalogRefreshHours) || 24)
254
340
  const result = await syncCatalog(config, { force: body.force === true, maxAgeMs: hours * 3600 * 1000 })
255
341
  if (result.ok && !result.skipped) appendLog(`目录同步 ${result.count} 条(${result.source},${Math.round((result.ms || 0) / 100) / 10}s)`)
@@ -258,7 +344,7 @@ export default {
258
344
 
259
345
  route('/dsh-modpack-kit/api/catalog/search', async (req, res) => {
260
346
  if (!needPost(req, res)) return
261
- const body = asJson(await readBody(req), {}) || {}
347
+ const body = await readJsonBody(req)
262
348
  const localPlugins = installedOrEmpty().filter((p) => p.isPlugin && p.isDirect)
263
349
  const localCategories = categoryMapFor(config, localPlugins.map((p) => p.name))
264
350
  const installed = localPlugins.map((p) => ({
@@ -284,10 +370,10 @@ export default {
284
370
  // —— 查某个包的可用版本 ——
285
371
  route('/dsh-modpack-kit/api/versions', async (req, res) => {
286
372
  if (!needPost(req, res)) return
287
- const body = asJson(await readBody(req), {})
373
+ const body = await readJsonBody(req)
288
374
  const name = String(body.name || '')
289
375
  try {
290
- const { meta, registry } = await npmMetadata(name, config)
376
+ const { meta, registry } = await npmMetadata(name, config, { full: true })
291
377
  const versions = Object.keys((meta && meta.versions) || {})
292
378
  .map((v) => ({ version: v, time: (meta.time && meta.time[v]) || '', deprecated: Boolean(meta.versions[v] && meta.versions[v].deprecated) }))
293
379
  .reverse()
@@ -432,10 +518,16 @@ export default {
432
518
  spec: item.spec ? String(item.spec) : (source === 'npm' ? String(item.version || '') : ''),
433
519
  mode: choice === 'custom' ? 'local' : 'base',
434
520
  configMode: choice,
521
+ group: item.group ? String(item.group).slice(0, 40) : '',
435
522
  download: (spec) => downloadPackage(name, spec || item.spec || String(item.version || ''), config),
436
523
  }
437
524
  }),
438
525
  options: {
526
+ strategy: (() => {
527
+ const raw = String(options.strategy || options.format || '').toLowerCase()
528
+ if (raw === 'lite' || raw === 'hybrid' || raw === 'full') return raw
529
+ return options.includePayload === false ? 'lite' : 'full'
530
+ })(),
439
531
  includePayload: options.includePayload !== false,
440
532
  includeConfig: options.includeConfig !== false,
441
533
  includeLocalEdits: options.includeLocalEdits === true,
@@ -577,11 +669,31 @@ export default {
577
669
  return job
578
670
  }
579
671
 
672
+ // 三种打包策略能不能选:客户端据此把卡片画成可点/灰掉,灰掉时给出原因。
673
+ route('/dsh-modpack-kit/api/pack/plan', async (req, res) => {
674
+ if (!needPost(req, res)) return
675
+ {
676
+ const body = await readJsonBody(req)
677
+ const selection = Array.isArray(body.selection) ? body.selection : []
678
+ if (selection.length === 0) return json(res, 400, { ok: false, error: '还没选插件' })
679
+ return json(res, 200, { ok: true, ...computePlan(selection) })
680
+ }
681
+ })
682
+
580
683
  route('/dsh-modpack-kit/api/pack', async (req, res) => {
581
684
  if (!needPost(req, res)) return
582
- const body = asJson(await readBody(req), {})
685
+ const body = await readJsonBody(req)
583
686
  const selection = Array.isArray(body.selection) ? body.selection : []
584
687
  if (selection.length === 0) { json(res, 400, { ok: false, error: '没有选择任何插件' }); return }
688
+ const strategy = String((body.options && body.options.strategy) || 'full')
689
+ if (strategy === 'lite' || strategy === 'hybrid') {
690
+ const plan = computePlan(selection)
691
+ const chosen = plan.strategies.find((entry) => entry.id === strategy)
692
+ if (chosen && chosen.ok === false) {
693
+ json(res, 400, { ok: false, error: '这个打包策略现在不适用:' + chosen.reason, plan })
694
+ return
695
+ }
696
+ }
585
697
  if (body.async === true || body.background === true) {
586
698
  const job = startPackJob(body)
587
699
  json(res, 200, { ok: true, async: true, job: publicJob(job) })
@@ -594,7 +706,7 @@ export default {
594
706
  // 风险停下来之后:只有「我知道在干什么」,点它就在同一个任务里接着跑完
595
707
  route('/dsh-modpack-kit/api/jobs/ack', async (req, res) => {
596
708
  if (!needPost(req, res)) return
597
- const body = asJson(await readBody(req), {})
709
+ const body = await readJsonBody(req)
598
710
  const job = jobs.get(String(body.id || ''))
599
711
  if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
600
712
  if (!job.risk) { json(res, 400, { ok: false, error: '这个任务没有风险项,不需要确认' }); return }
@@ -629,7 +741,7 @@ export default {
629
741
 
630
742
  route('/dsh-modpack-kit/api/jobs/dismiss', async (req, res) => {
631
743
  if (!needPost(req, res)) return
632
- const body = asJson(await readBody(req), {})
744
+ const body = await readJsonBody(req)
633
745
  const id = String(body.id || '')
634
746
  const job = jobs.get(id)
635
747
  if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已经删了)' }); return }
@@ -661,7 +773,7 @@ export default {
661
773
 
662
774
  route('/dsh-modpack-kit/api/jobs/cancel', async (req, res) => {
663
775
  if (!needPost(req, res)) return
664
- const body = asJson(await readBody(req), {})
776
+ const body = await readJsonBody(req)
665
777
  const job = jobs.get(String(body.id || ''))
666
778
  if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
667
779
  if (job.status !== 'running') {
@@ -691,7 +803,7 @@ export default {
691
803
  // —— 下载 / 落盘 ——
692
804
  route('/dsh-modpack-kit/api/download', async (req, res) => {
693
805
  if (!needPost(req, res)) return
694
- const body = asJson(await readBody(req), {})
806
+ const body = await readJsonBody(req)
695
807
  const item = pending.get(String(body.token || ''))
696
808
  if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
697
809
  const safeName = String(body.fileName || item.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
@@ -706,7 +818,7 @@ export default {
706
818
 
707
819
  route('/dsh-modpack-kit/api/save', async (req, res) => {
708
820
  if (!needPost(req, res)) return
709
- const body = asJson(await readBody(req), {})
821
+ const body = await readJsonBody(req)
710
822
  const item = pending.get(String(body.token || ''))
711
823
  if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
712
824
  const paths = pathsFor(config)
@@ -751,7 +863,7 @@ export default {
751
863
  return
752
864
  }
753
865
  if (req.method !== 'POST') { json(res, 405, { ok: false }); return }
754
- const body = asJson(await readBody(req), {})
866
+ const body = await readJsonBody(req)
755
867
  const raw = String(body.dir || '').trim()
756
868
  const dir = raw ? path.resolve(raw) : pathsFor(config).packs
757
869
  const listed = listPacks(dir)
@@ -766,7 +878,7 @@ export default {
766
878
  try {
767
879
  if (contentType.includes('application/json')) {
768
880
  // 有些环境不许 POST 二进制,界面会退回 base64:这里同样收
769
- const body = asJson(await readBody(req, MAX_DROP_BODY), {}) || {}
881
+ const body = await readJsonBody(req, {}, MAX_DROP_BODY)
770
882
  const raw = typeof body.data === 'string' ? body.data : ''
771
883
  if (!raw) { json(res, 400, { ok: false, error: '没有收到整合包内容' }); return }
772
884
  bytes = Buffer.from(raw, 'base64')
@@ -826,7 +938,7 @@ export default {
826
938
  // —— 预览 ——
827
939
  route('/dsh-modpack-kit/api/inspect', async (req, res) => {
828
940
  if (!needPost(req, res)) return
829
- const body = asJson(await readBody(req), {})
941
+ const body = await readJsonBody(req)
830
942
  try {
831
943
  const inspected = await inspectInput(body)
832
944
  const compat = compatFor(inspected.manifest)
@@ -878,6 +990,8 @@ export default {
878
990
  only: Array.isArray(body.only) && body.only.length > 0 ? body.only.map(String) : null,
879
991
  // 联网且有插件市场时优先按市场版本装(默认开;请求里能逐次关掉)
880
992
  preferMarket: typeof body.preferMarket === 'boolean' ? body.preferMarket : config.preferMarketOnInstall !== false,
993
+ // 离线安装:true = 不问 registry 直接用包里自带的;不给 = 由 installPack 先探一下网络决定
994
+ offline: typeof body.offline === 'boolean' ? body.offline : undefined,
881
995
  })
882
996
 
883
997
  const runInstall = async (inspected, body, job) => {
@@ -906,9 +1020,11 @@ export default {
906
1020
  manifest: inspected.manifest,
907
1021
  entries: inspected.entries,
908
1022
  config,
909
- options: { ...options, onProgress: (event) => push(event.pct, event.note) },
1023
+ options: { preferMarketOnInstall: options.preferMarketOnInstall !== false || config.preferMarketOnInstall !== false, ...options, onProgress: (event) => push(event.pct, event.note) },
910
1024
  context: {
911
1025
  profileDir: profileDir(),
1026
+ // 离线判断:registry 探不通就直接用包里自带的,别让每个插件都等超时
1027
+ probeRegistry: () => probeRegistry(config),
912
1028
  // 优先用宿主自带的插件管理器(pnpm、激活、重启判定都由它负责);
913
1029
  // 服务不在或调用抛错时 installPack 会自动退回 dsh 命令行。
914
1030
  installBundle: (() => {
@@ -919,7 +1035,7 @@ export default {
919
1035
  // 联网且市场可用时,优先按市场版本装(能用就返回 name@version,用不了返回 null 走包内)
920
1036
  resolveMarket: async (plugin) => {
921
1037
  try {
922
- const { meta } = await npmMetadata(plugin.name, config)
1038
+ const { meta } = await npmMetadata(plugin.name, config, { version: plugin.version || plugin.spec || '' })
923
1039
  const version = pickVersion(meta, plugin.version || plugin.spec || '') || pickVersion(meta, '')
924
1040
  if (!version) return null
925
1041
  appendLog('market ' + plugin.name + '@' + version + ' 优先于包内 ' + (plugin.version || '(未标版本)'))
@@ -929,6 +1045,12 @@ export default {
929
1045
  return null
930
1046
  }
931
1047
  },
1048
+ // 轻量包:只把条目取回内存(不落临时目录),扫描与安装都在内存里完成
1049
+ resolveSourceEntries: async (plugin) => {
1050
+ const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
1051
+ appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry + ' (memory, ' + downloaded.entries.length + ' files)')
1052
+ return downloaded.entries
1053
+ },
932
1054
  resolveSource: async (plugin, packRoot) => {
933
1055
  const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
934
1056
  const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
@@ -1001,7 +1123,7 @@ export default {
1001
1123
 
1002
1124
  route('/dsh-modpack-kit/api/install', async (req, res) => {
1003
1125
  if (!needPost(req, res)) return
1004
- const body = asJson(await readBody(req), {})
1126
+ const body = await readJsonBody(req)
1005
1127
  if (body.async === true || body.background === true) {
1006
1128
  const job = startInstallJob(body, body.label ? String(body.label) : undefined)
1007
1129
  json(res, 200, { ok: true, async: true, job: publicJob(job) })
@@ -1014,7 +1136,7 @@ export default {
1014
1136
  // 装完的追问:把刚才跳过的那些换成包内版本
1015
1137
  route('/dsh-modpack-kit/api/install/replace', async (req, res) => {
1016
1138
  if (!needPost(req, res)) return
1017
- const body = asJson(await readBody(req), {})
1139
+ const body = await readJsonBody(req)
1018
1140
  const token = String(body.token || '')
1019
1141
  const item = pendingInstalls.get(token)
1020
1142
  if (!item) { json(res, 400, { ok: false, error: '这次安装的上下文已过期,请重新读一遍整合包' }); return }
@@ -1043,6 +1165,21 @@ export default {
1043
1165
  json(res, 200, { ok: true, items: readHistory().slice().reverse() })
1044
1166
  })
1045
1167
 
1168
+ // 清空最近记录(文件留着,只是写空)
1169
+ route('/dsh-modpack-kit/api/history/clear', async (req, res) => {
1170
+ if (!needPost(req, res)) return
1171
+ json(res, 200, { ok: true, items: clearHistory() })
1172
+ })
1173
+
1174
+ // 删掉某一条:按 at 时间戳匹配
1175
+ route('/dsh-modpack-kit/api/history/remove', async (req, res) => {
1176
+ if (!needPost(req, res)) return
1177
+ const body = await readJsonBody(req)
1178
+ const items = removeHistory(body.at)
1179
+ appendLog('history remove ' + String((body && body.at) || '') + ' left=' + items.length)
1180
+ json(res, 200, { ok: true, items })
1181
+ })
1182
+
1046
1183
  route('/dsh-modpack-kit/api/plugin-summary', async (req, res) => {
1047
1184
  if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
1048
1185
  const installed = installedOrEmpty()
package/lib/groups.mjs ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * dsh-modpack —— 读插件市场的分组(只读,不改人家的状态文件)。
3
+ *
4
+ * 插件市场把用户自建的分组存在 profile 下的 `.dsh-market/state.json`
5
+ * (`groups` 名字到成员、`groupOrder` 顺序、`disabled` 停用名单)。分组只是
6
+ * 「哪些插件一起看」的整理信息,不决定启用状态,所以这里也只读不写:
7
+ * 打包时按分组批量勾选,装包时按市场自己的规则走。
8
+ *
9
+ * 市场没装、没建过分组、状态文件坏了,都退回「没有分组」——不让一个可选
10
+ * 的整理功能变成打包的前置条件。
11
+ */
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+
15
+ /** 市场状态文件的固定位置(profile 根下)。 */
16
+ export function marketStatePath(profileDir) {
17
+ return path.join(profileDir, '.dsh-market', 'state.json')
18
+ }
19
+
20
+ function stringList(value) {
21
+ if (!Array.isArray(value)) return []
22
+ const out = []
23
+ for (const item of value) {
24
+ if (typeof item !== 'string' || item === '' || out.includes(item)) continue
25
+ out.push(item)
26
+ }
27
+ return out
28
+ }
29
+
30
+ /**
31
+ * 读市场分组。返回 `{present, order, groups, disabled}`;
32
+ * `groups` 的成员已去重、去掉空串,但不判断装没装(那一步交给 groupViews)。
33
+ */
34
+ export function readMarketGroups(profileDir) {
35
+ const empty = { present: false, order: [], groups: {}, disabled: [] }
36
+ if (typeof profileDir !== 'string' || profileDir === '') return empty
37
+ let raw = null
38
+ try {
39
+ raw = JSON.parse(fs.readFileSync(marketStatePath(profileDir), 'utf8'))
40
+ } catch {
41
+ return empty
42
+ }
43
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return empty
44
+ const groups = {}
45
+ const source = raw.groups !== null && typeof raw.groups === 'object' && !Array.isArray(raw.groups) ? raw.groups : {}
46
+ for (const [name, members] of Object.entries(source)) {
47
+ if (name === '') continue
48
+ groups[name] = stringList(members)
49
+ }
50
+ const order = stringList(raw.groupOrder).filter((name) => groups[name] !== undefined)
51
+ for (const name of Object.keys(groups)) if (!order.includes(name)) order.push(name)
52
+ return { present: true, order, groups, disabled: stringList(raw.disabled) }
53
+ }
54
+
55
+ /**
56
+ * 把本机插件按市场分组的视角切开:分组在前(按市场的顺序),剩下的归
57
+ * 「未分组」。成员里已经卸掉的插件记进 `missing`,不混进列表。
58
+ *
59
+ * @param {object[]} installed listInstalled() 的结果(含 name)
60
+ * @param {{order: string[], groups: Record<string, string[]>}} market readMarketGroups() 的结果
61
+ */
62
+ export function groupViews(installed, market) {
63
+ const names = new Set((installed || []).map((item) => item.name))
64
+ const claimed = new Set()
65
+ const groups = []
66
+ for (const name of (market && market.order) || []) {
67
+ const members = ((market && market.groups && market.groups[name]) || []).filter((member) => names.has(member))
68
+ const missing = ((market && market.groups && market.groups[name]) || []).filter((member) => !names.has(member))
69
+ for (const member of members) claimed.add(member)
70
+ groups.push({ name, members, missing })
71
+ }
72
+ const ungrouped = (installed || []).map((item) => item.name).filter((name) => !claimed.has(name))
73
+ return { groups, ungrouped }
74
+ }
75
+
76
+ /** 目标 profile 里有没有插件市场(市场自己会在 profile 根下建 .dsh-market)。 */
77
+ export function hasMarket(profileDir) {
78
+ if (typeof profileDir !== 'string' || profileDir === '') return false
79
+ try {
80
+ return fs.statSync(path.join(profileDir, '.dsh-market')).isDirectory()
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 把包里的分组并进目标 profile 的市场状态文件:同名组合并成员、新组追加到
88
+ * 末尾,其它键(包括别人的分组、disabled、版本号)原样保留。
89
+ *
90
+ * @param {string} profileDir 目标 profile 目录
91
+ * @param {Record<string, string[]>} additions 组名 → 要并进去的成员
92
+ * @returns {{changed: boolean, summary: string, error?: string}}
93
+ */
94
+ export function applyMarketGroups(profileDir, additions) {
95
+ const file = marketStatePath(profileDir)
96
+ let raw = {}
97
+ try {
98
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'))
99
+ } catch {
100
+ raw = {}
101
+ }
102
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) raw = {}
103
+ const groups = raw.groups !== null && typeof raw.groups === 'object' && !Array.isArray(raw.groups) ? { ...raw.groups } : {}
104
+ const order = stringList(raw.groupOrder)
105
+ const changedParts = []
106
+ for (const [name, members] of Object.entries(additions || {})) {
107
+ if (!name) continue
108
+ const current = stringList(groups[name])
109
+ const merged = [...current]
110
+ let added = 0
111
+ for (const member of stringList(members)) {
112
+ if (merged.includes(member)) continue
113
+ merged.push(member)
114
+ added += 1
115
+ }
116
+ if (added === 0 && groups[name] !== undefined) continue
117
+ groups[name] = merged
118
+ if (!order.includes(name)) order.push(name)
119
+ changedParts.push(name + '(+' + added + ')')
120
+ }
121
+ if (changedParts.length === 0) return { changed: false, summary: '' }
122
+ raw.groups = groups
123
+ raw.groupOrder = order
124
+ try {
125
+ fs.mkdirSync(path.dirname(file), { recursive: true })
126
+ const tmp = file + '.tmp-' + process.pid
127
+ fs.writeFileSync(tmp, JSON.stringify(raw, null, 2) + '\n', 'utf8')
128
+ fs.renameSync(tmp, file)
129
+ } catch (error) {
130
+ return { changed: false, summary: '', error: String((error && error.message) || error) }
131
+ }
132
+ return { changed: true, summary: changedParts.join('、') }
133
+ }
package/lib/http.mjs CHANGED
@@ -33,6 +33,9 @@ export const readBody = (req, limit = MAX_JSON_BODY) => collect(req, limit, '请
33
33
 
34
34
  export const readRawBody = (req, limit = MAX_DROP_BODY) => collect(req, limit, '整合包太大:上限 ' + Math.round(limit / 1024 / 1024) + ' MB')
35
35
 
36
+ // 大部分路由只要一个对象:读不到、不是 JSON、是 null 都给同一份缺省值,免得每处都写 asJson(await readBody(req), {}) || {}
37
+ export const readJsonBody = async (req, fallback = {}, limit = MAX_JSON_BODY) => asJson(await readBody(req, limit), fallback)
38
+
36
39
  export function asJson(text, fallback) {
37
40
  try { return JSON.parse(text) } catch { return fallback }
38
41
  }