dsh-modpack-kit 0.1.3 → 0.1.5

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
@@ -9,7 +9,7 @@ import path from 'node:path'
9
9
  import { randomBytes } from 'node:crypto'
10
10
  import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
11
11
  import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
12
- import { downloadPackage, npmMetadata, fetchLimited, relativeTime } from './lib/registry.mjs'
12
+ import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime } 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'
@@ -22,6 +22,8 @@ import { buildReadme, pluginSummary } from './lib/manifest.mjs'
22
22
 
23
23
  const VERSION = '0.1.0'
24
24
  const MAX_JSON_BODY = 1024 * 1024
25
+ // 直接拖进来的整合包走原始字节(不塞 base64),上限与单次下载一致,够装大包
26
+ const MAX_DROP_BODY = 256 * 1024 * 1024
25
27
  const PENDING_TTL = 30 * 60 * 1000
26
28
  const PENDING_MAX = 4
27
29
  const PENDING_BYTES = 512 * 1024 * 1024
@@ -43,6 +45,22 @@ const readBody = (req, limit = MAX_JSON_BODY) => new Promise((resolve, reject) =
43
45
  req.on('error', reject)
44
46
  })
45
47
 
48
+ const readRawBody = (req, limit = MAX_DROP_BODY) => new Promise((resolve, reject) => {
49
+ let size = 0
50
+ const chunks = []
51
+ req.on('data', (chunk) => {
52
+ size += chunk.length
53
+ if (size > limit) {
54
+ reject(Object.assign(new Error('整合包太大:上限 ' + Math.round(limit / 1024 / 1024) + ' MB'), { statusCode: 413 }))
55
+ req.destroy()
56
+ return
57
+ }
58
+ chunks.push(chunk)
59
+ })
60
+ req.on('end', () => resolve(Buffer.concat(chunks)))
61
+ req.on('error', reject)
62
+ })
63
+
46
64
  const asJson = (text, fallback) => {
47
65
  try { return JSON.parse(text) } catch { return fallback }
48
66
  }
