dsh-modpack-kit 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,172 @@
1
+ /**
2
+ * @file lib/annotate.mjs
3
+ * @role 读「代码标注」:把每个源文件头部那段 @file 注释解析成结构化信息,并检查有没有漏标
4
+ * @sub 解析标注块, 列出要标注的运行文件, 汇总成树, 检查缺哪些键
5
+ * @exports api:parseAnnotation, readAnnotation, runtimeFiles, collectAnnotations, checkAnnotations, ANNOTATE_KEYS
6
+ * @uses 无(只用 node:fs / node:path,谁都能引,不依赖插件别处)
7
+ * @reads 插件目录下的 .js/.mjs 源码(只读,不改内容)
8
+ * @writes 不写任何文件
9
+ * @risk 改了键名就等于改了全仓 26 个文件的头部格式:解析器与 check 必须一起改,否则「代码标注」面板会整片报缺
10
+ * @touch 加键 → 同步 lib/annotate.mjs 的 ANNOTATE_KEYS、dev/tools/annotate-files.cjs 的写入表、docs/CODE-MAP.md 的说明
11
+ * @since 0.3.0
12
+ */
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+
16
+ // 标注块里认的键。顺序就是界面上展示的顺序:先「是什么」,再「怎么用」,最后「改它注意什么」。
17
+ export const ANNOTATE_KEYS = ['file', 'role', 'sub', 'exports', 'api', 'uses', 'reads', 'writes', 'risk', 'touch', 'since']
18
+
19
+ // 每个源文件都必须有的键:没有 @role 读的人不知道这文件干嘛,没有 @risk/@touch 改的人不知道会踩什么。
20
+ export const REQUIRED_KEYS = ['file', 'role', 'risk', 'touch']
21
+
22
+ const KEY_RE = /^ \* @([a-zA-Z]+)[ \t]+(.*)$/u
23
+ const CONT_RE = /^ \*[ \t]{2,}(?!@)(.*)$/u
24
+
25
+ function splitList(text) {
26
+ return String(text || '')
27
+ .split(/[、,,]/u)
28
+ .map((item) => item.trim())
29
+ .filter(Boolean)
30
+ }
31
+
32
+ /**
33
+ * 从文件正文里找带 @file 的那段注释块并解析。
34
+ * @returns {{file: string, role: string, sub: string[], exports: string[], api: string[], uses: string[], reads: string, writes: string, risk: string, touch: string, since: string, line: number, raw: string} | null}
35
+ */
36
+ export function parseAnnotation(text, fallbackFile = '') {
37
+ const lines = String(text || '').split(/\r?\n/u)
38
+ // 只往文件头部找(前 80 行):头部之外不可能再有标注块,扫全文只是浪费
39
+ const limit = Math.min(lines.length, 80)
40
+ for (let start = 0; start < limit; start += 1) {
41
+ if (lines[start].trim() !== '/**') continue
42
+ let end = -1
43
+ for (let i = start + 1; i < Math.min(lines.length, start + 80); i += 1) {
44
+ if (lines[i].trim() === '*/') { end = i; break }
45
+ }
46
+ if (end < 0) continue
47
+ const body = lines.slice(start + 1, end)
48
+ if (!body.some((line) => /@file\b/u.test(line))) continue
49
+ const values = {}
50
+ const raw = body.join('\n')
51
+ let currentKey = ''
52
+ for (const line of body) {
53
+ const hit = line.match(KEY_RE)
54
+ if (hit) {
55
+ currentKey = hit[1].toLowerCase()
56
+ values[currentKey] = hit[2].trim()
57
+ continue
58
+ }
59
+ const cont = line.match(CONT_RE)
60
+ if (cont && currentKey) {
61
+ values[currentKey] = (values[currentKey] ? values[currentKey] + ' ' : '') + cont[1].trim()
62
+ }
63
+ }
64
+ return {
65
+ file: values.file || fallbackFile,
66
+ role: values.role || '',
67
+ sub: splitList(values.sub),
68
+ exports: splitList(values.exports),
69
+ api: splitList(values.api),
70
+ uses: splitList(values.uses),
71
+ reads: values.reads || '',
72
+ writes: values.writes || '',
73
+ risk: values.risk || '',
74
+ touch: values.touch || '',
75
+ since: values.since || '',
76
+ line: start + 1,
77
+ raw,
78
+ }
79
+ }
80
+ return null
81
+ }
82
+
83
+ /** 读一个文件并解析它的标注;读不到就返回 null。 */
84
+ export function readAnnotation(fileAbs, fallbackFile = '') {
85
+ try {
86
+ return parseAnnotation(fs.readFileSync(fileAbs, 'utf8'), fallbackFile)
87
+ } catch {
88
+ return null
89
+ }
90
+ }
91
+
92
+ // 要标注的范围:插件真正会加载的代码。界面、服务端、两个附属小插件;docs/test/dev 不算。
93
+ const CODE_DIRS = ['lib', 'community', 'annotate', 'plugin-tree']
94
+ const CODE_FILES = ['index.js', 'client.js']
95
+
96
+ function walk(dir, root, out) {
97
+ let entries = []
98
+ try {
99
+ entries = fs.readdirSync(dir, { withFileTypes: true })
100
+ } catch {
101
+ return out
102
+ }
103
+ for (const entry of entries) {
104
+ const abs = path.join(dir, entry.name)
105
+ if (entry.isDirectory()) {
106
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue
107
+ walk(abs, root, out)
108
+ } else if (/\.(?:mjs|cjs|js)$/u.test(entry.name)) {
109
+ out.push(path.relative(root, abs).split(path.sep).join('/'))
110
+ }
111
+ }
112
+ return out
113
+ }
114
+
115
+ /** 列出所有应当带标注的运行文件(相对插件根,正斜杠)。 */
116
+ export function runtimeFiles(root) {
117
+ const out = []
118
+ for (const name of CODE_FILES) {
119
+ if (fs.existsSync(path.join(root, name))) out.push(name)
120
+ }
121
+ for (const dir of CODE_DIRS) {
122
+ walk(path.join(root, dir), root, out)
123
+ }
124
+ return out.sort()
125
+ }
126
+
127
+ /** 汇总所有标注:给「代码标注」附属小插件与界面用。 */
128
+ export function collectAnnotations(root, options = {}) {
129
+ const files = options.files || runtimeFiles(root)
130
+ const items = []
131
+ const missing = []
132
+ const problems = []
133
+ for (const rel of files) {
134
+ const parsed = readAnnotation(path.join(root, rel), rel)
135
+ if (!parsed) {
136
+ missing.push(rel)
137
+ continue
138
+ }
139
+ let lines = 0
140
+ try {
141
+ lines = fs.readFileSync(path.join(root, rel), 'utf8').split(/\r?\n/u).length
142
+ } catch {}
143
+ if (parsed.file !== rel) problems.push({ file: rel, problem: '标注里的 @file 与文件路径对不上:' + parsed.file })
144
+ const lacking = REQUIRED_KEYS.filter((key) => !parsed[key] || (Array.isArray(parsed[key]) && !parsed[key].length))
145
+ if (lacking.length) problems.push({ file: rel, problem: '缺 ' + lacking.map((key) => '@' + key).join(' ') })
146
+ items.push({ rel, lines, ...parsed })
147
+ }
148
+ const byDir = {}
149
+ for (const item of items) {
150
+ const dir = item.rel.includes('/') ? item.rel.slice(0, item.rel.lastIndexOf('/')) : '.'
151
+ byDir[dir] = (byDir[dir] || 0) + 1
152
+ }
153
+ return {
154
+ root,
155
+ files: items,
156
+ missing,
157
+ problems,
158
+ counts: { annotated: items.length, missing: missing.length, problems: problems.length, dirs: byDir },
159
+ }
160
+ }
161
+
162
+ /** 检查:给测试与界面的「自检」按钮用。 */
163
+ export function checkAnnotations(root) {
164
+ const summary = collectAnnotations(root)
165
+ return {
166
+ ok: summary.missing.length === 0 && summary.problems.length === 0,
167
+ checked: summary.files.length + summary.missing.length,
168
+ annotated: summary.files.length,
169
+ missing: summary.missing,
170
+ problems: summary.problems,
171
+ }
172
+ }
package/lib/classify.mjs CHANGED
@@ -1,3 +1,14 @@
1
+ /**
2
+ * @file lib/classify.mjs
3
+ * @role 旧分类兜底:市场目录没有分类时,按包名/描述关键词猜一个大类
4
+ * @sub 分类
5
+ * @exports CATEGORIES / classifyPlugin / categoryLabel
6
+ * @reads 插件包名与描述(内存里传入)
7
+ * @risk 分类 id 必须与插件市场目录一致,猜错会让「水槽」统计跟着错
8
+ * @touch 改分类表要同步 lib/market-catalog.mjs 的 CATEGORY_FALLBACK 与客户端 CATEGORY_LABELS
9
+ * @since 0.3.0
10
+ */
11
+
1
12
  /**
2
13
  * 分类:插件市场有分区,本插件照同一套分类给「本机已装」和「市场目录」打标签,
3
14
  * 让两边在同一张列表里能按类筛。纯字符串匹配,无网络、无副作用。
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @file lib/community.mjs
3
+ * @role 附属小插件「社区资源」的登记与开关解析:内置清单、是否被换成外部实现、当前是否启用
4
+ * @sub 社区资源
5
+ * @exports COMMUNITY_ID / COMMUNITY_API / readBuiltinManifest / resolveCommunity
6
+ * @reads community/manifest.json、profile 里是否装了同名外部实现
7
+ * @risk 关掉社区资源只该让社区那一层 404,不该影响打包/安装——判断错会把主体一起关掉
8
+ * @touch 改接口版本要同步 community/manifest.json 与 lib/subplugins.mjs 的登记表
9
+ * @since 0.3.0
10
+ */
11
+
12
+ /**
13
+ * 附属小插件(社区资源)的宿主侧支持。
14
+ *
15
+ * 只做两件事:
16
+ * 1. 读内置清单 community/manifest.json,给 status.community 提供 builtin 信息;
17
+ * 2. 看 profile 里有没有声明兼容的外部实现(包名 dsh-modpack-community + community.json),
18
+ * 有就标成 external。外部实现只公开信息、不改主体行为,出问题也退得回内置。
19
+ */
20
+ import fs from 'node:fs'
21
+ import path from 'node:path'
22
+
23
+ export const COMMUNITY_ID = 'dsh-modpack-community'
24
+ export const COMMUNITY_API = 1
25
+
26
+ const builtinManifest = new URL('../community/manifest.json', import.meta.url)
27
+
28
+ export function readBuiltinManifest() {
29
+ try {
30
+ return JSON.parse(fs.readFileSync(builtinManifest, 'utf8'))
31
+ } catch {
32
+ return { id: COMMUNITY_ID, apiVersion: COMMUNITY_API, name: '社区资源', routes: [] }
33
+ }
34
+ }
35
+
36
+ function readExternal(profileDir) {
37
+ if (!profileDir) return null
38
+ const file = path.join(profileDir, 'node_modules', COMMUNITY_ID, 'community.json')
39
+ try {
40
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
41
+ if (!raw || raw.id !== COMMUNITY_ID) return null
42
+ const apiVersion = Number(raw.apiVersion)
43
+ if (!Number.isFinite(apiVersion) || apiVersion < 1) return null
44
+ return { raw, apiVersion, file }
45
+ } catch {
46
+ return null
47
+ }
48
+ }
49
+
50
+ /**
51
+ * @returns {{id: string, mode: 'builtin'|'external', apiVersion: number, version: string, enabled: boolean, reason?: string, routes: string[]}}
52
+ */
53
+ export function resolveCommunity(profileDir, config = {}) {
54
+ const builtin = readBuiltinManifest()
55
+ const enabled = config.showModpackMarket !== false
56
+ const apiVersion = Number(builtin.apiVersion) || COMMUNITY_API
57
+ const external = readExternal(profileDir)
58
+ if (external && external.apiVersion <= apiVersion) {
59
+ return {
60
+ id: COMMUNITY_ID,
61
+ mode: 'external',
62
+ apiVersion: external.apiVersion,
63
+ version: String(external.raw.version || ''),
64
+ enabled,
65
+ routes: Array.isArray(builtin.routes) ? builtin.routes : [],
66
+ }
67
+ }
68
+ return {
69
+ id: COMMUNITY_ID,
70
+ mode: 'builtin',
71
+ apiVersion,
72
+ version: '',
73
+ enabled,
74
+ ...(external ? { reason: '外部实现声明的 apiVersion 比宿主新(' + external.apiVersion + ' > ' + apiVersion + '),继续用内置实现' } : {}),
75
+ routes: Array.isArray(builtin.routes) ? builtin.routes : [],
76
+ }
77
+ }
package/lib/compat.mjs CHANGED
@@ -1,3 +1,14 @@
1
+ /**
2
+ * @file lib/compat.mjs
3
+ * @role 兼容检查:打包前看选中插件之间、与宿主 DSH 版本有没有冲突(peer 依赖、重复包、废弃插件)
4
+ * @sub 兼容检测
5
+ * @exports checkCompatibility
6
+ * @reads 已装插件的 package.json 与市场目录里的条目
7
+ * @risk 这里只出建议、不阻断;写成阻断会让老用户的包打不出来
8
+ * @touch 新增检查项要同步打包结果里的 compat 字段与客户端「检测报告」渲染
9
+ * @since 0.3.0
10
+ */
11
+
1
12
  /**
2
13
  * dsh-modpack —— 兼容性检查。
3
14
  *
package/lib/github.mjs ADDED
@@ -0,0 +1,300 @@
1
+ /**
2
+ * @file lib/github.mjs
3
+ * @role GitHub 写接口:一键上传整合包(先 fork、建 Release、传资产、改词条、开 PR)
4
+ * @sub 社区资源上传、GitHub
5
+ * @exports gh / whoAmI / ensureFork / openPackPullRequest / entryFileName / packFileName / ensureRelease / uploadReleaseAsset
6
+ * @reads 用户显式给的 token(只存内存)、目录仓库的文件列表
7
+ * @risk token 只在内存里,任务结束必须清;本机直连 github.com 常被重置,写入一律走 POST 数据接口而不是 git push
8
+ * @touch 改上传流程要同步 index.js 的 /upload/* 路由与 client.js 的上传面板;token 生命周期改动要复查 /upload/status
9
+ * @since 0.3.0
10
+ */
11
+
12
+ import { execFile } from 'node:child_process'
13
+ import fs from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+
17
+ /**
18
+ * 只做 GitHub API 的那点事:用 curl 发请求(本机 Node 的 fetch 走代理会证书失败,
19
+ * curl 带 --ssl-no-revoke 是唯一稳的路子)。所有函数都返回解析后的 JSON。
20
+ */
21
+
22
+ const API = 'https://api.github.com'
23
+ const USER_AGENT = 'dsh-modpack-kit'
24
+
25
+ function run(args, input) {
26
+ return new Promise((resolve, reject) => {
27
+ const child = execFile('curl', args, { maxBuffer: 64 * 1024 * 1024, encoding: 'buffer' }, (error, stdout, stderr) => {
28
+ if (error) {
29
+ reject(new Error('curl 失败:' + String(error.message || error) + ' ' + String((stderr || '').toString('utf8')).slice(0, 300)))
30
+ return
31
+ }
32
+ resolve(stdout)
33
+ })
34
+ if (input !== undefined && child.stdin) {
35
+ child.stdin.end(input)
36
+ }
37
+ })
38
+ }
39
+
40
+ /** 调一次 API。method 大写,body 是对象或 undefined。 */
41
+ export async function gh(token, method, path, body) {
42
+ if (!token) throw new Error('还没有 GitHub 凭据:先在社区资源的上传页里填一次 token')
43
+ const args = [
44
+ '-sS',
45
+ '--ssl-no-revoke',
46
+ '-X', method,
47
+ '-H', 'accept: application/vnd.github+json',
48
+ '-H', 'authorization: Bearer ' + token,
49
+ '-H', 'user-agent: ' + USER_AGENT,
50
+ '-H', 'x-github-api-version: 2022-11-28',
51
+ '-w', '\n%{http_code}',
52
+ API + path,
53
+ ]
54
+ let input
55
+ if (body !== undefined) {
56
+ args.push('-H', 'content-type: application/json', '--data-binary', '@-')
57
+ input = JSON.stringify(body)
58
+ }
59
+ const out = (await run(args, input)).toString('utf8')
60
+ const index = out.lastIndexOf('\n')
61
+ const text = index >= 0 ? out.slice(0, index) : ''
62
+ const status = Number(index >= 0 ? out.slice(index + 1).trim() : '0')
63
+ let data = null
64
+ try {
65
+ data = text ? JSON.parse(text) : null
66
+ } catch {
67
+ data = null
68
+ }
69
+ if (status < 200 || status >= 300) {
70
+ const message = (data && (data.message || data.error)) || text.slice(0, 300) || 'HTTP ' + status
71
+ const error = new Error('GitHub 接口返回 ' + status + ':' + message)
72
+ error.status = status
73
+ error.data = data
74
+ throw error
75
+ }
76
+ return data
77
+ }
78
+
79
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
80
+
81
+ /** 拿到当前 token 是谁。 */
82
+ export async function whoAmI(token) {
83
+ const user = await gh(token, 'GET', '/user')
84
+ return { login: user.login, name: user.name || '' }
85
+ }
86
+
87
+ /** 确保 fork 存在(已存在就直接用),返回 fork 的 owner/name。 */
88
+ export async function ensureFork(token, catalog, login, onStep) {
89
+ const [owner, name] = String(catalog).split('/')
90
+ const forkPath = '/repos/' + login + '/' + name
91
+ try {
92
+ const repo = await gh(token, 'GET', forkPath)
93
+ if (onStep) onStep('已经有 fork:' + login + '/' + name)
94
+ return { owner: login, name, exists: true, parent: repo.parent ? repo.parent.full_name : catalog }
95
+ } catch (error) {
96
+ if (error.status !== 404) throw error
97
+ }
98
+ if (onStep) onStep('正在 fork 目录仓库…')
99
+ await gh(token, 'POST', '/repos/' + owner + '/' + name + '/forks', {})
100
+ for (let attempt = 0; attempt < 20; attempt += 1) {
101
+ await sleep(1500)
102
+ try {
103
+ const repo = await gh(token, 'GET', forkPath)
104
+ if (onStep) onStep('fork 好了:' + login + '/' + name)
105
+ return { owner: login, name, exists: false, parent: repo.parent ? repo.parent.full_name : catalog }
106
+ } catch (error) {
107
+ if (error.status !== 404) throw error
108
+ }
109
+ }
110
+ throw new Error('fork 建好后十分钟内还没出现,去 GitHub 网页上看一眼再重试')
111
+ }
112
+
113
+ /** 在一棵新分支上放两个新文件(包 + 条目),然后开 PR。 */
114
+ export async function openPackPullRequest(options) {
115
+ const { token, catalog, login, branch, packPath, packBase64, entryPath, entryText, title, body, onStep } = options
116
+ const [upstreamOwner, upstreamName] = String(catalog).split('/')
117
+ const fork = await ensureFork(token, catalog, login, onStep)
118
+ const repoPath = '/repos/' + fork.owner + '/' + fork.name
119
+
120
+ // 分支:已存在就换一个后缀,避免顶掉上一轮
121
+ let branchName = branch
122
+ let branchReady = false
123
+ for (let attempt = 0; attempt < 5; attempt += 1) {
124
+ try {
125
+ const ref = await gh(token, 'GET', repoPath + '/git/ref/heads/main')
126
+ const sha = ref.object.sha
127
+ await gh(token, 'POST', repoPath + '/git/refs', { ref: 'refs/heads/' + branchName, sha })
128
+ if (onStep) onStep('从 main 开了分支 ' + branchName)
129
+ branchReady = true
130
+ break
131
+ } catch (error) {
132
+ if (error.status === 422) {
133
+ branchName = branchName + '-' + Date.now().toString(36).slice(-4)
134
+ continue
135
+ }
136
+ throw error
137
+ }
138
+ }
139
+ if (!branchReady) throw new Error('分支建不出来(连续 5 次撞名):隔一分钟再传,或去 fork 里删几个旧分支')
140
+
141
+ // GitHub 的 contents API 对「已存在的文件」要求带 sha;我们是在新分支上写新文件,
142
+ // 撞名的唯一可能是 main 上已经有同名条目/包——提前查一次,给一句能照做的话。
143
+ const ensureFresh = async (filePath, what) => {
144
+ const encoded = String(filePath).split('/').map((part) => encodeURIComponent(part)).join('/')
145
+ try {
146
+ await gh(token, 'GET', repoPath + '/contents/' + encoded + '?ref=' + encodeURIComponent(branchName))
147
+ throw new Error('目录里已经有' + what + '(' + filePath + '):换一个包名(id 由文件名生成),或先去 ' + catalog + ' 删掉旧的那份再传')
148
+ } catch (error) {
149
+ if (error && error.status === 404) return
150
+ throw error
151
+ }
152
+ }
153
+
154
+ // 包放 Release 时 packPath 是空串:PR 里只带条目,包已经传进使用者自己的 Release
155
+ if (packPath) {
156
+ await ensureFresh(packPath, '这个包文件')
157
+
158
+ if (onStep) onStep('正在放包文件(' + Math.round(packBase64.length * 0.75 / 1024) + ' KB)…')
159
+ await gh(token, 'PUT', repoPath + '/contents/' + packPath, {
160
+ message: 'catalog: add ' + packPath.split('/').pop(),
161
+ content: packBase64,
162
+ branch: branchName,
163
+ })
164
+ }
165
+
166
+ // 封面:可选的第三份文件,放在 covers/ 下,条目里用 cover 指过来
167
+ if (options.coverPath && options.coverBase64) {
168
+ await ensureFresh(options.coverPath, '这张封面')
169
+ if (onStep) onStep('正在放封面图(' + Math.round(options.coverBase64.length * 0.75 / 1024) + ' KB)…')
170
+ await gh(token, 'PUT', repoPath + '/contents/' + options.coverPath, {
171
+ message: 'catalog: add cover for ' + (options.packId || 'pack'),
172
+ content: options.coverBase64,
173
+ branch: branchName,
174
+ })
175
+ }
176
+
177
+ if (onStep) onStep('正在写条目…')
178
+ await ensureFresh(entryPath, '这个条目')
179
+ await gh(token, 'PUT', repoPath + '/contents/' + entryPath, {
180
+ message: 'catalog: add entry ' + entryPath.split('/').pop(),
181
+ content: Buffer.from(entryText, 'utf8').toString('base64'),
182
+ branch: branchName,
183
+ })
184
+
185
+ if (onStep) onStep('正在开 PR…')
186
+ const pr = await gh(token, 'POST', '/repos/' + upstreamOwner + '/' + upstreamName + '/pulls', {
187
+ title,
188
+ head: fork.owner + ':' + branchName,
189
+ base: 'main',
190
+ body,
191
+ })
192
+ return { url: pr.html_url, number: pr.number, branch: branchName, fork: fork.owner + '/' + fork.name }
193
+ }
194
+
195
+ export function entryFileName(id) {
196
+ return 'data/packs/' + id + '.json'
197
+ }
198
+
199
+ // 只给文件名:目录仓库里放在 packs/ 下,Release 里就是资产名。
200
+ // 不要在这里带 'packs/' —— 条目里的 file 字段只认裸文件名。
201
+ export function packFileName(id, strategy) {
202
+ return id + '-' + strategy + '.dshpack'
203
+ }
204
+
205
+ /** 发一个二进制请求(Release 资产上传走 uploads.github.com,不能套 JSON 那套)。 */
206
+ function runRaw(args) {
207
+ return new Promise((resolve, reject) => {
208
+ const child = execFile('curl', args, { maxBuffer: 8 * 1024 * 1024, encoding: 'buffer' }, (error, stdout, stderr) => {
209
+ if (error) {
210
+ reject(new Error('curl 失败:' + String(error.message || error) + ' ' + String((stderr || '').toString('utf8')).slice(0, 300)))
211
+ return
212
+ }
213
+ resolve(stdout)
214
+ })
215
+ if (child.stdin) child.stdin.end()
216
+ })
217
+ }
218
+
219
+ function parseStatus(out) {
220
+ const text = out.toString('utf8')
221
+ const index = text.lastIndexOf('\n')
222
+ const body = index >= 0 ? text.slice(0, index) : ''
223
+ const status = Number(index >= 0 ? text.slice(index + 1).trim() : '0')
224
+ let data = null
225
+ try { data = body ? JSON.parse(body) : null } catch { data = null }
226
+ return { status, data, body }
227
+ }
228
+
229
+ /** 确保某个仓库里有一个叫 tag 的 Release(没有就建),返回 id。 */
230
+ export async function ensureRelease(token, repo, tag, name, onStep) {
231
+ try {
232
+ const found = await gh(token, 'GET', '/repos/' + repo + '/releases/tags/' + encodeURIComponent(tag))
233
+ if (found && found.id) {
234
+ if (onStep) onStep('已经有 Release ' + tag + ':' + (found.html_url || ''))
235
+ return { id: found.id, tag, created: false, url: found.html_url || '' }
236
+ }
237
+ } catch (error) {
238
+ if (error.status !== 404) throw error
239
+ }
240
+ const created = await gh(token, 'POST', '/repos/' + repo + '/releases', {
241
+ tag_name: tag,
242
+ name: name || tag,
243
+ body: '由 dsh-modpack-kit 上传的整合包;这个 Release 的资产下载数就是「真实下载量」。',
244
+ draft: false,
245
+ prerelease: false,
246
+ })
247
+ if (onStep) onStep('建了 Release ' + tag + ':' + (created.html_url || ''))
248
+ return { id: created.id, tag, created: true, url: created.html_url || '' }
249
+ }
250
+
251
+ /** 把包作为资产传进 Release(重名会先删旧的,免得一个 Release 里堆一串同名)。 */
252
+ export async function uploadReleaseAsset(token, repo, releaseId, name, buffer, onStep) {
253
+ const uploadUrl = 'https://uploads.github.com/repos/' + repo + '/releases/' + releaseId + '/assets?name=' + encodeURIComponent(name)
254
+ const post = async () => {
255
+ const file = path.join(os.tmpdir(), 'dshpack-asset-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8) + '.bin')
256
+ fs.writeFileSync(file, buffer)
257
+ try {
258
+ const out = await runRaw([
259
+ '-sS', '--ssl-no-revoke', '-X', 'POST',
260
+ '-H', 'accept: application/vnd.github+json',
261
+ '-H', 'authorization: Bearer ' + token,
262
+ '-H', 'user-agent: ' + USER_AGENT,
263
+ '-H', 'x-github-api-version: 2022-11-28',
264
+ '-H', 'content-type: application/octet-stream',
265
+ '--data-binary', '@' + file,
266
+ '-w', '\n%{http_code}',
267
+ uploadUrl,
268
+ ])
269
+ return parseStatus(out)
270
+ } finally {
271
+ try { fs.rmSync(file, { force: true }) } catch {}
272
+ }
273
+ }
274
+ let result = await post()
275
+ if (result.status === 422) {
276
+ // 同名资产已存在:删掉再传(GitHub 不允许覆盖资产)
277
+ try {
278
+ const rel = await gh(token, 'GET', '/repos/' + repo + '/releases/' + releaseId)
279
+ const existing = (Array.isArray(rel.assets) ? rel.assets : []).find((asset) => asset.name === name)
280
+ if (existing) {
281
+ await gh(token, 'DELETE', '/repos/' + repo + '/releases/assets/' + existing.id)
282
+ if (onStep) onStep('删掉同名旧资产,重新上传')
283
+ }
284
+ } catch {}
285
+ result = await post()
286
+ }
287
+ if (result.status < 200 || result.status >= 300) {
288
+ const message = (result.data && (result.data.message || result.data.error)) || result.body.slice(0, 300) || 'HTTP ' + result.status
289
+ const error = new Error('上传 Release 资产失败(' + result.status + '):' + message)
290
+ error.status = result.status
291
+ throw error
292
+ }
293
+ if (onStep) onStep('资产传好了:' + name + '(' + Math.round(buffer.length / 1024) + ' KB)')
294
+ return {
295
+ id: result.data && result.data.id,
296
+ name,
297
+ size: result.data && result.data.size,
298
+ url: (result.data && result.data.browser_download_url) || '',
299
+ }
300
+ }
package/lib/groups.mjs CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/groups.mjs
3
+ * @role 读插件市场的分组(.dsh-market/state.json)并把整合包带的组写回去
4
+ * @sub 分组
5
+ * @exports marketStatePath / readMarketGroups / groupViews / hasMarket / applyMarketGroups
6
+ * @reads <profile>/.dsh-market/state.json
7
+ * @writes 同名组并成员、新组追加 groupOrder,其它键原样保留(临时文件 + rename)
8
+ * @risk 这个文件不是我们的:写坏一次就丢用户的分组,必须只动 groups/groupOrder 且保留其它键
9
+ * @touch 改写入逻辑要同步 test/run.mjs 的临时 profile 用例与安装器的 restoreGroups
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 读插件市场的分组(只读,不改人家的状态文件)。
3
15
  *
package/lib/http.mjs CHANGED
@@ -1,3 +1,13 @@
1
+ /**
2
+ * @file lib/http.mjs
3
+ * @role 请求体读取与 JSON 回包:带体积上限(普通 JSON 1 MB、拖包 256 MB)
4
+ * @sub 网络、限额
5
+ * @exports MAX_JSON_BODY / MAX_DROP_BODY / sendJson / readBody / readRawBody / readJsonBody / asJson
6
+ * @risk 上限调大等于给内存放大攻击开口;拖包上限与 zip 解压上限是两道独立闸门
7
+ * @touch 改上限要同步 client.js 的提示文案与 test 的边界用例
8
+ * @since 0.3.0
9
+ */
10
+
1
11
  /**
2
12
  * HTTP 小工具:JSON 响应、请求体读取(文本 / 原始字节)。
3
13
  *
package/lib/install.mjs CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/install.mjs
3
+ * @role 安装整合包:校验与安全检测 → 解包落地 → 装插件(管理器优先、CLI 兜底)→ 恢复配置/分组/数据 → 写历史
4
+ * @sub 安装、安全检测、配置恢复、数据写回
5
+ * @exports InstallRefused / inspectPackBuffer / readPackFromUrl / materializePayload / installPack / patchPath
6
+ * @reads .dshpack(zip)、profile 现状、市场目录
7
+ * @writes profile 的 node_modules 与 package.json、cordis.patch.yml、~/.dsh/<数据目录>、插件自己的工作目录
8
+ * @risk 这是唯一会改用户环境的模块:任何「跳过已装」「不覆盖配置」「子包跳过」的判断错一次就会污染别人的 profile
9
+ * @touch 改安装顺序要同步 assets/install-stub.mjs(裸 DSH 安装器)、test/run.mjs 的 e2e 用例与 /install/replace 的路由
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 读包 / 检测 / 安装。
3
15
  *
package/lib/manifest.mjs CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/manifest.mjs
3
+ * @role 整合包清单 dsh-modpack.json:schema 版本、字段校验、打包时生成说明文件
4
+ * @sub 清单、校验
5
+ * @exports SCHEMA / KIND / MANIFEST_NAME / sha256 / shortHash / normalizeManifest / buildReadme
6
+ * @reads 包内 dsh-modpack.json
7
+ * @writes 只在打包时生成文本
8
+ * @risk schema 是兼容契约:加必填字段会让旧包全部装不上,只能加可选字段
9
+ * @touch 改字段要同步 lib/pack.mjs 的写入、lib/install.mjs 的读取与目录仓库的校验脚本
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 整合包清单(dsh-modpack.json)。
3
15
  *
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/market-catalog.mjs
3
+ * @role 插件市场目录(npm 包 dsh-plugin-catalog 的 index.json):索引、分类、搜索、分页、按名字查最新版
4
+ * @sub 插件市场、搜索、分类、分页
5
+ * @exports CATEGORY_FALLBACK / CATALOG_SOURCES / PAGE_SIZE_DEFAULT / catalogPaths / categoriesOf / buildIndex / readIndex / writeIndex / catalogSummary / syncCatalog / searchCatalog / categoryMapFor / lookupPlugins
6
+ * @reads CDN 上的 index.json、npm tarball 兜底、本地缓存
7
+ * @writes 插件自己的目录缓存
8
+ * @risk 目录是市场发布的,字段结构会变;CDN 与本机网络都可能不通,必须保留 npm 兜底
9
+ * @touch 改索引结构要同步 store.mjs 的 hostsVersion 迁移与 client.js 的目录面板
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 插件市场目录(分类 + 分页搜索)。
3
15
  *