dsh-modpack-kit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/compat.mjs ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * dsh-modpack —— 兼容性检查。
3
+ *
4
+ * 只报「确定能判断的」问题:peer 依赖在不在、版本满不满足、engines 对不对、
5
+ * license 允不允许、同 id 的配置会不会被覆盖。判断不了的一律说「无法判断」,
6
+ * 不装作通过——安装包最怕的就是假绿灯。
7
+ */
8
+ import { satisfies, parseVersion, compareVersions } from './semver.mjs'
9
+
10
+ const HOST_SCOPE = /^@deepseek-ai\//u
11
+
12
+ function versionOf(map, name) {
13
+ const hit = map.get(name)
14
+ return hit ? hit.version : null
15
+ }
16
+
17
+ /**
18
+ * @param {object[]} plugins 清单里的插件条目
19
+ * @param {object} context {installed: object[], dshVersion, nodeVersion, config}
20
+ */
21
+ export function checkCompatibility(plugins, context) {
22
+ const installedMap = new Map((context.installed || []).map((p) => [p.name, p]))
23
+ const packMap = new Map((plugins || []).map((p) => [p.name, p]))
24
+ const findings = []
25
+ const add = (level, plugin, code, message, suggestion) => findings.push({ level, plugin, code, message, suggestion })
26
+ const dshVersion = context.dshVersion || ''
27
+ const nodeVersion = context.nodeVersion || process.versions.node
28
+ const allow = new Set((context.config?.licenseAllow || []).map((x) => String(x).toLowerCase()))
29
+
30
+ for (const plugin of plugins || []) {
31
+ const local = installedMap.get(plugin.name)
32
+ if (local) {
33
+ if (local.version !== plugin.version) {
34
+ const cmp = compareVersions(plugin.version, local.version)
35
+ add('info', plugin.name, 'local-version',
36
+ '本地已装 ' + local.version + ',整合包里是 ' + plugin.version + (cmp === null ? '' : cmp > 0 ? '(较新)' : cmp < 0 ? '(较旧,可能降级)' : ''),
37
+ cmp !== null && cmp < 0 ? '确认要降级再装;降级可能丢掉新版本的配置项。' : '安装会按整合包里的版本处理。')
38
+ }
39
+ if (!local.isBundle && plugin.isBundle) {
40
+ add('warn', plugin.name, 'local-not-bundle', '本地同名包不是 DSH 插件(没有 dsh 段)', '确认整合包来源;装完可能不会出现在侧栏。')
41
+ }
42
+ } else {
43
+ add('info', plugin.name, 'not-installed', '本地未安装,将新增', '')
44
+ }
45
+
46
+ const peers = plugin.peerDependencies || {}
47
+ for (const [peer, range] of Object.entries(peers)) {
48
+ if (HOST_SCOPE.test(peer)) continue
49
+ const inPack = packMap.get(peer)
50
+ const inLocal = installedMap.get(peer)
51
+ const found = inPack ? inPack.version : inLocal ? inLocal.version : null
52
+ if (!found) {
53
+ add('warn', plugin.name, 'peer-missing-' + peer,
54
+ '需要 ' + peer + ' ' + range + ',整合包和本机都没有',
55
+ '安装后这个插件可能报错或功能缺失;把它一起打包进来。')
56
+ continue
57
+ }
58
+ const ok = satisfies(found, range)
59
+ if (ok === false) {
60
+ add('error', plugin.name, 'peer-conflict-' + peer,
61
+ '需要 ' + peer + ' ' + range + ',实际是 ' + found + '(版本冲突)',
62
+ '换成满足范围的 ' + peer + ' 版本,或把整合包里那个插件换版本。')
63
+ } else if (ok === null) {
64
+ add('info', plugin.name, 'peer-unknown-' + peer, 'peer 范围看不懂:' + peer + ' ' + range, '请人工确认。')
65
+ }
66
+ }
67
+
68
+ const engines = plugin.engines || {}
69
+ if (engines.dsh && dshVersion) {
70
+ const ok = satisfies(dshVersion, String(engines.dsh))
71
+ if (ok === false) {
72
+ add('error', plugin.name, 'engines-dsh', '要求 DSH ' + engines.dsh + ',本机是 ' + dshVersion,
73
+ '先升级 DSH 再装,或换一个兼容的插件版本。')
74
+ } else if (ok === null) {
75
+ add('info', plugin.name, 'engines-dsh-unknown', 'engines.dsh 看不懂:' + engines.dsh, '')
76
+ }
77
+ }
78
+ if (engines.node && nodeVersion) {
79
+ const ok = satisfies(String(nodeVersion), String(engines.node))
80
+ if (ok === false) {
81
+ add('error', plugin.name, 'engines-node', '要求 Node ' + engines.node + ',本机是 ' + nodeVersion,
82
+ 'DSH 自带 Node 版本不可换;请找兼容的插件版本。')
83
+ }
84
+ }
85
+
86
+ if (!plugin.license) {
87
+ add('warn', plugin.name, 'license-missing', '插件没写 license', '再分发前请联系作者确认授权,否则不要传给别人。')
88
+ } else if (!allow.has(String(plugin.license).toLowerCase())) {
89
+ add('warn', plugin.name, 'license-unlisted', 'license 不在允许列表:' + plugin.license,
90
+ '确认许可允许再分发;不确定就只在自己机器上装。')
91
+ }
92
+ if (plugin.localEdits) {
93
+ add('info', plugin.name, 'local-edits', '打包时带的是打包者改过的本地文件', '和上游发布的版本可能不一致。')
94
+ }
95
+ if (!plugin.hasClient && !plugin.hasPatch && plugin.isBundle === false) {
96
+ add('warn', plugin.name, 'not-bundle', '这个包没有 dsh 段,可能不是 DSH 插件', '确认是不是装错了东西。')
97
+ }
98
+ }
99
+
100
+ const errors = findings.filter((f) => f.level === 'error')
101
+ const warns = findings.filter((f) => f.level === 'warn')
102
+ return {
103
+ findings,
104
+ blocking: errors.length > 0,
105
+ counts: { error: errors.length, warn: warns.length, info: findings.length - errors.length - warns.length },
106
+ summary: errors.length > 0
107
+ ? '有 ' + errors.length + ' 个必须处理的问题,' + warns.length + ' 个提醒'
108
+ : warns.length > 0
109
+ ? '可以装,但有 ' + warns.length + ' 个提醒'
110
+ : '没发现兼容问题',
111
+ }
112
+ }
@@ -0,0 +1,344 @@
1
+ /**
2
+ * dsh-modpack —— 读包 / 检测 / 安装。
3
+ *
4
+ * 安装只有一条腿:调用官方 `dsh plugin add file:<目录>`。整合包不自己写 node_modules,
5
+ * 也不自己改 pnpm 锁——那样迟早和插件市场打架。本模块负责的是它前面那一步:
6
+ * 解出文件、校验完整性、扫一遍风险、判断兼容、再把配置补回去。
7
+ */
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import { readZip, readZipText, safeEntryName } from './zip.mjs'
11
+ import { scanEntries, renderScanReport } from './scan.mjs'
12
+ import { MANIFEST_NAME, normalizeManifest, sha256 } from './manifest.mjs'
13
+ import { checkCompatibility } from './compat.mjs'
14
+ import { captureConfigs, collectFiles } from './pack.mjs'
15
+ import { upsertPatchItem, parseYaml } from './yamlish.mjs'
16
+ import {
17
+ ensureDir,
18
+ writeJsonAtomic,
19
+ appendLog,
20
+ pathsFor,
21
+ slugify,
22
+ } from './store.mjs'
23
+ import {
24
+ ensureBundles,
25
+ setBundles,
26
+ readBundles,
27
+ readProfilePackage,
28
+ listInstalled,
29
+ dshVersion,
30
+ patchPath,
31
+ readPatch,
32
+ writePatch,
33
+ runDshPlugin,
34
+ } from './profile.mjs'
35
+
36
+ export class InstallRefused extends Error {
37
+ constructor(message, scan) {
38
+ super(message)
39
+ this.name = 'InstallRefused'
40
+ this.scan = scan
41
+ }
42
+ }
43
+
44
+ const META_ENTRIES = new Set([MANIFEST_NAME, 'README.txt', 'integrity.json'])
45
+ const isMeta = (name) => META_ENTRIES.has(name) || name.startsWith('security/')
46
+
47
+ /**
48
+ * 在内存里检查一个包:解 zip → 找清单 → 校验完整性 → 扫描。
49
+ * 不写任何东西;调用方拿到结果后再决定要不要装。
50
+ */
51
+ export function inspectPackBuffer(buffer, options = {}) {
52
+ const config = options.config || {}
53
+ const notes = []
54
+ const entries = readZip(buffer, {
55
+ maxEntryBytes: config.maxFileBytes ?? 16 * 1024 * 1024,
56
+ maxTotalBytes: config.maxPackBytes ?? 256 * 1024 * 1024,
57
+ })
58
+
59
+ const manifestText = readZipText(entries, MANIFEST_NAME)
60
+ if (!manifestText) throw new Error('这个文件不是 DSH 整合包:缺少 ' + MANIFEST_NAME)
61
+ let raw
62
+ try {
63
+ raw = JSON.parse(manifestText)
64
+ } catch (error) {
65
+ throw new Error('清单无法解析:' + String(error?.message || error))
66
+ }
67
+ const manifest = normalizeManifest(raw)
68
+
69
+ const integrity = { present: false, ok: true, mismatches: [], missing: [] }
70
+ const integrityText = readZipText(entries, 'integrity.json')
71
+ if (integrityText) {
72
+ integrity.present = true
73
+ try {
74
+ const record = JSON.parse(integrityText)
75
+ const files = record && typeof record.files === 'object' ? record.files : {}
76
+ const present = new Map(entries.map((e) => [e.name, e]))
77
+ for (const [name, expected] of Object.entries(files)) {
78
+ const entry = present.get(name)
79
+ if (!entry) { integrity.missing.push(name); continue }
80
+ const actual = sha256(entry.data)
81
+ if (actual !== expected) integrity.mismatches.push(name)
82
+ }
83
+ integrity.ok = integrity.mismatches.length === 0 && integrity.missing.length === 0
84
+ } catch (error) {
85
+ integrity.present = true
86
+ integrity.ok = false
87
+ notes.push('integrity.json 解析失败:' + String(error?.message || error))
88
+ }
89
+ } else {
90
+ integrity.present = false
91
+ integrity.ok = false
92
+ notes.push('包内没有 integrity.json,无法确认文件没被改过(已阻止安装;来源可信时可用「强制」跳过)')
93
+ }
94
+
95
+ const payload = entries.filter((e) => !isMeta(e.name))
96
+ const scan = options.scanBeforeInstall === false
97
+ ? { findings: [], counts: { high: 0, medium: 0, low: 0 }, scannedFiles: 0, scannedBytes: 0, skipped: [], redacted: true, note: '未执行扫描(调用方关闭)' }
98
+ : scanEntries(payload.map((e) => ({ name: e.name, data: e.data })), { extraRules: options.extraScanRules })
99
+ const report = renderScanReport(manifest.name, scan, { approvedRisk: Boolean(options.force) })
100
+
101
+ const blockingReasons = []
102
+ if (!integrity.present && !options.force) {
103
+ blockingReasons.push('包里没有 integrity.json,无法确认文件没被改过')
104
+ }
105
+ if (integrity.present && !integrity.ok) {
106
+ blockingReasons.push('完整性校验失败(' + (integrity.mismatches.length + integrity.missing.length) + ' 个文件对不上)')
107
+ }
108
+ if (scan.counts.high > 0 && !options.force) {
109
+ blockingReasons.push('安全检测发现 ' + scan.counts.high + ' 个高风险项')
110
+ }
111
+
112
+ return { manifest, entries, integrity, scan, report, blockingReasons, notes }
113
+ }
114
+
115
+ /** 从链接读取整合包(只允许 https 与白名单域名)。 */
116
+ export async function readPackFromUrl(url, config, fetchLimitedFn) {
117
+ const buffer = await fetchLimitedFn(url, config, {
118
+ maxBytes: config.maxDownloadBytes ?? 128 * 1024 * 1024,
119
+ accept: 'application/octet-stream, application/zip, */*',
120
+ })
121
+ return buffer
122
+ }
123
+
124
+ function pluginPayload(entries, dirName) {
125
+ const prefix = 'plugins/' + dirName + '/'
126
+ return entries.filter((e) => e.name.startsWith(prefix))
127
+ }
128
+
129
+ /**
130
+ * 把某个插件的文件释放到 vendor 目录,返回可交给 `dsh plugin add file:` 的目录。
131
+ * 目录名带包 id,避免不同整合包互相覆盖。
132
+ */
133
+ export function materializePayload(entries, manifest, plugin, config) {
134
+ const base = pathsFor(config).vendor
135
+ const packDir = path.join(base, slugify(manifest.id || manifest.name || 'pack', 'pack'))
136
+ const target = path.join(packDir, 'plugins', plugin.dirName || plugin.name)
137
+ const files = pluginPayload(entries, plugin.dirName || plugin.name)
138
+ if (files.length === 0) throw new Error(plugin.name + ':包里没有它的文件(轻量版需要用网络取)')
139
+ // 重装时旧文件必须清掉:pnpm 会把目录里的一切都装进去,残留文件会让新版本带上旧代码
140
+ try { fs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }) } catch {}
141
+ ensureDir(target)
142
+ for (const entry of files) {
143
+ const rel = entry.name.slice(('plugins/' + (plugin.dirName || plugin.name) + '/').length)
144
+ const safeRel = safeEntryName(rel)
145
+ const dest = path.join(target, safeRel)
146
+ const resolved = path.resolve(dest)
147
+ if (!resolved.startsWith(path.resolve(target) + path.sep) && resolved !== path.resolve(target)) {
148
+ throw new Error('包内路径逃逸:' + entry.name)
149
+ }
150
+ ensureDir(path.dirname(resolved))
151
+ fs.writeFileSync(resolved, entry.data)
152
+ }
153
+ return target
154
+ }
155
+
156
+ function packDirOf(config, manifest) {
157
+ return path.join(pathsFor(config).vendor, slugify(manifest.id || manifest.name || 'pack', 'pack'))
158
+ }
159
+
160
+ /**
161
+ * 安装整合包。
162
+ * @param {object} input
163
+ * @param {object} input.manifest
164
+ * @param {object[]} input.entries
165
+ * @param {object} input.config
166
+ * @param {object} input.options {force, keepLocal, applyConfig, dryRun}
167
+ * @param {object} input.context {profileDir, onLine}
168
+ */
169
+ export async function installPack(input) {
170
+ const { manifest, entries, config, options = {}, context = {} } = input
171
+ const profileDir = context.profileDir || pathsFor(config).profile
172
+ const profile = config.profile || 'desktop'
173
+ const installed = listInstalled(profileDir)
174
+ const compat = checkCompatibility(manifest.plugins, {
175
+ installed,
176
+ dshVersion: dshVersion(profileDir),
177
+ nodeVersion: process.versions.node,
178
+ config,
179
+ })
180
+
181
+ const actions = []
182
+ const lines = []
183
+ const onLine = typeof context.onLine === 'function' ? context.onLine : () => {}
184
+
185
+ if (compat.blocking && !options.force) {
186
+ return {
187
+ ok: false,
188
+ refused: true,
189
+ reason: '兼容性检测有 ' + compat.counts.error + ' 个阻断问题',
190
+ compat,
191
+ actions,
192
+ lines,
193
+ needsRestart: false,
194
+ }
195
+ }
196
+
197
+ const touchedBundles = []
198
+ const configItems = []
199
+ const packRoot = packDirOf(config, manifest)
200
+ // CLI 自己会把 bundle 登记进 profile;「装好先不启用」靠装完撤回列表实现,所以先记一份原始清单。
201
+ const bundlesBefore = readBundles(readProfilePackage(profileDir))
202
+
203
+ for (const plugin of manifest.plugins) {
204
+ const existing = installed.find((p) => p.name === plugin.name)
205
+ const keepLocal = options.keepLocal !== false && config.keepLocal !== false && manifest.options.keepLocalOnInstall !== false
206
+ if (existing && keepLocal) {
207
+ actions.push({ plugin: plugin.name, action: 'kept', ok: true, message: '本地已装 ' + existing.version + ',按“保留本地修改”跳过覆盖' })
208
+ continue
209
+ }
210
+
211
+ let dir = null
212
+ if (manifest.format === 'full' && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
213
+ try {
214
+ dir = materializePayload(entries, manifest, plugin, config)
215
+ } catch (error) {
216
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: String(error?.message || error) })
217
+ continue
218
+ }
219
+ } else if (typeof context.resolveSource === 'function') {
220
+ try {
221
+ dir = await context.resolveSource(plugin, packRoot)
222
+ } catch (error) {
223
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '取包失败:' + String(error?.message || error) })
224
+ continue
225
+ }
226
+ } else {
227
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '轻量包需要在联网环境下解析来源' })
228
+ continue
229
+ }
230
+
231
+ if (manifest.format !== 'full') {
232
+ // 轻量包本体不夹带源码,真正的代码是刚下载回来的:装之前必须补扫一遍,否则「安装前检测」是空转
233
+ try {
234
+ const brought = collectFiles(dir, {
235
+ prefix: '',
236
+ maxFileBytes: config.maxFileBytes ?? 16 * 1024 * 1024,
237
+ maxTotalBytes: 64 * 1024 * 1024,
238
+ })
239
+ const deep = scanEntries(brought.files, { extraRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
240
+ if (deep.counts.high > 0 && !options.force) {
241
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '从市场取回的代码里有 ' + deep.counts.high + ' 个高风险项,已拦下' })
242
+ continue
243
+ }
244
+ lines.push('轻量包:已补扫从市场取回的 ' + deep.scannedFiles + ' 个文件(高 ' + deep.counts.high + ')')
245
+ } catch (error) {
246
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '补充扫描失败:' + String(error?.message || error) })
247
+ continue
248
+ }
249
+ }
250
+
251
+ if (options.dryRun) {
252
+ actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '演练:将添加 ' + dir })
253
+ continue
254
+ }
255
+
256
+ const runCli = typeof context.runCli === 'function' ? context.runCli : runDshPlugin
257
+ const result = await runCli(profile, ['plugin', '--profile', profile, 'add', 'file:' + dir], {
258
+ cwd: profileDir,
259
+ onLine: (line) => { lines.push(line); onLine(line) },
260
+ })
261
+ appendLog('install ' + plugin.name + ' exit=' + result.code)
262
+ if (result.code !== 0) {
263
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: 'dsh plugin add 失败(退出码 ' + result.code + '),详见日志' })
264
+ continue
265
+ }
266
+ if (plugin.isBundle && plugin.hasPatch) touchedBundles.push(plugin.name)
267
+ actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '已装 ' + (plugin.version || '') })
268
+ }
269
+
270
+ if (!options.dryRun) {
271
+ const before = bundlesBefore
272
+ const after = readBundles(readProfilePackage(profileDir))
273
+ if (options.enableBundles === false) {
274
+ // 沙箱/试验场景:文件与依赖都装好,但不登记 bundle —— 重启也不会加载。
275
+ if (after.length !== before.length || after.some((x) => !before.includes(x))) {
276
+ const restored = setBundles(profileDir, before)
277
+ if (restored) lines.push('按设置未启用:已把 bundle 清单撤回原样(' + touchedBundles.join(', ') + ' 装了但不加载)')
278
+ } else {
279
+ lines.push('按设置未启用:' + (touchedBundles.join(', ') || '本次插件') + ' 没有登记 bundle,重启也不会加载')
280
+ }
281
+ } else if (touchedBundles.length > 0) {
282
+ const ensured = ensureBundles(profileDir, touchedBundles)
283
+ if (ensured.changed) lines.push('已登记 bundle:' + ensured.added.join(', ') + '(原清单备份 ' + ensured.backup + ')')
284
+ }
285
+ }
286
+
287
+ // 配置回填:只改目标条目,其它字节不动
288
+ if (options.applyConfig !== false && manifest.options.includeConfig) {
289
+ const patch = readPatch(profileDir)
290
+ let text = patch
291
+ for (const plugin of manifest.plugins) {
292
+ const snap = manifest.plugins.find((p) => p.name === plugin.name && p.configIncluded)
293
+ if (!snap) continue
294
+ if (options.keepLocal !== false && config.keepLocal !== false) {
295
+ const captured = captureConfigs(text, [snap], (t) => parseYaml(t)).captured
296
+ if (captured.size > 0) {
297
+ actions.push({ plugin: plugin.name, action: 'config', ok: true, message: '本地已有配置,按“保留本地”不覆盖' })
298
+ continue
299
+ }
300
+ }
301
+ const entry = entries.find((e) => e.name === 'configs/' + plugin.name + '.json')
302
+ if (!entry) continue
303
+ let snapConfig
304
+ try { snapConfig = JSON.parse(entry.data.toString('utf8')) } catch { continue }
305
+ const result = upsertPatchItem(text, {
306
+ id: snapConfig.id || plugin.name,
307
+ name: snapConfig.name || plugin.name,
308
+ config: snapConfig.config ?? null,
309
+ disabled: snapConfig.disabled,
310
+ })
311
+ text = result.text
312
+ configItems.push({ plugin: plugin.name, action: result.action })
313
+ actions.push({ plugin: plugin.name, action: 'config', ok: true, message: (result.action === 'replaced' ? '已对齐配置' : '已补上配置条目') })
314
+ }
315
+ if (text !== patch && !options.dryRun) {
316
+ const backup = writePatch(profileDir, text)
317
+ lines.push('配置层已更新,备份:' + backup)
318
+ }
319
+ }
320
+
321
+ const ok = actions.every((a) => a.ok)
322
+ const record = {
323
+ at: new Date().toISOString(),
324
+ kind: 'install',
325
+ pack: manifest.name,
326
+ id: manifest.id,
327
+ format: manifest.format,
328
+ ok,
329
+ actions,
330
+ configItems,
331
+ }
332
+ if (!options.dryRun) writeJsonAtomic(path.join(packRoot, 'install-result.json'), record)
333
+
334
+ return {
335
+ ok,
336
+ compat,
337
+ actions,
338
+ configItems,
339
+ lines,
340
+ needsRestart: options.enableBundles === false ? false : actions.some((a) => a.action === 'install' && a.ok),
341
+ }
342
+ }
343
+
344
+ export { patchPath }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * dsh-modpack —— 整合包清单(dsh-modpack.json)。
3
+ *
4
+ * 清单是整个格式的契约:读的一方只认 `schema` + `kind`,看不到就拒绝;
5
+ * 每一项都有上限,防止一个坏包把界面撑爆。
6
+ */
7
+ import { createHash } from 'node:crypto'
8
+
9
+ export const SCHEMA = 1
10
+ export const KIND = 'dsh-modpack'
11
+ export const MANIFEST_NAME = 'dsh-modpack.json'
12
+
13
+ export const sha256 = (buf) => createHash('sha256').update(buf).digest('hex')
14
+ export const shortHash = (buf) => sha256(buf).slice(0, 16)
15
+
16
+ const str = (v, max = 200) => (typeof v === 'string' ? v.slice(0, max) : '')
17
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0)
18
+ const bool = (v) => v === true
19
+
20
+ function normalizePlugin(raw) {
21
+ if (!raw || typeof raw !== 'object') throw new Error('插件条目不是对象')
22
+ const name = str(raw.name, 214)
23
+ if (!/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/iu.test(name)) throw new Error('插件名不合法:' + name)
24
+ const config = raw.config && typeof raw.config === 'object' && !Array.isArray(raw.config) ? raw.config : null
25
+ const peers = raw.peerDependencies && typeof raw.peerDependencies === 'object' ? raw.peerDependencies : {}
26
+ const peerList = {}
27
+ for (const [key, value] of Object.entries(peers).slice(0, 100)) {
28
+ if (typeof key === 'string' && typeof value === 'string') peerList[key] = value.slice(0, 200)
29
+ }
30
+ return {
31
+ name,
32
+ version: str(raw.version, 64) || '0.0.0',
33
+ requested: str(raw.requested, 64),
34
+ source: ['profile', 'npm', 'file', 'url', 'vendor'].includes(raw.source) ? raw.source : 'npm',
35
+ registry: str(raw.registry, 300),
36
+ tarball: str(raw.tarball, 500),
37
+ integrity: str(raw.integrity, 200),
38
+ license: str(raw.license, 80),
39
+ repository: str(raw.repository, 300),
40
+ author: str(raw.author, 120),
41
+ files: num(raw.files),
42
+ size: num(raw.size),
43
+ hasClient: bool(raw.hasClient),
44
+ hasPatch: bool(raw.hasPatch),
45
+ isBundle: raw.isBundle !== false,
46
+ localEdits: bool(raw.localEdits),
47
+ // 老包没有 mode 字段,用 localEdits 兜底
48
+ mode: raw.mode === 'local' ? 'local' : raw.mode === 'base' ? 'base' : bool(raw.localEdits) ? 'local' : 'base',
49
+ configIncluded: bool(raw.configIncluded),
50
+ dataIncluded: bool(raw.dataIncluded),
51
+ peerDependencies: peerList,
52
+ engines: raw.engines && typeof raw.engines === 'object' ? raw.engines : {},
53
+ // pnpm 别名 / link 安装时目录名可能不等于包名,payload 前缀以它为准
54
+ dirName: (() => {
55
+ const value = str(raw.dirName, 200)
56
+ return /^[@A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)?$/u.test(value) ? value : ''
57
+ })(),
58
+ config,
59
+ note: str(raw.note, 300),
60
+ }
61
+ }
62
+
63
+ export function normalizeManifest(raw) {
64
+ if (!raw || typeof raw !== 'object') throw new Error('清单不是对象')
65
+ if (raw.schema !== SCHEMA) throw new Error('不支持的清单版本:' + String(raw.schema))
66
+ if (raw.kind !== KIND) throw new Error('不是 dsh 整合包:kind=' + String(raw.kind))
67
+ const plugins = Array.isArray(raw.plugins) ? raw.plugins.slice(0, 200).map(normalizePlugin) : []
68
+ if (plugins.length === 0) throw new Error('整合包里没有插件')
69
+ const seen = new Set()
70
+ for (const p of plugins) {
71
+ if (seen.has(p.name)) throw new Error('重复插件:' + p.name)
72
+ seen.add(p.name)
73
+ }
74
+ const format = raw.format === 'full' ? 'full' : 'lite'
75
+ return {
76
+ schema: SCHEMA,
77
+ kind: KIND,
78
+ format,
79
+ id: str(raw.id, 80),
80
+ name: str(raw.name, 120) || '未命名整合包',
81
+ description: str(raw.description, 2000),
82
+ author: str(raw.author, 120),
83
+ license: str(raw.license, 80),
84
+ homepage: str(raw.homepage, 300),
85
+ createdAt: str(raw.createdAt, 40) || new Date().toISOString(),
86
+ generator: {
87
+ name: str(raw.generator?.name, 80) || 'dsh-modpack',
88
+ version: str(raw.generator?.version, 40) || '0.0.0',
89
+ },
90
+ dshVersion: str(raw.dshVersion, 40),
91
+ options: {
92
+ includePayload: format === 'full',
93
+ includeConfig: raw.options ? bool(raw.options.includeConfig) : true,
94
+ includeLocalEdits: raw.options ? bool(raw.options.includeLocalEdits) : false,
95
+ keepLocalOnInstall: raw.options ? raw.options.keepLocalOnInstall !== false : true,
96
+ },
97
+ plugins,
98
+ files: Array.isArray(raw.files)
99
+ ? raw.files.slice(0, 5000).map((f) => ({ path: str(f.path, 500), sha256: str(f.sha256, 64), size: num(f.size) })).filter((f) => f.path && f.sha256)
100
+ : [],
101
+ security: {
102
+ scanned: raw.security ? raw.security.scanned === true : false,
103
+ high: num(raw.security?.high),
104
+ medium: num(raw.security?.medium),
105
+ low: num(raw.security?.low),
106
+ approvedRisk: bool(raw.security?.approvedRisk),
107
+ note: str(raw.security?.note, 500),
108
+ },
109
+ install: {
110
+ restartRequired: true,
111
+ notes: Array.isArray(raw.install?.notes) ? raw.install.notes.slice(0, 30).map((n) => str(n, 300)) : [],
112
+ },
113
+ extensions: raw.extensions && typeof raw.extensions === 'object' ? raw.extensions : {},
114
+ }
115
+ }
116
+
117
+ export function pluginSummary(manifest) {
118
+ return {
119
+ name: manifest.name,
120
+ format: manifest.format,
121
+ plugins: manifest.plugins.length,
122
+ createdAt: manifest.createdAt,
123
+ dshVersion: manifest.dshVersion,
124
+ bytes: manifest.files.reduce((sum, f) => sum + (f.size || 0), 0),
125
+ payloadBytes: manifest.plugins.reduce((sum, p) => sum + (p.size || 0), 0),
126
+ security: manifest.security,
127
+ }
128
+ }
129
+
130
+ /** 给人看的 README.txt:不装本插件也能照着装。 */
131
+ export function buildReadme(manifest, extra = {}) {
132
+ const lines = []
133
+ lines.push('DSH 整合包 —— ' + manifest.name)
134
+ lines.push('='.repeat(60))
135
+ if (manifest.description) {
136
+ lines.push('')
137
+ for (const line of manifest.description.split(/\r?\n/u)) lines.push(line)
138
+ }
139
+ lines.push('')
140
+ lines.push('格式:' + manifest.format + '(' + (manifest.format === 'full' ? '完整版:包含插件本体,任何工具解压即可读' : '轻量版:只有清单,需要 dsh-modpack 插件联网安装') + ')')
141
+ lines.push('生成:' + manifest.createdAt + ' 生成器:' + manifest.generator.name + ' ' + manifest.generator.version)
142
+ if (manifest.author) lines.push('打包者:' + manifest.author)
143
+ if (manifest.dshVersion) lines.push('打包时 DSH 版本:' + manifest.dshVersion)
144
+ lines.push('')
145
+ lines.push('包含的插件(' + manifest.plugins.length + ' 个)')
146
+ for (const p of manifest.plugins) {
147
+ lines.push(' · ' + p.name + '@' + p.version + (p.license ? ' [' + p.license + ']' : ' [未标注 license]') + (p.localEdits ? ' (含打包者的本地修改)' : ''))
148
+ }
149
+ lines.push('')
150
+ lines.push('安全检测')
151
+ lines.push(' 扫描:' + (manifest.security.scanned ? '已执行' : '未执行') + ',高风险 ' + manifest.security.high + ' / 中 ' + manifest.security.medium + ' / 低 ' + manifest.security.low)
152
+ lines.push(' 报告:security/report.txt(片段已打码;命中的原始内容没有落盘)')
153
+ lines.push(' 提醒:静态检测不是杀毒,未命中不代表保证安全;安装前请自行确认来源。')
154
+ lines.push('')
155
+ lines.push('怎么装')
156
+ if (manifest.format === 'lite') {
157
+ lines.push(' 1. 在 DSH 里安装 dsh-modpack 插件;')
158
+ lines.push(' 2. 侧栏打开「整合包 → 安装」,选择本文件或粘贴下载链接;')
159
+ lines.push(' 3. 按提示确认安全扫描与兼容性结果,然后安装。')
160
+ } else {
161
+ lines.push(' 方式 A(推荐,有 dsh-modpack 插件):侧栏「整合包 → 安装」选择本文件,会校验完整性、')
162
+ lines.push(' 重新扫描安全项、检查兼容性,并把打包时保存的配置同步回来。')
163
+ lines.push(' 方式 B(没有装 dsh-modpack,也能装):')
164
+ lines.push(' 1. 解压本 zip;')
165
+ lines.push(' 2. 对 plugins/ 下每个目录执行:')
166
+ lines.push(' dsh plugin --profile <你的profile> add file:<本机绝对路径>/plugins/<插件名>')
167
+ lines.push(' 3. 把插件名追加到 ~/.dsh/profiles/<你的profile>/package.json 的 dsh.profile.bundles;')
168
+ lines.push(' 4. 配好的选项在 configs/ 里,按 cordis.patch.yml 的格式手工合并;')
169
+ lines.push(' 5. 重启 DSH。')
170
+ }
171
+ lines.push('')
172
+ lines.push('目录结构')
173
+ lines.push(' dsh-modpack.json 清单(机器可读,schema ' + SCHEMA + ')')
174
+ lines.push(' integrity.json 每个文件的 sha256')
175
+ lines.push(' security/ 安全检测报告(已打码)')
176
+ lines.push(' configs/ 打包时的非默认配置(每个插件一个 json)')
177
+ if (manifest.format === 'full') lines.push(' plugins/ 插件本体,一个目录一个插件')
178
+ lines.push(' data/ 插件数据快照(如果打包时选了保留)')
179
+ lines.push('')
180
+ lines.push('合规与免责')
181
+ lines.push(' · 整合包只应包含你有权再分发的插件;每个插件的 license 列在上面,')
182
+ lines.push(' 原作者的版权仍归原作者,分发前请自行确认许可条款。')
183
+ lines.push(' · 包里不包含账号凭证;打包时检测到疑似凭证的文件不会被打进去。')
184
+ lines.push(' · 不绕过任何官方渠道,不提供破解、破解依赖或规避授权的功能。')
185
+ lines.push(' · 使用前请遵守所在地法律与 B 站/DeepSeek 等平台的服务条款。')
186
+ lines.push('')
187
+ if (extra.footer) lines.push(extra.footer)
188
+ return lines.join('\n')
189
+ }