@@ -313,18 +331,42 @@ export default {
313
331
  // —— 打包(支持后台任务:左下角悬浮窗要进度,且允许同时打多个包) ——
314
332
  const jobs = new Map()
315
333
  let jobSeq = 0
316
- const JOBS_KEEP = 10 * 60 * 1000
334
+ // 收尾的记录按状态分别留:完成的多留一会儿方便回看,失败/取消的很快就清,别堆在眼前。
335
+ // 秒数来自设置 jobKeepSeconds(0 = 收尾就清),测试就靠它把时间压到零。
336
+ const FAILED_KEEP = 15 * 1000
337
+ const RUNNING_STALE = 10 * 60 * 1000
338
+ const keepMs = () => Math.max(0, Number(config.jobKeepSeconds) || 0) * 1000
339
+ const heartbeatAge = (job, now) => {
340
+ const stamp = Date.parse(job.updatedAt || job.finishedAt || job.startedAt || '') || 0
341
+ return stamp > 0 ? now - stamp : 0
342
+ }
343
+ // 卡住的 running(进程还在但心跳没了):标成失败,让它走失败那条清理路径
344
+ const reapStuck = (job, now) => {
345
+ if (job.status !== 'running') return
346
+ if (heartbeatAge(job, now) <= RUNNING_STALE) return
347
+ job.status = 'failed'
348
+ job.error = '卡住了:很久没有新进度,已自动收掉'
349
+ job.note = '已自动收掉'
350
+ job.finishedAt = new Date().toISOString()
351
+ job.updatedAt = job.finishedAt
352
+ job.updatedAt = job.finishedAt
353
+ }
317
354
  const pruneJobs = () => {
318
- const cut = Date.now() - JOBS_KEEP
355
+ const now = Date.now()
356
+ const keep = keepMs()
319
357
  for (const [id, job] of jobs) {
358
+ reapStuck(job, now)
359
+ // 停在风险点等你决定的,一直留着
360
+ if (job.status === 'paused') continue
320
361
  if (job.status === 'running') continue
321
- const stamp = Date.parse(job.finishedAt || job.startedAt) || 0
322
- if (stamp && stamp < cut) jobs.delete(id)
362
+ const age = heartbeatAge(job, now)
363
+ const limit = job.status === 'done' || job.status === 'acked' ? keep : Math.min(keep, FAILED_KEEP)
364
+ if (limit <= 0 || age > limit) jobs.delete(id)
323
365
  }
324
366
  for (const id of [...jobs.keys()]) {
325
367
  if (jobs.size <= 20) break
326
368
  const job = jobs.get(id)
327
- if (job.status === 'running') continue
369
+ if (job.status === 'running' || job.status === 'paused') continue
328
370
  jobs.delete(id)
329
371
  }
330
372
  }
@@ -337,6 +379,8 @@ export default {
337
379
  pct: 0,
338
380
  note: '准备中',
339
381
  startedAt: new Date().toISOString(),
382
+ // 最近一次有动静的时间:用来判断「还活着」还是「卡住了」
383
+ updatedAt: new Date().toISOString(),
340
384
  finishedAt: '',
341
385
  error: '',
342
386
  data: null,
@@ -386,13 +430,19 @@ export default {
386
430
  }
387
431
  try {
388
432
  const result = await buildPack({
389
- selection: selection.map((item) => ({
390
- name: String(item.name || ''),
391
- source: item.source === 'npm' ? 'npm' : 'profile',
392
- spec: item.spec ? String(item.spec) : '',
393
- mode: item.mode === 'local' ? 'local' : item.mode === 'base' ? 'base' : undefined,
394
- download: (spec) => downloadPackage(String(item.name || ''), spec || item.spec || '', config),
395
- })),
433
+ selection: selection.map((item) => {
434
+ const name = String(item.name || '')
435
+ const here = installed.some((p) => p.name === name)
436
+ // 市场里没装的插件也能打包:本机没有这份代码,就从 registry 按版本取包
437
+ const source = item.source === 'npm' || item.source === 'market' || !here ? 'npm' : 'profile'
438
+ return {
439
+ name,
440
+ source,
441
+ spec: item.spec ? String(item.spec) : (source === 'npm' ? String(item.version || '') : ''),
442
+ mode: item.mode === 'local' ? 'local' : item.mode === 'base' ? 'base' : undefined,
443
+ download: (spec) => downloadPackage(name, spec || item.spec || String(item.version || ''), config),
444
+ }
445
+ }),
396
446
  options: {
397
447
  includePayload: options.includePayload !== false,
398
448
  includeConfig: options.includeConfig !== false,
@@ -484,6 +534,7 @@ export default {
484
534
  : [],
485
535
  }
486
536
  job.finishedAt = new Date().toISOString()
537
+ job.updatedAt = job.finishedAt
487
538
  if (payload.needsAck === true) {
488
539
  job.status = 'paused'
489
540
  job.note = '检测到风险,等你决定'
@@ -505,6 +556,7 @@ export default {
505
556
  // 失败/取消也把原因放进 error,进度窗那一行能直接看到为什么卡住
506
557
  if (!(payload && payload.ok)) job.error = (payload && payload.error) || job.note
507
558
  job.finishedAt = new Date().toISOString()
559
+ job.updatedAt = job.finishedAt
508
560
  }
509
561
  const startPackJob = (body, label) => {
510
562
  const job = createJob('pack', label || ('打包「' + String((body.options && body.options.name) || 'DSH 整合包') + '」'))
@@ -522,6 +574,7 @@ export default {
522
574
  job.error = String((error && error.message) || error)
523
575
  job.note = '失败'
524
576
  job.finishedAt = new Date().toISOString()
577
+ job.updatedAt = job.finishedAt
525
578
  })
526
579
  return job
527
580
  }
@@ -571,6 +624,7 @@ export default {
571
624
  job.error = String((error && error.message) || error)
572
625
  job.note = '失败'
573
626
  job.finishedAt = new Date().toISOString()
627
+ job.updatedAt = job.finishedAt
574
628
  })
575
629
  json(res, 200, { ok: true, job: publicJob(job) })
576
630
  })
@@ -586,17 +640,24 @@ export default {
586
640
  json(res, 200, { ok: true, removed: id })
587
641
  })
588
642
 
589
- // 清空进程:删掉所有收尾记录(完成的、失败的、取消的、超上限卡住的都算),
590
- // 只有还在跑的与停在风险点等决定的留着。
643
+ // 清空进程:除了「正在跑」与「停在风险点等决定」,其余一律删——
644
+ // 完成的、失败的、取消的、超上限卡住的、以及假 running(心跳停了)都带走。
591
645
  route('/dsh-modpack-kit/api/jobs/clear', async (req, res) => {
592
646
  if (!needPost(req, res)) return
593
- const keep = new Set(['running', 'paused'])
594
647
  const removed = []
648
+ const now = Date.now()
595
649
  for (const [id, job] of [...jobs.entries()]) {
596
- if (keep.has(job.status)) continue
650
+ if (job.status === 'paused') continue
651
+ if (job.status === 'running') {
652
+ // 还活着的不动;心跳停了的先标成失败,再按收尾清掉
653
+ reapStuck(job, now)
654
+ if (job.status === 'running') continue
655
+ }
656
+ // 卡住的 running:没有文件落盘(包在内存里组装),直接摘掉即可
597
657
  jobs.delete(id)
598
658
  removed.push(id)
599
659
  }
660
+ pruneJobs()
600
661
  json(res, 200, { ok: true, removed, jobs: [...jobs.values()].map(publicJob) })
601
662
  })
602
663
 
@@ -659,19 +720,91 @@ export default {
659
720
  json(res, 200, { ok: true, path: target, size: item.buffer.length })
660
721
  })
661
722
 
662
- route('/dsh-modpack-kit/api/packs', async (req, res) => {
663
- if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
664
- const dir = pathsFor(config).packs
723
+ // 列某个目录下的整合包:GET 读本插件自己的 packs 目录,POST { dir } 读你指定的目录
724
+ const listPacks = (dir) => {
665
725
  const items = []
726
+ let error = ''
666
727
  try {
667
- for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
668
- if (!dirent.isFile() || !dirent.name.endsWith('.dshpack')) continue
669
- const stat = fs.statSync(path.join(dir, dirent.name))
670
- items.push({ name: dirent.name, size: stat.size, mtime: stat.mtime.toISOString() })
728
+ const stat = fs.statSync(dir)
729
+ if (!stat.isDirectory()) error = '这个路径不是目录'
730
+ } catch (e) {
731
+ error = '这个目录读不到(不存在或没有权限)'
732
+ }
733
+ if (!error) {
734
+ try {
735
+ for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
736
+ if (!dirent.isFile() || !dirent.name.toLowerCase().endsWith('.dshpack')) continue
737
+ const stat = fs.statSync(path.join(dir, dirent.name))
738
+ items.push({ name: dirent.name, size: stat.size, mtime: stat.mtime.toISOString(), path: path.join(dir, dirent.name) })
739
+ }
740
+ } catch (e) {
741
+ error = String((e && e.message) || e)
671
742
  }
672
- } catch {}
743
+ }
673
744
  items.sort((a, b) => (a.mtime < b.mtime ? 1 : -1))
674
- json(res, 200, { ok: true, dir, items })
745
+ return { error, items }
746
+ }
747
+
748
+ route('/dsh-modpack-kit/api/packs', async (req, res) => {
749
+ if (req.method === 'GET') {
750
+ const dir = pathsFor(config).packs
751
+ const listed = listPacks(dir)
752
+ json(res, 200, { ok: !listed.error, dir, items: listed.items, error: listed.error })
753
+ return
754
+ }
755
+ if (req.method !== 'POST') { json(res, 405, { ok: false }); return }
756
+ const body = asJson(await readBody(req), {})
757
+ const raw = String(body.dir || '').trim()
758
+ const dir = raw ? path.resolve(raw) : pathsFor(config).packs
759
+ const listed = listPacks(dir)
760
+ json(res, 200, { ok: !listed.error, dir, items: listed.items, error: listed.error })
761
+ })
762
+
763
+ // 拖到界面上的整合包:原始字节能走就走原始字节,走不通再走 base64 JSON
764
+ route('/dsh-modpack-kit/api/pack/drop', async (req, res) => {
765
+ if (!needPost(req, res)) return
766
+ let bytes = null
767
+ const contentType = String(req.headers['content-type'] || '').toLowerCase()
768
+ try {
769
+ if (contentType.includes('application/json')) {
770
+ // 有些环境不许 POST 二进制,界面会退回 base64:这里同样收
771
+ const body = asJson(await readBody(req, MAX_DROP_BODY), {}) || {}
772
+ const raw = typeof body.data === 'string' ? body.data : ''
773
+ if (!raw) { json(res, 400, { ok: false, error: '没有收到整合包内容' }); return }
774
+ bytes = Buffer.from(raw, 'base64')
775
+ } else {
776
+ bytes = await readRawBody(req)
777
+ }
778
+ } catch (error) {
779
+ json(res, 413, { ok: false, error: String((error && error.message) || error) })
780
+ return
781
+ }
782
+ if (!bytes || bytes.length < 32) { json(res, 400, { ok: false, error: '这个文件看起来不是整合包(太小了)' }); return }
783
+ try {
784
+ const inspected = inspectPackBuffer(bytes, {
785
+ config,
786
+ scanBeforeInstall: config.scanBeforeInstall !== false,
787
+ extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
788
+ })
789
+ const fileName = slugify(inspected.manifest.name || 'dropped', 'pack') + '.dshpack'
790
+ const token = rememberPending(fileName, { buffer: bytes, manifest: inspected.manifest, report: inspected.report, scan: inspected.scan })
791
+ json(res, 200, {
792
+ ok: true,
793
+ token,
794
+ fileName,
795
+ size: bytes.length,
796
+ manifest: inspected.manifest,
797
+ integrity: inspected.integrity,
798
+ scan: inspected.scan,
799
+ scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins),
800
+ report: inspected.report,
801
+ blockingReasons: inspected.blockingReasons,
802
+ notes: inspected.notes,
803
+ compat: compatFor(inspected.manifest),
804
+ })
805
+ } catch (error) {
806
+ json(res, 200, { ok: false, error: String((error && error.message) || error) })
807
+ }
675
808
  })
