dsh-modpack-kit 0.2.2 → 0.2.4
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/README.md +119 -15
- package/assets/install-stub.mjs +21 -3
- package/client.js +1484 -30
- package/docs/CODE-MAP.md +431 -0
- package/docs/DETAIL.md +87 -4
- package/docs/MARKET.txt +19 -0
- package/index.js +743 -10
- package/lib/community.mjs +66 -0
- package/lib/compat.mjs +12 -11
- package/lib/github.mjs +289 -0
- package/lib/groups.mjs +25 -11
- package/lib/install.mjs +25 -5
- package/lib/manifest.mjs +3 -1
- package/lib/market-catalog.mjs +11 -5
- package/lib/modpack-catalog.mjs +382 -0
- package/lib/net.mjs +4 -3
- package/lib/pack.mjs +20 -14
- package/lib/profile.mjs +5 -2
- package/lib/repack.mjs +57 -0
- package/lib/store.mjs +6 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-modpack —— Host 侧。
|
|
2
|
+
* dsh-modpack-kit —— Host 侧。
|
|
3
|
+
*
|
|
4
|
+
* 改之前先看 docs/CODE-MAP.md(功能 → 符号 → grep 示例;路由表也在那里自动生成)。
|
|
5
|
+
* 路由体写法:if (!needPost(req, res)) return + await readJsonBody(req),不要再包 fenced()。
|
|
3
6
|
*
|
|
4
7
|
* 只做四件事:把本机状况喂给页面、在内存里打包、在安装前把包拆开看清楚、调官方 CLI 装。
|
|
5
8
|
* 所有网络请求走 lib/registry 的白名单与体积上限;所有文件写入落在 <DSH_HOME>/dsh-modpack。
|
|
6
9
|
*/
|
|
7
10
|
import fs from 'node:fs'
|
|
8
11
|
import path from 'node:path'
|
|
9
|
-
import {
|
|
12
|
+
import { spawn } from 'node:child_process'
|
|
13
|
+
import { randomBytes, createHash } from 'node:crypto'
|
|
10
14
|
import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, clearHistory, removeHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
|
|
11
|
-
import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
|
|
15
|
+
import { listInstalled, dshVersion, readProfilePackage, readBundles, runDshPlugin } from './lib/profile.mjs'
|
|
12
16
|
import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime, probeRegistry } from './lib/registry.mjs'
|
|
13
17
|
import { buildPack, PackRefused } from './lib/pack.mjs'
|
|
14
18
|
import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
|
|
@@ -17,9 +21,13 @@ import { readMarketGroups, groupViews } from './lib/groups.mjs'
|
|
|
17
21
|
import { classifyPlugin } from './lib/classify.mjs'
|
|
18
22
|
import { groupFindings } from './lib/scan.mjs'
|
|
19
23
|
import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
|
|
24
|
+
import { CATEGORY_FALLBACK, marketSummary, searchMarket, syncMarket, findMarketPack, fetchMarketPack } from './lib/modpack-catalog.mjs'
|
|
25
|
+
import { resolveCommunity } from './lib/community.mjs'
|
|
26
|
+
import { whoAmI, openPackPullRequest, entryFileName, packFileName, ensureRelease, uploadReleaseAsset } from './lib/github.mjs'
|
|
20
27
|
import { parseYaml } from './lib/yamlish.mjs'
|
|
21
28
|
import { readPatch } from './lib/profile.mjs'
|
|
22
29
|
import { buildReadme } from './lib/manifest.mjs'
|
|
30
|
+
import { rewritePackManifest } from './lib/repack.mjs'
|
|
23
31
|
import { sendJson as json, readBody, readRawBody, readJsonBody, MAX_JSON_BODY, MAX_DROP_BODY } from './lib/http.mjs'
|
|
24
32
|
|
|
25
33
|
const VERSION = (() => {
|
|
@@ -85,6 +93,14 @@ export default {
|
|
|
85
93
|
profile: profileName(config),
|
|
86
94
|
paths: pathsFor(config),
|
|
87
95
|
catalog,
|
|
96
|
+
// 社区资源(自建目录):只读缓存,界面拿摘要与首页;真正的搜索走 /market/search
|
|
97
|
+
modpackMarket: (() => {
|
|
98
|
+
try { return marketSummary(config) } catch { return { present: false, stale: true, count: 0, categories: [], repo: '' } }
|
|
99
|
+
})(),
|
|
100
|
+
// 附属小插件:mode=builtin 表示用插件内置实现;profile 里装了声明兼容的外部实现时是 external
|
|
101
|
+
community: (() => {
|
|
102
|
+
try { return resolveCommunity(dir, config) } catch { return null }
|
|
103
|
+
})(),
|
|
88
104
|
placements: {
|
|
89
105
|
settings: config.showInSettings !== false,
|
|
90
106
|
sidebar: config.showInSidebar !== false,
|
|
@@ -171,6 +187,14 @@ export default {
|
|
|
171
187
|
return false
|
|
172
188
|
}
|
|
173
189
|
|
|
190
|
+
// 社区资源是「整合包」的附属小插件:关掉它的时候,那几条接口统一回 404
|
|
191
|
+
// (不是 405/500),界面据此提示「去设置里打开」,主体照常。
|
|
192
|
+
const COMMUNITY_OFF = { ok: false, error: '社区资源已关闭(小插件没启用):在设置里打开「显示『社区资源』这一栏」' }
|
|
193
|
+
const communityRoute = (pathname, handler) => route(pathname, async (req, res) => {
|
|
194
|
+
if (config.showModpackMarket === false) { json(res, 404, COMMUNITY_OFF); return }
|
|
195
|
+
await handler(req, res)
|
|
196
|
+
})
|
|
197
|
+
|
|
174
198
|
function pendingBytes() {
|
|
175
199
|
let total = 0
|
|
176
200
|
for (const item of pending.values()) total += item.buffer ? item.buffer.length : 0
|
|
@@ -194,9 +218,23 @@ export default {
|
|
|
194
218
|
for (const [token, item] of pending) if (now - item.at > PENDING_TTL) pending.delete(token)
|
|
195
219
|
}
|
|
196
220
|
|
|
221
|
+
// 读 profile 里的插件清单要遍历几百个包的 package.json,刷新时连着调十几次很慢:
|
|
222
|
+
// 这里按 profile 目录的 mtime 记住上一次结果,目录没变就直接复用(插件增删会改 mtime)
|
|
223
|
+
let installedMemo = { key: '', at: 0, value: [] };
|
|
197
224
|
const installedOrEmpty = () => {
|
|
198
|
-
|
|
199
|
-
|
|
225
|
+
let key = '';
|
|
226
|
+
try {
|
|
227
|
+
const dir = profileDir();
|
|
228
|
+
const stat = fs.statSync(path.join(dir, 'package.json'));
|
|
229
|
+
key = dir + '|' + stat.mtimeMs + '|' + stat.size;
|
|
230
|
+
} catch { key = ''; }
|
|
231
|
+
const now = Date.now();
|
|
232
|
+
if (key && installedMemo.key === key && now - installedMemo.at < 5000) return installedMemo.value;
|
|
233
|
+
let value = [];
|
|
234
|
+
try { value = listInstalled(profileDir()) } catch { value = []; }
|
|
235
|
+
installedMemo = { key, at: now, value };
|
|
236
|
+
return value;
|
|
237
|
+
};
|
|
200
238
|
|
|
201
239
|
// 三种策略能不能选:按「这次勾了哪些插件」实时算,客户端拿去做卡片灰显与原因弹窗;
|
|
202
240
|
// 打包时也再算一遍,挡住「界面上换了插件、策略却没跟着变」的情况。
|
|
@@ -244,7 +282,7 @@ export default {
|
|
|
244
282
|
},
|
|
245
283
|
{
|
|
246
284
|
id: 'lite',
|
|
247
|
-
title: '
|
|
285
|
+
title: '轻量包(轻量包)',
|
|
248
286
|
online: true,
|
|
249
287
|
ok: liteBlockers.length === 0,
|
|
250
288
|
reason: liteBlockers.map((b) => b.text).join(';'),
|
|
@@ -266,6 +304,7 @@ export default {
|
|
|
266
304
|
}
|
|
267
305
|
|
|
268
306
|
const compatFor = (manifest) => checkCompatibility(manifest.plugins, {
|
|
307
|
+
format: manifest && manifest.format,
|
|
269
308
|
installed: installedOrEmpty(),
|
|
270
309
|
dshVersion: (() => { try { return dshVersion(profileDir()) } catch { return '' } })(),
|
|
271
310
|
nodeVersion: process.versions.node,
|
|
@@ -377,6 +416,562 @@ export default {
|
|
|
377
416
|
}
|
|
378
417
|
})
|
|
379
418
|
|
|
419
|
+
// —— 社区资源(自建目录) ——
|
|
420
|
+
// 只做三件事:读目录、检索、取包;校验/扫描/安装全部复用 /inspect 与 /install 那条老路。
|
|
421
|
+
communityRoute('/dsh-modpack-kit/api/market', async (req, res) => {
|
|
422
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
423
|
+
let summary = null
|
|
424
|
+
try { summary = marketSummary(config) } catch (e) { summary = { present: false, stale: true, count: 0, categories: [], error: String((e && e.message) || e) } }
|
|
425
|
+
// 没目录、或过期了:后台自己去拉,页面先拿空壳(首屏不该被网络拖住)
|
|
426
|
+
if (!summary.present || summary.stale) ensureMarket(false)
|
|
427
|
+
const installed = new Set(installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name))
|
|
428
|
+
let first = { items: [], total: 0, hasMore: false }
|
|
429
|
+
if (summary.present) {
|
|
430
|
+
try {
|
|
431
|
+
first = searchMarket(config, { page: 1, pageSize: config.catalogPageSize, installed })
|
|
432
|
+
} catch (e) { first = { items: [], total: 0, hasMore: false, error: String((e && e.message) || e) } }
|
|
433
|
+
}
|
|
434
|
+
json(res, 200, { ok: true, summary, ...first, page: 1, pageSize: config.catalogPageSize })
|
|
435
|
+
})
|
|
436
|
+
|
|
437
|
+
// 社区资源的检索同样按 key 缓存 20 秒:连按几个键不该每次都重新打分
|
|
438
|
+
const marketSearchCache = new Map()
|
|
439
|
+
communityRoute('/dsh-modpack-kit/api/market/search', async (req, res) => {
|
|
440
|
+
if (!needPost(req, res)) return
|
|
441
|
+
const body = await readJsonBody(req)
|
|
442
|
+
const installed = installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name)
|
|
443
|
+
const cacheKey = JSON.stringify([body.query || '', body.category || 'all', body.sort || 'new', body.page || 1, body.pageSize || 20, installed.length])
|
|
444
|
+
const cached = marketSearchCache.get(cacheKey)
|
|
445
|
+
if (cached && Date.now() - cached.at < 20000) { json(res, 200, cached.data); return }
|
|
446
|
+
try {
|
|
447
|
+
const data = searchMarket(config, {
|
|
448
|
+
query: body.query,
|
|
449
|
+
category: body.category,
|
|
450
|
+
page: body.page,
|
|
451
|
+
pageSize: Number(body.pageSize) || config.catalogPageSize,
|
|
452
|
+
sort: body.sort,
|
|
453
|
+
installed,
|
|
454
|
+
})
|
|
455
|
+
marketSearchCache.set(cacheKey, { at: Date.now(), data })
|
|
456
|
+
if (marketSearchCache.size > 40) marketSearchCache.delete(marketSearchCache.keys().next().value)
|
|
457
|
+
json(res, 200, data)
|
|
458
|
+
} catch (e) {
|
|
459
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e), items: [], total: 0 })
|
|
460
|
+
}
|
|
461
|
+
})
|
|
462
|
+
|
|
463
|
+
communityRoute('/dsh-modpack-kit/api/market/sync', async (req, res) => {
|
|
464
|
+
if (!needPost(req, res)) return
|
|
465
|
+
const body = await readJsonBody(req)
|
|
466
|
+
try {
|
|
467
|
+
const result = await syncMarket(config, { force: body.force === true || config.modpackRefreshHours === 0 })
|
|
468
|
+
if (result.ok && !result.skipped) appendLog('modpack market synced: ' + result.count + ' packs / ' + result.source)
|
|
469
|
+
const installed = installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name)
|
|
470
|
+
const first = result.ok ? searchMarket(config, { page: 1, pageSize: config.catalogPageSize, installed }) : null
|
|
471
|
+
json(res, 200, { ok: result.ok, error: result.error || '', summary: marketSummary(config), ...(first || { items: [], total: 0, hasMore: false }) })
|
|
472
|
+
} catch (e) {
|
|
473
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e) })
|
|
474
|
+
}
|
|
475
|
+
})
|
|
476
|
+
|
|
477
|
+
communityRoute('/dsh-modpack-kit/api/upload/status', async (req, res) => {
|
|
478
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
479
|
+
json(res, 405, { ok: false, error: '只接受 GET' })
|
|
480
|
+
return
|
|
481
|
+
}
|
|
482
|
+
const token = readUploadToken()
|
|
483
|
+
json(res, 200, {
|
|
484
|
+
ok: true,
|
|
485
|
+
configured: Boolean(token),
|
|
486
|
+
login: uploadWho ? uploadWho.login : '',
|
|
487
|
+
repo: UPLOAD_REPO,
|
|
488
|
+
maxBytes: UPLOAD_MAX_BYTES,
|
|
489
|
+
memoryOnly: true,
|
|
490
|
+
})
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
// 保存 / 清除 GitHub 凭据:只放内存,不落盘、不进 settings;上传结束立刻丢
|
|
494
|
+
communityRoute('/dsh-modpack-kit/api/upload/token', async (req, res) => {
|
|
495
|
+
if (!needPost(req, res)) return
|
|
496
|
+
const body = (await readJsonBody(req)) || {}
|
|
497
|
+
const token = String(body.token || '').trim()
|
|
498
|
+
if (!token) {
|
|
499
|
+
setUploadToken('')
|
|
500
|
+
json(res, 200, { ok: true, configured: false, memoryOnly: true })
|
|
501
|
+
return
|
|
502
|
+
}
|
|
503
|
+
if (!/^[A-Za-z0-9_]{20,}$/u.test(token)) {
|
|
504
|
+
json(res, 400, { ok: false, error: '看起来不像 GitHub token(应是 ghp_ 或 github_pat_ 开头的一长串)' })
|
|
505
|
+
return
|
|
506
|
+
}
|
|
507
|
+
try {
|
|
508
|
+
const user = await whoAmI(token)
|
|
509
|
+
setUploadToken(token)
|
|
510
|
+
uploadWho = user
|
|
511
|
+
appendLog('upload token verified for ' + user.login)
|
|
512
|
+
json(res, 200, { ok: true, configured: true, login: user.login, memoryOnly: true })
|
|
513
|
+
} catch (error) {
|
|
514
|
+
json(res, 400, { ok: false, error: '这个 token 用不了:' + String((error && error.message) || error) })
|
|
515
|
+
}
|
|
516
|
+
})
|
|
517
|
+
|
|
518
|
+
// 上传前的「读一眼」:把包内清单读出来填到可编辑的输入框里。
|
|
519
|
+
// 只读清单、不扫描、不要凭据;参数(类型/格式/大小)仍由 submit 再判一次。
|
|
520
|
+
communityRoute('/dsh-modpack-kit/api/upload/preview', async (req, res) => {
|
|
521
|
+
if (!needPost(req, res)) return
|
|
522
|
+
const body = (await readJsonBody(req, {}, 48 * 1024 * 1024)) || {}
|
|
523
|
+
let got
|
|
524
|
+
try {
|
|
525
|
+
got = readUploadBytes(body)
|
|
526
|
+
} catch (error) {
|
|
527
|
+
json(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
528
|
+
return
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
const inspected = await inspectPackBuffer(got.bytes, {
|
|
532
|
+
config,
|
|
533
|
+
force: true,
|
|
534
|
+
scanBeforeInstall: false,
|
|
535
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
536
|
+
})
|
|
537
|
+
const manifest = inspected.manifest || {}
|
|
538
|
+
const pluginList = (manifest.plugins || []).map((plugin) => ({
|
|
539
|
+
name: plugin.name,
|
|
540
|
+
version: plugin.latest === true ? '' : String(plugin.version || ''),
|
|
541
|
+
latest: plugin.latest === true,
|
|
542
|
+
group: plugin.group || '',
|
|
543
|
+
configMode: plugin.configMode === 'custom' ? 'custom' : 'preset',
|
|
544
|
+
configIncluded: plugin.configIncluded === true,
|
|
545
|
+
configKeys: Array.isArray(plugin.configRedacted) ? plugin.configRedacted.length : 0,
|
|
546
|
+
dataIncluded: plugin.dataIncluded === true,
|
|
547
|
+
dataRedacted: Number(plugin.dataRedacted || 0),
|
|
548
|
+
embedded: plugin.embedded === true,
|
|
549
|
+
}))
|
|
550
|
+
const withConfig = pluginList.filter((item) => item.configMode === 'custom' || item.configIncluded)
|
|
551
|
+
const withData = pluginList.filter((item) => item.dataIncluded)
|
|
552
|
+
json(res, 200, {
|
|
553
|
+
ok: true,
|
|
554
|
+
fileName: got.fileName,
|
|
555
|
+
size: got.bytes.length,
|
|
556
|
+
sha256: createHash('sha256').update(got.bytes).digest('hex'),
|
|
557
|
+
format: manifest.format,
|
|
558
|
+
fields: {
|
|
559
|
+
name: String(manifest.name || ''),
|
|
560
|
+
author: String(body.author || manifest.author || ''),
|
|
561
|
+
description: String(manifest.description || ''),
|
|
562
|
+
homepage: String(manifest.homepage || ''),
|
|
563
|
+
},
|
|
564
|
+
plugins: pluginList.length,
|
|
565
|
+
pluginList,
|
|
566
|
+
summary: {
|
|
567
|
+
configMode: withConfig.length > 0 ? 'custom' : 'preset',
|
|
568
|
+
configCount: withConfig.length,
|
|
569
|
+
dataCount: withData.length,
|
|
570
|
+
redacted: pluginList.reduce((sum, item) => sum + item.configKeys + item.dataRedacted, 0),
|
|
571
|
+
groups: [...new Set(pluginList.map((item) => item.group).filter(Boolean))],
|
|
572
|
+
embeddedCount: pluginList.filter((item) => item.embedded).length,
|
|
573
|
+
},
|
|
574
|
+
})
|
|
575
|
+
} catch (error) {
|
|
576
|
+
json(res, 400, { ok: false, error: '读不了这个包:' + String((error && error.message) || error) })
|
|
577
|
+
}
|
|
578
|
+
})
|
|
579
|
+
|
|
580
|
+
// 上传的字节:页面直接选文件时走 base64;从「浏览文件夹」挑的走本机路径。
|
|
581
|
+
// 两条都限死在 UPLOAD_MAX_BYTES,路径只认 .dshpack 且必须是文件。
|
|
582
|
+
const readUploadBytes = (body) => {
|
|
583
|
+
const b64 = String((body && body.base64) || '').replace(/^data:[^,]+,/u, '')
|
|
584
|
+
if (b64) return { bytes: Buffer.from(b64, 'base64'), fileName: String((body && body.fileName) || '').trim() }
|
|
585
|
+
const raw = String((body && body.file) || '').trim()
|
|
586
|
+
if (!raw) throw new Error('缺 base64 或 file(先把包选上)')
|
|
587
|
+
const target = path.resolve(raw)
|
|
588
|
+
if (!target.toLowerCase().endsWith('.dshpack')) throw new Error('只认 .dshpack 整合包')
|
|
589
|
+
let stat
|
|
590
|
+
try { stat = fs.statSync(target) } catch { throw new Error('这个路径读不到:' + target) }
|
|
591
|
+
if (!stat.isFile()) throw new Error('这个路径不是文件:' + target)
|
|
592
|
+
if (stat.size > UPLOAD_MAX_BYTES) throw new Error('包超过 32 MB:目录不收这么大的,完整包请放发布页')
|
|
593
|
+
return { bytes: fs.readFileSync(target), fileName: path.basename(target) }
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// 一键上传:收包 → 校验(只收轻量/混合)→ fork/分支 → 放包与条目 → 开 PR
|
|
597
|
+
// 顺序:先把包本身验完(不需要凭据),再要 token——这样参数错误不会白白消耗一次 GitHub 调用
|
|
598
|
+
communityRoute('/dsh-modpack-kit/api/upload/submit', async (req, res) => {
|
|
599
|
+
if (!needPost(req, res)) return
|
|
600
|
+
const body = (await readJsonBody(req, {}, 48 * 1024 * 1024)) || {}
|
|
601
|
+
let bytes = Buffer.alloc(0)
|
|
602
|
+
let fileName = String(body.fileName || '').trim()
|
|
603
|
+
try {
|
|
604
|
+
const got = readUploadBytes(body)
|
|
605
|
+
bytes = got.bytes
|
|
606
|
+
fileName = fileName || got.fileName
|
|
607
|
+
} catch (error) {
|
|
608
|
+
json(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
609
|
+
return
|
|
610
|
+
}
|
|
611
|
+
const edits = body.edits && typeof body.edits === 'object' ? body.edits : {}
|
|
612
|
+
const category = String(body.category || '').trim()
|
|
613
|
+
const homepage = String(body.homepage || '').trim()
|
|
614
|
+
// 放哪:默认把包放进目录仓库(零额外步骤,但没有逐文件下载计数);
|
|
615
|
+
// host=release 时放到使用者自己的 GitHub Release 里,那边资产自带 download_count,
|
|
616
|
+
// 目录构建时读出来就是「真实下载量」。
|
|
617
|
+
const host = body.host === 'release' ? 'release' : 'repo'
|
|
618
|
+
// 演练:把整套检查(类型、读包、改词条、封面、条目拼装)真跑一遍,
|
|
619
|
+
// 但不碰 GitHub、不开 PR、不需要凭据。用来验实现,也方便先看条目长什么样。
|
|
620
|
+
const dryRun = body.dryRun === true
|
|
621
|
+
const ownerRepo = String(body.repo || '').trim()
|
|
622
|
+
const tag = String(body.tag || '').trim()
|
|
623
|
+
|
|
624
|
+
if (!fileName) {
|
|
625
|
+
json(res, 400, { ok: false, error: '缺文件名:页面会从选择的文件里带过来' })
|
|
626
|
+
return
|
|
627
|
+
}
|
|
628
|
+
if (!category) {
|
|
629
|
+
json(res, 400, { ok: false, error: '选一个类型(工作办公 / 性能优化 / 界面美化 / 实用功能 / 开发调试 / 娱乐休闲 / 学习资料 / 其它 / 水槽)' })
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
const allowedCategories = new Set(CATEGORY_FALLBACK.map((item) => item.label))
|
|
633
|
+
if (!allowedCategories.has(category)) {
|
|
634
|
+
json(res, 400, { ok: false, error: '不认识的类型「' + category + '」:可选 ' + Array.from(allowedCategories).join(' / ') })
|
|
635
|
+
return
|
|
636
|
+
}
|
|
637
|
+
if (!bytes.length) {
|
|
638
|
+
json(res, 400, { ok: false, error: '包是空的' })
|
|
639
|
+
return
|
|
640
|
+
}
|
|
641
|
+
if (bytes.length > UPLOAD_MAX_BYTES) {
|
|
642
|
+
json(res, 400, { ok: false, error: '包超过 32 MB:目录不收这么大的,完整包请放发布页' })
|
|
643
|
+
return
|
|
644
|
+
}
|
|
645
|
+
let inspected
|
|
646
|
+
try {
|
|
647
|
+
// 注意:inspectPackBuffer 的第二个参数是 options,config 要挂在 options.config 上。
|
|
648
|
+
// 之前这里直接传了 config,导致 maxPackBytes / extraScanRules 全被忽略。
|
|
649
|
+
inspected = await inspectPackBuffer(bytes, {
|
|
650
|
+
config,
|
|
651
|
+
force: true,
|
|
652
|
+
scanBeforeInstall: false,
|
|
653
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
654
|
+
})
|
|
655
|
+
} catch (error) {
|
|
656
|
+
json(res, 400, { ok: false, error: '读不了这个包:' + String((error && error.message) || error) })
|
|
657
|
+
return
|
|
658
|
+
}
|
|
659
|
+
// 「名称 / 作者 / 简介 / 主页」允许在上传前自己改:目录只认包里的清单,
|
|
660
|
+
// 所以改的时候是原地改写包内的 dsh-modpack.json(顺带重写 README.txt 与 integrity.json),
|
|
661
|
+
// 而不是在条目里另存一份覆盖字段——这样别人装到的包和目录里显示的也是改后的内容。
|
|
662
|
+
let edited = null
|
|
663
|
+
if (Object.keys(edits).length > 0) {
|
|
664
|
+
try {
|
|
665
|
+
const result = rewritePackManifest(bytes, edits)
|
|
666
|
+
if (result.changed) {
|
|
667
|
+
bytes = result.buffer
|
|
668
|
+
edited = result.patch
|
|
669
|
+
inspected = await inspectPackBuffer(bytes, {
|
|
670
|
+
config,
|
|
671
|
+
force: true,
|
|
672
|
+
scanBeforeInstall: false,
|
|
673
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
674
|
+
})
|
|
675
|
+
}
|
|
676
|
+
} catch (error) {
|
|
677
|
+
json(res, 400, { ok: false, error: '改清单时出错了:' + String((error && error.message) || error) })
|
|
678
|
+
return
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
const manifest = inspected.manifest || {}
|
|
682
|
+
const strategy = String(manifest.format || 'lite')
|
|
683
|
+
if (strategy !== 'lite' && strategy !== 'hybrid') {
|
|
684
|
+
json(res, 400, { ok: false, error: '目录只收轻量包与混合包;这个是完整包(' + strategy + ')' })
|
|
685
|
+
return
|
|
686
|
+
}
|
|
687
|
+
const slug = String(fileName).replace(/\.dshpack$/iu, '').toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+|-+$/gu, '')
|
|
688
|
+
const id = slug.length >= 3 && slug.length <= 40 ? slug : ('pack-' + Date.now().toString(36))
|
|
689
|
+
if (!/^[a-z0-9][a-z0-9-]{2,40}$/u.test(id)) {
|
|
690
|
+
json(res, 400, { ok: false, error: '文件名转不出合法的 id(要 3~40 位小写字母数字短横线),把包名改成英文再试' })
|
|
691
|
+
return
|
|
692
|
+
}
|
|
693
|
+
const file = packFileName(id, strategy)
|
|
694
|
+
const sha = inspected.integrity && inspected.integrity.sha256
|
|
695
|
+
? inspected.integrity.sha256
|
|
696
|
+
: createHash('sha256').update(bytes).digest('hex')
|
|
697
|
+
const today = new Date().toISOString().slice(0, 10)
|
|
698
|
+
const releaseRepo = ownerRepo
|
|
699
|
+
const releaseTag = tag || ('packs-' + id)
|
|
700
|
+
if (host === 'release') {
|
|
701
|
+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(releaseRepo)) {
|
|
702
|
+
json(res, 400, { ok: false, error: '要放 Release 的话,得先填你自己的仓库(owner/name)' })
|
|
703
|
+
return
|
|
704
|
+
}
|
|
705
|
+
if (!/^[A-Za-z0-9._-]{1,60}$/u.test(releaseTag)) {
|
|
706
|
+
json(res, 400, { ok: false, error: 'tag 只能用字母、数字、点、下划线与短横线(1~60 位)' })
|
|
707
|
+
return
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
// 封面图:只认 png/jpeg 的 data URL,大小限住,别让一张图把 PR 撑成几十 MB
|
|
711
|
+
const COVER_DATA_RE = /^data:image\/(?:png|jpeg);base64,[A-Za-z0-9+/=]+$/u
|
|
712
|
+
const COVER_MAX_BYTES = 300 * 1024
|
|
713
|
+
const parseCover = (value) => {
|
|
714
|
+
const text = String(value || '')
|
|
715
|
+
const match = /^data:image\/(png|jpeg);base64,([A-Za-z0-9+/=]+)$/u.exec(text)
|
|
716
|
+
if (!match) throw new Error('封面只认 PNG 或 JPG')
|
|
717
|
+
const coverBytes = Buffer.from(match[2], 'base64')
|
|
718
|
+
if (coverBytes.length === 0) throw new Error('封面是空的')
|
|
719
|
+
if (coverBytes.length > COVER_MAX_BYTES) {
|
|
720
|
+
throw new Error('封面太大:' + Math.round(coverBytes.length / 1024) + ' KB,上限 300 KB(建议 512×512 以内)')
|
|
721
|
+
}
|
|
722
|
+
return { ext: match[1] === 'jpeg' ? 'jpg' : 'png', bytes: coverBytes }
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
let coverPath = ''
|
|
726
|
+
if (body.cover) {
|
|
727
|
+
const cover = parseCover(body.cover)
|
|
728
|
+
coverPath = 'covers/' + id + '.' + cover.ext
|
|
729
|
+
}
|
|
730
|
+
const entry = {
|
|
731
|
+
id,
|
|
732
|
+
category,
|
|
733
|
+
customization: strategy === 'lite' ? 'none' : 'custom',
|
|
734
|
+
...(coverPath ? { cover: coverPath } : {}),
|
|
735
|
+
file,
|
|
736
|
+
sha256: sha,
|
|
737
|
+
size: bytes.length,
|
|
738
|
+
createdAt: today,
|
|
739
|
+
updatedAt: today,
|
|
740
|
+
homepage,
|
|
741
|
+
...(host === 'release'
|
|
742
|
+
? { host: 'release', repo: releaseRepo, tag: releaseTag }
|
|
743
|
+
: { repo: UPLOAD_REPO }),
|
|
744
|
+
}
|
|
745
|
+
// 包验完了才要凭据:没填 token 时上面的错误都已经返回,不会走到这里。
|
|
746
|
+
// 演练模式不需要凭据。
|
|
747
|
+
const token = dryRun ? '' : readUploadToken()
|
|
748
|
+
if (!dryRun && !token) {
|
|
749
|
+
json(res, 400, { ok: false, error: '还没有 GitHub 凭据:先在上传页填一次 token(只存在内存里,不会被抄进整合包)' })
|
|
750
|
+
return
|
|
751
|
+
}
|
|
752
|
+
// 上传也走任务队列:进度显示在左下角悬浮窗,出错也停在那一行等你点「我已知晓」
|
|
753
|
+
const job = createJob('upload', (dryRun ? '演练上传「' : '上传整合包「') + (manifest.name || id) + '」')
|
|
754
|
+
const steps = []
|
|
755
|
+
const push = (text, pct) => {
|
|
756
|
+
if (job.cancelled) {
|
|
757
|
+
const stop = new Error('已取消')
|
|
758
|
+
stop.name = 'JobCancelled'
|
|
759
|
+
throw stop
|
|
760
|
+
}
|
|
761
|
+
if (text) steps.push(text)
|
|
762
|
+
if (typeof pct === 'number') job.pct = pct
|
|
763
|
+
job.note = steps[steps.length - 1] || job.note
|
|
764
|
+
job.updatedAt = new Date().toISOString()
|
|
765
|
+
}
|
|
766
|
+
push('读取包与清单', 10)
|
|
767
|
+
;(async () => {
|
|
768
|
+
try {
|
|
769
|
+
if (dryRun) {
|
|
770
|
+
push('类型 / 读包 / 格式检查通过(' + strategy + ')', 30)
|
|
771
|
+
if (edited) push('会按你改的内容重写清单:' + Object.keys(edited).join('、'), 45)
|
|
772
|
+
if (coverPath) push('会放封面:' + coverPath, 55)
|
|
773
|
+
if (host === 'release') push('会放 Release:' + releaseRepo + ' · ' + releaseTag, 65)
|
|
774
|
+
else push('会把包写进 packs/' + file, 65)
|
|
775
|
+
push('会写条目 ' + entryFileName(id) + '(sha256 ' + sha.slice(0, 12) + '…)', 85)
|
|
776
|
+
job.status = 'done'
|
|
777
|
+
job.pct = 100
|
|
778
|
+
job.note = '演练完成:没有真的上传'
|
|
779
|
+
job.data = { dryRun: true, entry, steps }
|
|
780
|
+
return
|
|
781
|
+
}
|
|
782
|
+
const user = await whoAmI(token)
|
|
783
|
+
push('登录为 ' + user.login, 20)
|
|
784
|
+
if (!uploadWho) uploadWho = user
|
|
785
|
+
if (edited) push('按你改的内容重写清单:' + Object.keys(edited).join('、'), 15)
|
|
786
|
+
if (host === 'release') {
|
|
787
|
+
push('准备 Release', 35)
|
|
788
|
+
const release = await ensureRelease(token, releaseRepo, releaseTag, manifest.name || id, (text) => push(text, 45))
|
|
789
|
+
const asset = await uploadReleaseAsset(token, releaseRepo, release.id, file, bytes, (text) => push(text, 60))
|
|
790
|
+
push('下载地址:' + (asset.url || ('https://github.com/' + releaseRepo + '/releases/download/' + releaseTag + '/' + file)), 70)
|
|
791
|
+
}
|
|
792
|
+
const pr = await openPackPullRequest({
|
|
793
|
+
token,
|
|
794
|
+
catalog: UPLOAD_REPO,
|
|
795
|
+
login: user.login,
|
|
796
|
+
branch: 'add-pack-' + id + '-' + Date.now().toString(36).slice(-4),
|
|
797
|
+
// 条目里的 file 是裸文件名,仓库里落在 packs/ 下
|
|
798
|
+
packPath: host === 'release' ? '' : 'packs/' + file,
|
|
799
|
+
packBase64: host === 'release' ? '' : base64,
|
|
800
|
+
entryPath: entryFileName(id),
|
|
801
|
+
...(coverPath ? { coverPath, coverBase64: (body.cover ? String(body.cover).split(',')[1] : ''), packId: id } : {}),
|
|
802
|
+
entryText: JSON.stringify(entry, null, 2) + '\n',
|
|
803
|
+
title: 'catalog: add ' + (manifest.name || id),
|
|
804
|
+
body: [
|
|
805
|
+
'新增整合包:**' + (manifest.name || id) + '**',
|
|
806
|
+
'',
|
|
807
|
+
'- 类型:' + category,
|
|
808
|
+
'- 格式:' + strategy + '(' + (entry.customization === 'custom' ? '有自定义' : '无修改') + ')',
|
|
809
|
+
'- 插件:' + ((manifest.plugins || []).length) + ' 个',
|
|
810
|
+
'- sha256:' + sha,
|
|
811
|
+
'- 存放:' + (host === 'release' ? 'GitHub Release(' + releaseRepo + ' · ' + releaseTag + ')' : '目录仓库 packs/'),
|
|
812
|
+
'',
|
|
813
|
+
'由 dsh-modpack-kit 的上传页自动生成。',
|
|
814
|
+
].join('\n'),
|
|
815
|
+
onStep: (text) => push(text, job.pct < 70 ? 75 : 85),
|
|
816
|
+
})
|
|
817
|
+
appendLog('upload ' + id + ' -> PR #' + pr.number)
|
|
818
|
+
job.status = 'done'
|
|
819
|
+
job.pct = 100
|
|
820
|
+
job.note = 'PR 开好了:#' + pr.number
|
|
821
|
+
job.data = { pr, entry, steps }
|
|
822
|
+
} catch (error) {
|
|
823
|
+
if (error && error.name === 'JobCancelled') {
|
|
824
|
+
job.status = 'cancelled'
|
|
825
|
+
job.note = '已取消(没有开 PR)'
|
|
826
|
+
job.error = '已取消'
|
|
827
|
+
} else {
|
|
828
|
+
job.status = 'failed'
|
|
829
|
+
job.note = '卡住了'
|
|
830
|
+
job.error = String((error && error.message) || error)
|
|
831
|
+
}
|
|
832
|
+
job.data = { steps, entry, id }
|
|
833
|
+
} finally {
|
|
834
|
+
// 用后即刻清除:不管成没成,内存里的 token 都不留
|
|
835
|
+
clearUploadToken()
|
|
836
|
+
job.finishedAt = new Date().toISOString()
|
|
837
|
+
job.updatedAt = job.finishedAt
|
|
838
|
+
}
|
|
839
|
+
})()
|
|
840
|
+
json(res, 202, { ok: true, async: true, job: publicJob(job), entryId: id })
|
|
841
|
+
})
|
|
842
|
+
|
|
843
|
+
// 本地预览:把刚选好的包临时当成社区目录里的一条,
|
|
844
|
+
// 让「预览」能真的走一遍下载 → 读包 → 安装,全程不联网、不开 PR。
|
|
845
|
+
let localPreview = null
|
|
846
|
+
const PREVIEW_ID = '__local_preview__'
|
|
847
|
+
communityRoute('/dsh-modpack-kit/api/market/preview', async (req, res) => {
|
|
848
|
+
if (!needPost(req, res)) return
|
|
849
|
+
const body = await readJsonBody(req, {}, MAX_DROP_BODY)
|
|
850
|
+
try {
|
|
851
|
+
const gotBytes = readUploadBytes(body)
|
|
852
|
+
const bytes = gotBytes.bytes
|
|
853
|
+
const inspected = inspectPackBuffer(bytes, {
|
|
854
|
+
config,
|
|
855
|
+
force: true,
|
|
856
|
+
scanBeforeInstall: false,
|
|
857
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
858
|
+
})
|
|
859
|
+
const manifest = inspected.manifest
|
|
860
|
+
const count = Array.isArray(manifest.plugins) ? manifest.plugins.length : 0
|
|
861
|
+
localPreview = { bytes, manifest, at: Date.now() }
|
|
862
|
+
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
863
|
+
json(res, 200, {
|
|
864
|
+
ok: true,
|
|
865
|
+
pack: {
|
|
866
|
+
id: PREVIEW_ID,
|
|
867
|
+
name: String(body.name || manifest.name || '本地预览包'),
|
|
868
|
+
author: String(manifest.author || ''),
|
|
869
|
+
description: { zh: String(body.description || manifest.description || ''), en: '' },
|
|
870
|
+
category: String(body.category || '其它'),
|
|
871
|
+
strategy: manifest.format === 'hybrid' ? 'hybrid' : 'lite',
|
|
872
|
+
pluginCount: count,
|
|
873
|
+
tier: count >= 13 ? 'huge' : count >= 9 ? 'large' : count >= 4 ? 'medium' : 'small',
|
|
874
|
+
plugins: (manifest.plugins || []).map((p) => ({ name: p.name, version: p.version || '', latest: p.latest === true })),
|
|
875
|
+
cover: COVER_DATA_RE.test(String(body.cover || '')) ? String(body.cover) : '',
|
|
876
|
+
file: PREVIEW_ID + '.dshpack',
|
|
877
|
+
sha256,
|
|
878
|
+
size: bytes.length,
|
|
879
|
+
local: true,
|
|
880
|
+
pluginsDetail: manifest.plugins || [],
|
|
881
|
+
},
|
|
882
|
+
})
|
|
883
|
+
} catch (e) {
|
|
884
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e) })
|
|
885
|
+
}
|
|
886
|
+
})
|
|
887
|
+
|
|
888
|
+
// 下载一个整合包:只认目录里登记过的条目,sha256 必须对得上,
|
|
889
|
+
// 下完直接在内存里交给原来的 inspect(安全检测、兼容、许可证那一套原样走)。
|
|
890
|
+
communityRoute('/dsh-modpack-kit/api/market/download', async (req, res) => {
|
|
891
|
+
if (!needPost(req, res)) return
|
|
892
|
+
const body = await readJsonBody(req)
|
|
893
|
+
const saveOnly = body.saveOnly === true
|
|
894
|
+
const isPreview = body.id === PREVIEW_ID
|
|
895
|
+
const found = isPreview
|
|
896
|
+
? (localPreview
|
|
897
|
+
? {
|
|
898
|
+
ok: true,
|
|
899
|
+
pack: {
|
|
900
|
+
id: PREVIEW_ID,
|
|
901
|
+
name: localPreview.manifest.name || '本地预览包',
|
|
902
|
+
sha256: createHash('sha256').update(localPreview.bytes).digest('hex'),
|
|
903
|
+
},
|
|
904
|
+
}
|
|
905
|
+
: { ok: false, error: '还没有可以预览的包:先在「上传我的整合包」里选一个,再点预览' })
|
|
906
|
+
: findMarketPack(config, body.id)
|
|
907
|
+
if (!found.ok) { json(res, 200, { ok: false, error: found.error }); return }
|
|
908
|
+
const pack = found.pack
|
|
909
|
+
try {
|
|
910
|
+
const fetched = isPreview ? { url: 'local://' + PREVIEW_ID, buffer: localPreview.bytes } : await fetchMarketPack(config, pack)
|
|
911
|
+
const bytes = fetched.buffer
|
|
912
|
+
if (pack.size > 0 && bytes.length !== pack.size) {
|
|
913
|
+
throw new Error('包体积和目录里登记的不一致(登记 ' + pack.size + ' 字节,实际 ' + bytes.length + ' 字节)')
|
|
914
|
+
}
|
|
915
|
+
const actual = createHash('sha256').update(bytes).digest('hex')
|
|
916
|
+
if (!isPreview && pack.sha256 && actual !== pack.sha256) {
|
|
917
|
+
throw new Error('sha256 对不上:目录登记 ' + pack.sha256.slice(0, 12) + '…,实际 ' + actual.slice(0, 12) + '…')
|
|
918
|
+
}
|
|
919
|
+
const inspected = inspectPackBuffer(bytes, {
|
|
920
|
+
config,
|
|
921
|
+
force: body.force === true,
|
|
922
|
+
scanBeforeInstall: config.scanBeforeInstall !== false,
|
|
923
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
924
|
+
})
|
|
925
|
+
const fileName = slugify(inspected.manifest.name || pack.id, 'pack') + '.dshpack'
|
|
926
|
+
const token = saveOnly ? '' : rememberPending(fileName, { buffer: bytes, manifest: inspected.manifest, report: inspected.report, scan: inspected.scan })
|
|
927
|
+
appendLog('market ' + (saveOnly ? 'save' : 'download') + ' ' + pack.id + ' ' + bytes.length + ' bytes')
|
|
928
|
+
// 下载的包也留一份在插件自己的 packs 目录里:安装页能直接再选它,
|
|
929
|
+
// 关掉 DSH 之后那些内存里的 token 就没了,磁盘上这份还在。
|
|
930
|
+
const packsDir = pathsFor(config).packs
|
|
931
|
+
let savedPath = ''
|
|
932
|
+
let savedName = ''
|
|
933
|
+
try {
|
|
934
|
+
fs.mkdirSync(packsDir, { recursive: true })
|
|
935
|
+
const base = slugify(inspected.manifest.name || pack.name || pack.id || 'pack', 'pack')
|
|
936
|
+
const wantName = base + '-' + String(actual).slice(0, 8) + '.dshpack'
|
|
937
|
+
const target = path.join(packsDir, wantName)
|
|
938
|
+
if (!fs.existsSync(target)) fs.writeFileSync(target, bytes)
|
|
939
|
+
savedPath = target
|
|
940
|
+
savedName = wantName
|
|
941
|
+
appendLog('market save ' + wantName + ' ' + bytes.length + ' bytes')
|
|
942
|
+
} catch (e) {
|
|
943
|
+
// 存不下不影响这次安装:token 里还有字节,装完再说
|
|
944
|
+
appendLog('market save failed: ' + String((e && e.message) || e))
|
|
945
|
+
}
|
|
946
|
+
if (saveOnly) {
|
|
947
|
+
json(res, 200, { ok: true, savedOnly: true, savedPath, savedName, savedDir: packsDir, size: bytes.length, packId: pack.id, packName: pack.name, sha256: actual })
|
|
948
|
+
return
|
|
949
|
+
}
|
|
950
|
+
json(res, 200, {
|
|
951
|
+
ok: true,
|
|
952
|
+
token,
|
|
953
|
+
fileName,
|
|
954
|
+
savedPath,
|
|
955
|
+
savedName,
|
|
956
|
+
savedDir: packsDir,
|
|
957
|
+
size: bytes.length,
|
|
958
|
+
packId: pack.id,
|
|
959
|
+
packName: pack.name,
|
|
960
|
+
url: fetched.url,
|
|
961
|
+
manifest: inspected.manifest,
|
|
962
|
+
integrity: inspected.integrity,
|
|
963
|
+
scan: inspected.scan,
|
|
964
|
+
scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins),
|
|
965
|
+
report: inspected.report,
|
|
966
|
+
blockingReasons: inspected.blockingReasons,
|
|
967
|
+
notes: inspected.notes,
|
|
968
|
+
compat: compatFor(inspected.manifest),
|
|
969
|
+
})
|
|
970
|
+
} catch (e) {
|
|
971
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e) })
|
|
972
|
+
}
|
|
973
|
+
})
|
|
974
|
+
|
|
380
975
|
|
|
381
976
|
// —— 查某个包的可用版本 ——
|
|
382
977
|
route('/dsh-modpack-kit/api/versions', async (req, res) => {
|
|
@@ -394,7 +989,7 @@ export default {
|
|
|
394
989
|
}
|
|
395
990
|
})
|
|
396
991
|
|
|
397
|
-
// ——
|
|
992
|
+
// —— 打包(支持后台任务:悬浮窗要进度,且允许同时打多个包) ——
|
|
398
993
|
const jobs = new Map()
|
|
399
994
|
let jobSeq = 0
|
|
400
995
|
// 任务记录默认留到 DSH 下次启动(或点「清空进程」),切页面、换入口都不丢。
|
|
@@ -580,7 +1175,7 @@ export default {
|
|
|
580
1175
|
scanGroups: result.scanGroups,
|
|
581
1176
|
report: result.report,
|
|
582
1177
|
notes: result.notes,
|
|
583
|
-
compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: dshVersionNow, nodeVersion: process.versions.node, config }),
|
|
1178
|
+
compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: dshVersionNow, nodeVersion: process.versions.node, config, format: result.manifest && result.manifest.format }),
|
|
584
1179
|
}
|
|
585
1180
|
} catch (error) {
|
|
586
1181
|
if (error instanceof JobCancelled) {
|
|
@@ -691,6 +1286,50 @@ export default {
|
|
|
691
1286
|
}
|
|
692
1287
|
})
|
|
693
1288
|
|
|
1289
|
+
// 社区资源 → 插件 这一层的「装 / 更新」:跟插件市场同一个来源(npm 上的 name@version),
|
|
1290
|
+
// 优先交给宿主的插件管理器;管理器不在时退回官方命令行。装完插件市场认的就是市场版。
|
|
1291
|
+
route('/dsh-modpack-kit/api/plugin/install', async (req, res) => {
|
|
1292
|
+
if (!needPost(req, res)) return
|
|
1293
|
+
const body = await readJsonBody(req)
|
|
1294
|
+
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
1295
|
+
if (!/^(?:@[A-Za-z0-9][A-Za-z0-9._-]*\/)?[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(name)) {
|
|
1296
|
+
json(res, 400, { ok: false, error: '插件名不合法' })
|
|
1297
|
+
return
|
|
1298
|
+
}
|
|
1299
|
+
const version = typeof body.version === 'string' ? body.version.trim() : ''
|
|
1300
|
+
const wanted = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u.test(version) ? name + '@' + version : name
|
|
1301
|
+
const manager = ctx.get('pluginManager')
|
|
1302
|
+
try {
|
|
1303
|
+
if (manager && typeof manager.installBundle === 'function') {
|
|
1304
|
+
const change = await manager.installBundle(wanted, { enabled: true })
|
|
1305
|
+
const application = String((change && change.application) || '')
|
|
1306
|
+
appendLog('plugin ' + wanted + ' via=manager application=' + application)
|
|
1307
|
+
json(res, 200, {
|
|
1308
|
+
ok: application !== 'failed' && application !== 'cancelled',
|
|
1309
|
+
spec: wanted,
|
|
1310
|
+
application,
|
|
1311
|
+
restartRequired: application === 'restart-required',
|
|
1312
|
+
error: change && change.error ? String((change.error && change.error.code) || change.error) : '',
|
|
1313
|
+
output: change && change.packageResult ? String(change.packageResult.output || '').slice(-800) : '',
|
|
1314
|
+
})
|
|
1315
|
+
return
|
|
1316
|
+
}
|
|
1317
|
+
const profile = profileName(config)
|
|
1318
|
+
const result = await runDshPlugin(profile, ['add', wanted], { timeoutMs: 300000 })
|
|
1319
|
+
const code = result && typeof result.code === 'number' ? result.code : 1
|
|
1320
|
+
appendLog('plugin ' + wanted + ' via=cli exit=' + code)
|
|
1321
|
+
json(res, 200, {
|
|
1322
|
+
ok: code === 0,
|
|
1323
|
+
spec: wanted,
|
|
1324
|
+
application: code === 0 ? 'restart-required' : 'failed',
|
|
1325
|
+
restartRequired: code === 0,
|
|
1326
|
+
error: code === 0 ? '' : String((result && result.output) || '').slice(-800),
|
|
1327
|
+
})
|
|
1328
|
+
} catch (error) {
|
|
1329
|
+
json(res, 500, { ok: false, spec: wanted, error: String((error && error.message) || error), hint: '命令行这条路失败时,也可以在插件市场里装;两边来源一样。' })
|
|
1330
|
+
}
|
|
1331
|
+
})
|
|
1332
|
+
|
|
694
1333
|
route('/dsh-modpack-kit/api/pack', async (req, res) => {
|
|
695
1334
|
if (!needPost(req, res)) return
|
|
696
1335
|
const body = await readJsonBody(req)
|
|
@@ -881,6 +1520,46 @@ export default {
|
|
|
881
1520
|
json(res, 200, { ok: !listed.error, dir, items: listed.items, error: listed.error })
|
|
882
1521
|
})
|
|
883
1522
|
|
|
1523
|
+
// 打开插件自己的 packs 目录(设置里那个按钮)
|
|
1524
|
+
route('/dsh-modpack-kit/api/packs/open', async (req, res) => {
|
|
1525
|
+
if (!needPost(req, res)) return
|
|
1526
|
+
const dir = pathsFor(config).packs
|
|
1527
|
+
try {
|
|
1528
|
+
ensureDir(dir)
|
|
1529
|
+
if (process.platform === 'win32') spawn('explorer.exe', [dir], { detached: true, stdio: 'ignore' }).unref()
|
|
1530
|
+
else if (process.platform === 'darwin') spawn('open', [dir], { detached: true, stdio: 'ignore' }).unref()
|
|
1531
|
+
else spawn('xdg-open', [dir], { detached: true, stdio: 'ignore' }).unref()
|
|
1532
|
+
} catch (e) {
|
|
1533
|
+
json(res, 500, { ok: false, error: '打不开目录:' + ((e && e.message) || e) })
|
|
1534
|
+
return
|
|
1535
|
+
}
|
|
1536
|
+
json(res, 200, { ok: true, dir })
|
|
1537
|
+
})
|
|
1538
|
+
// 删掉插件自己 packs 目录里的一个包(安装页「已下载」那张卡用)
|
|
1539
|
+
route('/dsh-modpack-kit/api/packs/remove', async (req, res) => {
|
|
1540
|
+
if (!needPost(req, res)) return
|
|
1541
|
+
const body = await readJsonBody(req)
|
|
1542
|
+
const raw = String(body.name || '').trim()
|
|
1543
|
+
// 只认「纯粹的文件名」:带目录、带 .. 一律拒,别让它变成越界删除
|
|
1544
|
+
if (!raw || raw !== path.basename(raw) || /[\\/]/u.test(raw) || !raw.toLowerCase().endsWith('.dshpack')) {
|
|
1545
|
+
json(res, 400, { ok: false, error: '只删 packs 目录里的 .dshpack 文件名(不能带路径)' })
|
|
1546
|
+
return
|
|
1547
|
+
}
|
|
1548
|
+
const name = raw
|
|
1549
|
+
const dir = pathsFor(config).packs
|
|
1550
|
+
const target = path.join(dir, name)
|
|
1551
|
+
if (path.dirname(target) !== path.resolve(dir)) { json(res, 400, { ok: false, error: '不在插件自己的 packs 目录里' }); return }
|
|
1552
|
+
try {
|
|
1553
|
+
fs.rmSync(target, { force: true })
|
|
1554
|
+
appendLog('packs remove ' + name)
|
|
1555
|
+
} catch (e) {
|
|
1556
|
+
json(res, 500, { ok: false, error: String((e && e.message) || e) })
|
|
1557
|
+
return
|
|
1558
|
+
}
|
|
1559
|
+
const listed = listPacks(dir)
|
|
1560
|
+
json(res, 200, { ok: true, dir, items: listed.items, error: listed.error })
|
|
1561
|
+
})
|
|
1562
|
+
|
|
884
1563
|
// 拖到界面上的整合包:原始字节能走就走原始字节,走不通再走 base64 JSON
|
|
885
1564
|
route('/dsh-modpack-kit/api/pack/drop', async (req, res) => {
|
|
886
1565
|
if (!needPost(req, res)) return
|
|
@@ -1101,7 +1780,19 @@ export default {
|
|
|
1101
1780
|
}
|
|
1102
1781
|
push(4, '读取整合包')
|
|
1103
1782
|
const inspected = await inspectInput(body)
|
|
1104
|
-
|
|
1783
|
+
const payload = await runInstall(inspected, body, job)
|
|
1784
|
+
// 装完按设置把这份安装包清掉:只删插件自己 packs 目录里的文件,别的路径不碰
|
|
1785
|
+
if (payload && payload.ok && config.autoClearPack === true) {
|
|
1786
|
+
const want = String(body.sourcePackFile || '')
|
|
1787
|
+
const packsDir = path.resolve(pathsFor(config).packs)
|
|
1788
|
+
if (want) {
|
|
1789
|
+
const target = path.resolve(want)
|
|
1790
|
+
if (path.dirname(target) === packsDir && target.toLowerCase().endsWith('.dshpack')) {
|
|
1791
|
+
try { fs.rmSync(target, { force: true }); appendLog('auto clear pack ' + path.basename(target)) } catch (e) { appendLog('auto clear failed: ' + ((e && e.message) || e)) }
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
return payload
|
|
1105
1796
|
} catch (error) {
|
|
1106
1797
|
if (error instanceof JobCancelled) return { ok: false, cancelled: true, error: '已取消(没有改动 profile)' }
|
|
1107
1798
|
return { ok: false, error: String((error && error.message) || error) }
|
|
@@ -1223,9 +1914,51 @@ export default {
|
|
|
1223
1914
|
return catalogJob
|
|
1224
1915
|
}
|
|
1225
1916
|
|
|
1917
|
+
// ---- 一键上传:GitHub 凭据只存本机,不进 settings,也不会被抽进整合包 ----
|
|
1918
|
+
const UPLOAD_REPO = 'Vesna-Strivozha-cn/dsh-modpack-catalog'
|
|
1919
|
+
const UPLOAD_MAX_BYTES = 32 * 1024 * 1024
|
|
1920
|
+
// 凭据只在内存里活着:不落盘、不进 settings、不进日志。
|
|
1921
|
+
// 每次上传都要重新填一次;上传结束(成功或失败)立刻丢掉。
|
|
1922
|
+
let uploadToken = ''
|
|
1923
|
+
let uploadWho = null
|
|
1924
|
+
const setUploadToken = (token) => {
|
|
1925
|
+
uploadToken = String(token || '').trim()
|
|
1926
|
+
if (!uploadToken) uploadWho = null
|
|
1927
|
+
}
|
|
1928
|
+
const clearUploadToken = () => {
|
|
1929
|
+
uploadToken = ''
|
|
1930
|
+
uploadWho = null
|
|
1931
|
+
}
|
|
1932
|
+
const readUploadToken = () => uploadToken
|
|
1933
|
+
|
|
1934
|
+
// 社区资源也照这个套路:启动补一次、过期在后台补、十分钟内失败不重敲
|
|
1935
|
+
let marketJob = null
|
|
1936
|
+
let lastMarketTry = 0
|
|
1937
|
+
const ensureMarket = (force) => {
|
|
1938
|
+
if (marketJob) return marketJob
|
|
1939
|
+
if (force !== true && Date.now() - lastMarketTry < 10 * 60 * 1000) return Promise.resolve({ ok: false, skipped: true })
|
|
1940
|
+
if (force !== true) lastMarketTry = Date.now()
|
|
1941
|
+
const hours = Math.max(1, Number(config.modpackRefreshHours) || 24)
|
|
1942
|
+
marketJob = syncMarket(config, { force: force === true, maxAgeMs: hours * 3600 * 1000 })
|
|
1943
|
+
.then((result) => {
|
|
1944
|
+
if (result && result.ok && !result.skipped) appendLog(`整合包目录更新 ${result.count} 个(${result.source})`)
|
|
1945
|
+
else if (result && !result.ok) log('modpack market sync failed:', result.error)
|
|
1946
|
+
return result
|
|
1947
|
+
})
|
|
1948
|
+
.catch((error) => {
|
|
1949
|
+
log('modpack market sync failed:', String((error && error.message) || error))
|
|
1950
|
+
return { ok: false, error: String((error && error.message) || error) }
|
|
1951
|
+
})
|
|
1952
|
+
.finally(() => { marketJob = null })
|
|
1953
|
+
return marketJob
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1226
1956
|
log('routes ready')
|
|
1227
1957
|
// 起来就把目录补一次;没有网也不影响其它功能,失败只写日志
|
|
1228
|
-
if (process.env.DSH_MODPACK_OFFLINE !== '1')
|
|
1958
|
+
if (process.env.DSH_MODPACK_OFFLINE !== '1') {
|
|
1959
|
+
ensureCatalog(false).catch(() => {})
|
|
1960
|
+
if (config.showModpackMarket !== false) ensureMarket(false).catch(() => {})
|
|
1961
|
+
}
|
|
1229
1962
|
ctx.effect(() => {
|
|
1230
1963
|
const timer = setInterval(sweeper, 60 * 1000)
|
|
1231
1964
|
if (typeof timer.unref === 'function') timer.unref()
|