676
809
 
677
810
  async function inspectInput(body) {
@@ -717,51 +850,193 @@ export default {
717
850
  })
718
851
 
719
852
  // —— 安装 ——
720
- route('/dsh-modpack-kit/api/install', async (req, res) => {
721
- if (!needPost(req, res)) return
722
- const body = asJson(await readBody(req), {})
723
- const options = {
724
- force: body.force === true,
725
- keepLocal: body.keepLocal !== false,
726
- applyConfig: body.applyConfig !== false,
727
- dryRun: body.dryRun === true,
728
- // 是否登记 bundle:请求里给了就听请求的,没给就听设置里的 enableOnInstall(默认关)。
729
- enableBundles: typeof body.enableBundles === 'boolean' ? body.enableBundles : config.enableOnInstall === true,
853
+ // —— 安装:先跳过本机已装的,装完其余再问要不要替换 ——
854
+ const pendingInstalls = new Map()
855
+ const rememberInstall = (inspected) => {
856
+ const token = 'inst_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
857
+ pendingInstalls.set(token, { inspected, at: Date.now() })
858
+ // 上限 4 份、30 分钟过期:别让内存一直攒着包
859
+ for (const [key, item] of pendingInstalls) {
860
+ if (pendingInstalls.size <= 4) break
861
+ if (key === token) continue
862
+ pendingInstalls.delete(key)
730
863
  }
731
- try {
732
- const inspected = await inspectInput(body)
733
- if (inspected.blockingReasons.length > 0 && !options.force) {
734
- const refused = new InstallRefused(inspected.blockingReasons.join(';'), inspected.scan)
735
- json(res, 200, { ok: false, refused: true, error: refused.message, integrity: inspected.integrity, scan: inspected.scan, scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins), report: inspected.report })
736
- return
864
+ for (const [key, item] of pendingInstalls) {
865
+ if (Date.now() - item.at > 30 * 60 * 1000) pendingInstalls.delete(key)
866
+ }
867
+ return token
868
+ }
869
+
870
+ const installOptionsOf = (body) => ({
871
+ force: body.force === true,
872
+ keepLocal: body.keepLocal !== false,
873
+ applyConfig: body.applyConfig !== false,
874
+ dryRun: body.dryRun === true,
875
+ // 是否登记 bundle:请求里给了就听请求的,没给就听设置里的 enableOnInstall(默认关)。
876
+ enableBundles: typeof body.enableBundles === 'boolean' ? body.enableBundles : config.enableOnInstall === true,
877
+ // 默认:本机已装(同名或同插件不同版本)先跳过,其余照装,最后再问
878
+ deferExisting: body.deferExisting !== false && body.replaceExisting !== true,
879
+ replaceExisting: body.replaceExisting === true,
880
+ only: Array.isArray(body.only) && body.only.length > 0 ? body.only.map(String) : null,
881
+ // 联网且有插件市场时优先按市场版本装(默认开;请求里能逐次关掉)
882
+ preferMarket: typeof body.preferMarket === 'boolean' ? body.preferMarket : config.preferMarketOnInstall !== false,
883
+ })
884
+
885
+ const runInstall = async (inspected, body, job) => {
886
+ const options = installOptionsOf(body)
887
+ const push = (pct, note) => {
888
+ if (!job) return
889
+ if (job.cancelled) throw new JobCancelled('已取消')
890
+ job.pct = pct
891
+ job.note = note || job.note
892
+ job.updatedAt = new Date().toISOString()
893
+ }
894
+ const scanGroups = groupFindings(inspected.scan.findings, inspected.manifest.plugins)
895
+ if (inspected.blockingReasons.length > 0 && !options.force) {
896
+ return {
897
+ ok: false,
898
+ refused: true,
899
+ error: inspected.blockingReasons.join(';'),
900
+ integrity: inspected.integrity,
901
+ scan: inspected.scan,
902
+ scanGroups,
903
+ report: inspected.report,
737
904
  }
738
- const result = await installPack({
739
- manifest: inspected.manifest,
740
- entries: inspected.entries,
741
- config,
742
- options,
743
- context: {
744
- profileDir: profileDir(),
745
- resolveSource: async (plugin, packRoot) => {
746
- const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
747
- const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
748
- ensureDir(target)
749
- for (const entry of downloaded.entries) {
750
- const dest = path.join(target, entry.name)
751
- if (!path.resolve(dest).startsWith(path.resolve(target) + path.sep)) continue
752
- ensureDir(path.dirname(dest))
753
- fs.writeFileSync(dest, entry.data)
754
- }
755
- appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry)
756
- return target
757
- },
905
+ }
906
+ push(12, '开始安装')
907
+ const result = await installPack({
908
+ manifest: inspected.manifest,
909
+ entries: inspected.entries,
910
+ config,
911
+ options: { ...options, onProgress: (event) => push(event.pct, event.note) },
912
+ context: {
913
+ profileDir: profileDir(),
914
+ // 优先用宿主自带的插件管理器(pnpm、激活、重启判定都由它负责);
915
+ // 服务不在或调用抛错时 installPack 会自动退回 dsh 命令行。
916
+ installBundle: (() => {
917
+ const manager = ctx.get('pluginManager')
918
+ if (!manager || typeof manager.installBundle !== 'function') return undefined
919
+ return (spec, opts) => manager.installBundle(spec, opts)
920
+ })(),
921
+ // 联网且市场可用时,优先按市场版本装(能用就返回 name@version,用不了返回 null 走包内)
922
+ resolveMarket: async (plugin) => {
923
+ try {
924
+ const { meta } = await npmMetadata(plugin.name, config)
925
+ const version = pickVersion(meta, plugin.version || plugin.spec || '') || pickVersion(meta, '')
926
+ if (!version) return null
927
+ appendLog('market ' + plugin.name + '@' + version + ' 优先于包内 ' + (plugin.version || '(未标版本)'))
928
+ return { spec: plugin.name + '@' + version, version }
929
+ } catch (error) {
930
+ appendLog('market miss ' + plugin.name + ': ' + String((error && error.message) || error))
931
+ return null
932
+ }
758
933
  },
759
- })
760
- 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)
761
- json(res, 200, { ok: result.ok, ...result, manifest: inspected.manifest, scan: inspected.scan, scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins), report: inspected.report, integrity: inspected.integrity })
934
+ resolveSource: async (plugin, packRoot) => {
935
+ const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
936
+ const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
937
+ ensureDir(target)
938
+ for (const entry of downloaded.entries) {
939
+ const dest = path.join(target, entry.name)
940
+ if (!path.resolve(dest).startsWith(path.resolve(target) + path.sep)) continue
941
+ ensureDir(path.dirname(dest))
942
+ fs.writeFileSync(dest, entry.data)
943
+ }
944
+ appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry)
945
+ return target
946
+ },
947
+ },
948
+ })
949
+ 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)
950
+ const token = rememberInstall(inspected)
951
+ return {
952
+ ok: result.ok,
953
+ ...result,
954
+ token,
955
+ manifest: inspected.manifest,
956
+ scan: inspected.scan,
957
+ scanGroups,
958
+ report: inspected.report,
959
+ integrity: inspected.integrity,
960
+ }
961
+ }
962
+
963
+ const performInstall = async (body, job) => {
964
+ try {
965
+ const push = (pct, note) => {
966
+ if (!job) return
967
+ if (job.cancelled) throw new JobCancelled('已取消')
968
+ job.pct = pct
969
+ job.note = note || job.note
970
+ }
971
+ push(4, '读取整合包')
972
+ const inspected = await inspectInput(body)
973
+ return await runInstall(inspected, body, job)
762
974
  } catch (error) {
763
- json(res, 200, { ok: false, error: String((error && error.message) || error) })
975
+ if (error instanceof JobCancelled) return { ok: false, cancelled: true, error: '已取消(没有改动 profile)' }
976
+ return { ok: false, error: String((error && error.message) || error) }
764
977
  }
978
+ }
979
+
980
+ const finishInstallJob = (job, payload) => {
981
+ job.status = payload && payload.ok ? 'done' : payload && payload.cancelled === true ? 'cancelled' : 'failed'
982
+ job.data = payload
983
+ job.pct = payload && payload.ok ? 100 : job.pct
984
+ job.note = payload && payload.ok ? '完成' : ((payload && payload.error) || '已停止')
985
+ if (!(payload && payload.ok)) job.error = (payload && payload.error) || job.note
986
+ job.finishedAt = new Date().toISOString()
987
+ job.updatedAt = job.finishedAt
988
+ }
989
+
990
+ const startInstallJob = (body, label) => {
991
+ const job = createJob('install', label || '安装整合包')
992
+ performInstall(body, job)
993
+ .then((payload) => finishInstallJob(job, payload))
994
+ .catch((error) => {
995
+ job.status = 'failed'
996
+ job.error = String((error && error.message) || error)
997
+ job.note = '失败'
998
+ job.finishedAt = new Date().toISOString()
999
+ job.updatedAt = job.finishedAt
1000
+ })
1001
+ return job
1002
+ }
1003
+
1004
+ route('/dsh-modpack-kit/api/install', async (req, res) => {
1005
+ if (!needPost(req, res)) return
1006
+ const body = asJson(await readBody(req), {})
1007
+ if (body.async === true || body.background === true) {
1008
+ const job = startInstallJob(body, body.label ? String(body.label) : undefined)
1009
+ json(res, 200, { ok: true, async: true, job: publicJob(job) })
1010
+ return
1011
+ }
1012
+ const payload = await performInstall(body, null)
1013
+ json(res, 200, payload)
1014
+ })
1015
+
1016
+ // 装完的追问:把刚才跳过的那些换成包内版本
1017
+ route('/dsh-modpack-kit/api/install/replace', async (req, res) => {
1018
+ if (!needPost(req, res)) return
1019
+ const body = asJson(await readBody(req), {})
1020
+ const token = String(body.token || '')
1021
+ const item = pendingInstalls.get(token)
1022
+ if (!item) { json(res, 400, { ok: false, error: '这次安装的上下文已过期,请重新读一遍整合包' }); return }
1023
+ const names = Array.isArray(body.names) && body.names.length > 0 ? body.names.map(String) : null
1024
+ if (body.async === true || body.background === true) {
1025
+ const job = createJob('install', '替换为包内版本' + (names ? '(' + names.length + ' 个)' : ''))
1026
+ runInstall(item.inspected, { ...body, replaceExisting: true, keepLocal: false, only: names }, job)
1027
+ .then((payload) => finishInstallJob(job, payload))
1028
+ .catch((error) => {
1029
+ job.status = 'failed'
1030
+ job.error = String((error && error.message) || error)
1031
+ job.note = '失败'
1032
+ job.finishedAt = new Date().toISOString()
1033
+ job.updatedAt = job.finishedAt
1034
+ })
1035
+ json(res, 200, { ok: true, async: true, job: publicJob(job) })
1036
+ return
1037
+ }
1038
+ const payload = await runInstall(item.inspected, { ...body, replaceExisting: true, keepLocal: false, only: names }, null)
1039
+ json(res, 200, payload)
765
1040
  })
766
1041
 
767
1042
  // —— 历史 ——