dsh-modpack-kit 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,12 +1,15 @@
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 { randomBytes } from 'node:crypto'
12
+ import { randomBytes, createHash } from 'node:crypto'
10
13
  import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, clearHistory, removeHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
11
14
  import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
12
15
  import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime, probeRegistry } from './lib/registry.mjs'
@@ -17,6 +20,7 @@ import { readMarketGroups, groupViews } from './lib/groups.mjs'
17
20
  import { classifyPlugin } from './lib/classify.mjs'
18
21
  import { groupFindings } from './lib/scan.mjs'
19
22
  import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
23
+ import { marketSummary, searchMarket, syncMarket, findMarketPack, fetchMarketPack } from './lib/modpack-catalog.mjs'
20
24
  import { parseYaml } from './lib/yamlish.mjs'
21
25
  import { readPatch } from './lib/profile.mjs'
22
26
  import { buildReadme } from './lib/manifest.mjs'
@@ -85,6 +89,10 @@ export default {
85
89
  profile: profileName(config),
86
90
  paths: pathsFor(config),
87
91
  catalog,
92
+ // 社区资源(自建目录):只读缓存,界面拿摘要与首页;真正的搜索走 /market/search
93
+ modpackMarket: (() => {
94
+ try { return marketSummary(config) } catch { return { present: false, stale: true, count: 0, categories: [], repo: '' } }
95
+ })(),
88
96
  placements: {
89
97
  settings: config.showInSettings !== false,
90
98
  sidebar: config.showInSidebar !== false,
@@ -194,9 +202,23 @@ export default {
194
202
  for (const [token, item] of pending) if (now - item.at > PENDING_TTL) pending.delete(token)
195
203
  }
196
204
 
205
+ // 读 profile 里的插件清单要遍历几百个包的 package.json,刷新时连着调十几次很慢:
206
+ // 这里按 profile 目录的 mtime 记住上一次结果,目录没变就直接复用(插件增删会改 mtime)
207
+ let installedMemo = { key: '', at: 0, value: [] };
197
208
  const installedOrEmpty = () => {
198
- try { return listInstalled(profileDir()) } catch { return [] }
199
- }
209
+ let key = '';
210
+ try {
211
+ const dir = profileDir();
212
+ const stat = fs.statSync(path.join(dir, 'package.json'));
213
+ key = dir + '|' + stat.mtimeMs + '|' + stat.size;
214
+ } catch { key = ''; }
215
+ const now = Date.now();
216
+ if (key && installedMemo.key === key && now - installedMemo.at < 5000) return installedMemo.value;
217
+ let value = [];
218
+ try { value = listInstalled(profileDir()) } catch { value = []; }
219
+ installedMemo = { key, at: now, value };
220
+ return value;
221
+ };
200
222
 
201
223
  // 三种策略能不能选:按「这次勾了哪些插件」实时算,客户端拿去做卡片灰显与原因弹窗;
202
224
  // 打包时也再算一遍,挡住「界面上换了插件、策略却没跟着变」的情况。
@@ -244,7 +266,7 @@ export default {
244
266
  },
245
267
  {
246
268
  id: 'lite',
247
- title: '仅下载码(轻量包)',
269
+ title: '轻量包(轻量包)',
248
270
  online: true,
249
271
  ok: liteBlockers.length === 0,
250
272
  reason: liteBlockers.map((b) => b.text).join(';'),
@@ -266,6 +288,7 @@ export default {
266
288
  }
267
289
 
268
290
  const compatFor = (manifest) => checkCompatibility(manifest.plugins, {
291
+ format: manifest && manifest.format,
269
292
  installed: installedOrEmpty(),
270
293
  dshVersion: (() => { try { return dshVersion(profileDir()) } catch { return '' } })(),
271
294
  nodeVersion: process.versions.node,
@@ -377,6 +400,113 @@ export default {
377
400
  }
378
401
  })
379
402
 
403
+ // —— 社区资源(自建目录) ——
404
+ // 只做三件事:读目录、检索、取包;校验/扫描/安装全部复用 /inspect 与 /install 那条老路。
405
+ route('/dsh-modpack-kit/api/market', async (req, res) => {
406
+ if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
407
+ let summary = null
408
+ try { summary = marketSummary(config) } catch (e) { summary = { present: false, stale: true, count: 0, categories: [], error: String((e && e.message) || e) } }
409
+ // 没目录、或过期了:后台自己去拉,页面先拿空壳(首屏不该被网络拖住)
410
+ if (!summary.present || summary.stale) ensureMarket(false)
411
+ const installed = new Set(installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name))
412
+ let first = { items: [], total: 0, hasMore: false }
413
+ if (summary.present) {
414
+ try {
415
+ first = searchMarket(config, { page: 1, pageSize: config.catalogPageSize, installed })
416
+ } catch (e) { first = { items: [], total: 0, hasMore: false, error: String((e && e.message) || e) } }
417
+ }
418
+ json(res, 200, { ok: true, summary, ...first, page: 1, pageSize: config.catalogPageSize })
419
+ })
420
+
421
+ // 社区资源的检索同样按 key 缓存 20 秒:连按几个键不该每次都重新打分
422
+ const marketSearchCache = new Map()
423
+ route('/dsh-modpack-kit/api/market/search', async (req, res) => {
424
+ if (!needPost(req, res)) return
425
+ const body = await readJsonBody(req)
426
+ const installed = installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name)
427
+ const cacheKey = JSON.stringify([body.query || '', body.category || 'all', body.sort || 'new', body.page || 1, body.pageSize || 20, installed.length])
428
+ const cached = marketSearchCache.get(cacheKey)
429
+ if (cached && Date.now() - cached.at < 20000) { json(res, 200, cached.data); return }
430
+ try {
431
+ const data = searchMarket(config, {
432
+ query: body.query,
433
+ category: body.category,
434
+ page: body.page,
435
+ pageSize: Number(body.pageSize) || config.catalogPageSize,
436
+ sort: body.sort,
437
+ installed,
438
+ })
439
+ marketSearchCache.set(cacheKey, { at: Date.now(), data })
440
+ if (marketSearchCache.size > 40) marketSearchCache.delete(marketSearchCache.keys().next().value)
441
+ json(res, 200, data)
442
+ } catch (e) {
443
+ json(res, 200, { ok: false, error: String((e && e.message) || e), items: [], total: 0 })
444
+ }
445
+ })
446
+
447
+ route('/dsh-modpack-kit/api/market/sync', async (req, res) => {
448
+ if (!needPost(req, res)) return
449
+ const body = await readJsonBody(req)
450
+ try {
451
+ const result = await syncMarket(config, { force: body.force === true || config.modpackRefreshHours === 0 })
452
+ if (result.ok && !result.skipped) appendLog('modpack market synced: ' + result.count + ' packs / ' + result.source)
453
+ const installed = installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name)
454
+ const first = result.ok ? searchMarket(config, { page: 1, pageSize: config.catalogPageSize, installed }) : null
455
+ json(res, 200, { ok: result.ok, error: result.error || '', summary: marketSummary(config), ...(first || { items: [], total: 0, hasMore: false }) })
456
+ } catch (e) {
457
+ json(res, 200, { ok: false, error: String((e && e.message) || e) })
458
+ }
459
+ })
460
+
461
+ // 下载一个整合包:只认目录里登记过的条目,sha256 必须对得上,
462
+ // 下完直接在内存里交给原来的 inspect(安全检测、兼容、许可证那一套原样走)。
463
+ route('/dsh-modpack-kit/api/market/download', async (req, res) => {
464
+ if (!needPost(req, res)) return
465
+ const body = await readJsonBody(req)
466
+ const found = findMarketPack(config, body.id)
467
+ if (!found.ok) { json(res, 200, { ok: false, error: found.error }); return }
468
+ const pack = found.pack
469
+ try {
470
+ const fetched = await fetchMarketPack(config, pack)
471
+ const bytes = fetched.buffer
472
+ if (pack.size > 0 && bytes.length !== pack.size) {
473
+ throw new Error('包体积和目录里登记的不一致(登记 ' + pack.size + ' 字节,实际 ' + bytes.length + ' 字节)')
474
+ }
475
+ const actual = createHash('sha256').update(bytes).digest('hex')
476
+ if (pack.sha256 && actual !== pack.sha256) {
477
+ throw new Error('sha256 对不上:目录登记 ' + pack.sha256.slice(0, 12) + '…,实际 ' + actual.slice(0, 12) + '…')
478
+ }
479
+ const inspected = inspectPackBuffer(bytes, {
480
+ config,
481
+ force: body.force === true,
482
+ scanBeforeInstall: config.scanBeforeInstall !== false,
483
+ extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
484
+ })
485
+ const fileName = slugify(inspected.manifest.name || pack.id, 'pack') + '.dshpack'
486
+ const token = rememberPending(fileName, { buffer: bytes, manifest: inspected.manifest, report: inspected.report, scan: inspected.scan })
487
+ appendLog('market download ' + pack.id + ' ' + bytes.length + ' bytes')
488
+ json(res, 200, {
489
+ ok: true,
490
+ token,
491
+ fileName,
492
+ size: bytes.length,
493
+ packId: pack.id,
494
+ packName: pack.name,
495
+ url: fetched.url,
496
+ manifest: inspected.manifest,
497
+ integrity: inspected.integrity,
498
+ scan: inspected.scan,
499
+ scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins),
500
+ report: inspected.report,
501
+ blockingReasons: inspected.blockingReasons,
502
+ notes: inspected.notes,
503
+ compat: compatFor(inspected.manifest),
504
+ })
505
+ } catch (e) {
506
+ json(res, 200, { ok: false, error: String((e && e.message) || e) })
507
+ }
508
+ })
509
+
380
510
 
381
511
  // —— 查某个包的可用版本 ——
382
512
  route('/dsh-modpack-kit/api/versions', async (req, res) => {
@@ -394,7 +524,7 @@ export default {
394
524
  }
395
525
  })
396
526
 
397
- // —— 打包(支持后台任务:左下角悬浮窗要进度,且允许同时打多个包) ——
527
+ // —— 打包(支持后台任务:悬浮窗要进度,且允许同时打多个包) ——
398
528
  const jobs = new Map()
399
529
  let jobSeq = 0
400
530
  // 任务记录默认留到 DSH 下次启动(或点「清空进程」),切页面、换入口都不丢。
@@ -580,7 +710,7 @@ export default {
580
710
  scanGroups: result.scanGroups,
581
711
  report: result.report,
582
712
  notes: result.notes,
583
- compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: dshVersionNow, nodeVersion: process.versions.node, config }),
713
+ compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: dshVersionNow, nodeVersion: process.versions.node, config, format: result.manifest && result.manifest.format }),
584
714
  }
585
715
  } catch (error) {
586
716
  if (error instanceof JobCancelled) {
@@ -1223,9 +1353,34 @@ export default {
1223
1353
  return catalogJob
1224
1354
  }
1225
1355
 
1356
+ // 社区资源也照这个套路:启动补一次、过期在后台补、十分钟内失败不重敲
1357
+ let marketJob = null
1358
+ let lastMarketTry = 0
1359
+ const ensureMarket = (force) => {
1360
+ if (marketJob) return marketJob
1361
+ if (force !== true && Date.now() - lastMarketTry < 10 * 60 * 1000) return Promise.resolve({ ok: false, skipped: true })
1362
+ if (force !== true) lastMarketTry = Date.now()
1363
+ const hours = Math.max(1, Number(config.modpackRefreshHours) || 24)
1364
+ marketJob = syncMarket(config, { force: force === true, maxAgeMs: hours * 3600 * 1000 })
1365
+ .then((result) => {
1366
+ if (result && result.ok && !result.skipped) appendLog(`整合包目录更新 ${result.count} 个(${result.source})`)
1367
+ else if (result && !result.ok) log('modpack market sync failed:', result.error)
1368
+ return result
1369
+ })
1370
+ .catch((error) => {
1371
+ log('modpack market sync failed:', String((error && error.message) || error))
1372
+ return { ok: false, error: String((error && error.message) || error) }
1373
+ })
1374
+ .finally(() => { marketJob = null })
1375
+ return marketJob
1376
+ }
1377
+
1226
1378
  log('routes ready')
1227
1379
  // 起来就把目录补一次;没有网也不影响其它功能,失败只写日志
1228
- if (process.env.DSH_MODPACK_OFFLINE !== '1') ensureCatalog(false).catch(() => {})
1380
+ if (process.env.DSH_MODPACK_OFFLINE !== '1') {
1381
+ ensureCatalog(false).catch(() => {})
1382
+ if (config.showModpackMarket !== false) ensureMarket(false).catch(() => {})
1383
+ }
1229
1384
  ctx.effect(() => {
1230
1385
  const timer = setInterval(sweeper, 60 * 1000)
1231
1386
  if (typeof timer.unref === 'function') timer.unref()
package/lib/compat.mjs CHANGED
@@ -26,19 +26,22 @@ export function checkCompatibility(plugins, context) {
26
26
  const dshVersion = context.dshVersion || ''
27
27
  const nodeVersion = context.nodeVersion || process.versions.node
28
28
  const allow = new Set((context.config?.licenseAllow || []).map((x) => String(x).toLowerCase()))
29
+ // 建议要跟打包策略对得上:轻量包只记版本,不能说「把它一起打包进来」
30
+ const format = context.format === 'full' || context.format === 'hybrid' ? context.format : 'lite'
31
+ const canCarry = format === 'full' || format === 'hybrid'
32
+ const missingPeerSuggestion = canCarry
33
+ ? '装完可能报错或功能缺失:把这个依赖也勾进包里,或先在本机装好它。'
34
+ : '轻量包只记版本、不带别的东西,装的时候要联网取包:先在本机装好这个依赖,或改用完整包 / 混合包把依赖一起带走。'
29
35
 
30
36
  for (const plugin of plugins || []) {
31
37
  const local = installedMap.get(plugin.name)
32
38
  if (local) {
33
- if (local.version !== plugin.version) {
39
+ if (plugin.latest !== true && plugin.version && local.version !== plugin.version) {
34
40
  const cmp = compareVersions(plugin.version, local.version)
35
41
  add('info', plugin.name, 'local-version',
36
42
  '本地已装 ' + local.version + ',整合包里是 ' + plugin.version + (cmp === null ? '' : cmp > 0 ? '(较新)' : cmp < 0 ? '(较旧,可能降级)' : ''),
37
43
  cmp !== null && cmp < 0 ? '确认要降级再装;降级可能丢掉新版本的配置项。' : '安装会按整合包里的版本处理。')
38
44
  }
39
- if (!local.isBundle && plugin.isBundle) {
40
- add('warn', plugin.name, 'local-not-bundle', '本地同名包不是 DSH 插件(没有 dsh 段)', '确认整合包来源;装完可能不会出现在侧栏。')
41
- }
42
45
  } else {
43
46
  add('info', plugin.name, 'not-installed', '本地未安装,将新增', '')
44
47
  }
@@ -52,7 +55,7 @@ export function checkCompatibility(plugins, context) {
52
55
  if (!found) {
53
56
  add('warn', plugin.name, 'peer-missing-' + peer,
54
57
  '需要 ' + peer + ' ' + range + ',整合包和本机都没有',
55
- '安装后这个插件可能报错或功能缺失;把它一起打包进来。')
58
+ missingPeerSuggestion)
56
59
  continue
57
60
  }
58
61
  const ok = satisfies(found, range)
@@ -83,18 +86,16 @@ export function checkCompatibility(plugins, context) {
83
86
  }
84
87
  }
85
88
 
86
- if (!plugin.license) {
87
- add('warn', plugin.name, 'license-missing', '插件没写 license', '再分发前请联系作者确认授权,否则不要传给别人。')
88
- } else if (!allow.has(String(plugin.license).toLowerCase())) {
89
+ // 轻量包只记版本、不转手代码,这里不提许可证的事。
90
+ if (canCarry && !plugin.license) {
91
+ add('warn', plugin.name, 'license-missing', '插件没写 license', '包里带的是第三方代码,再分发前请联系作者确认授权,否则不要传给别人。')
92
+ } else if (canCarry && !allow.has(String(plugin.license).toLowerCase())) {
89
93
  add('warn', plugin.name, 'license-unlisted', 'license 不在允许列表:' + plugin.license,
90
94
  '确认许可允许再分发;不确定就只在自己机器上装。')
91
95
  }
92
96
  if (plugin.localEdits) {
93
97
  add('info', plugin.name, 'local-edits', '打包时带的是打包者改过的本地文件', '和上游发布的版本可能不一致。')
94
98
  }
95
- if (!plugin.hasClient && !plugin.hasPatch && plugin.isBundle === false) {
96
- add('warn', plugin.name, 'not-bundle', '这个包没有 dsh 段,可能不是 DSH 插件', '确认是不是装错了东西。')
97
- }
98
99
  }
99
100
 
100
101
  const errors = findings.filter((f) => f.level === 'error')
package/lib/groups.mjs CHANGED
@@ -91,20 +91,32 @@ export function hasMarket(profileDir) {
91
91
  * @param {Record<string, string[]>} additions 组名 → 要并进去的成员
92
92
  * @returns {{changed: boolean, summary: string, error?: string}}
93
93
  */
94
- export function applyMarketGroups(profileDir, additions) {
95
- const file = marketStatePath(profileDir)
94
+ export function applyMarketGroups(profileDir, additions, options = {}) {
95
+ const stateFile = marketStatePath(profileDir)
96
+ const packKey = typeof options.packKey === 'string' ? options.packKey : ''
96
97
  let raw = {}
97
98
  try {
98
- raw = JSON.parse(fs.readFileSync(file, 'utf8'))
99
+ raw = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
99
100
  } catch {
100
101
  raw = {}
101
102
  }
102
103
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) raw = {}
103
104
  const groups = raw.groups !== null && typeof raw.groups === 'object' && !Array.isArray(raw.groups) ? { ...raw.groups } : {}
104
105
  const order = stringList(raw.groupOrder)
106
+ const origins = raw.groupOrigins !== null && typeof raw.groupOrigins === 'object' && !Array.isArray(raw.groupOrigins) ? { ...raw.groupOrigins } : {}
105
107
  const changedParts = []
106
- for (const [name, members] of Object.entries(additions || {})) {
107
- if (!name) continue
108
+ const renames = {}
109
+ for (const [rawName, members] of Object.entries(additions || {})) {
110
+ if (!rawName) continue
111
+ let name = rawName
112
+ const owner = typeof origins[name] === 'string' ? origins[name] : ''
113
+ // 别的包已经用掉这个名字:找第一个空位,依次试「名字 2」「名字 3」……避免互相污染
114
+ if (groups[name] !== undefined && owner !== '' && packKey !== '' && owner !== packKey) {
115
+ let index = 2
116
+ while (groups[name + ' ' + index] !== undefined) index += 1
117
+ name = name + ' ' + index
118
+ renames[rawName] = name
119
+ }
108
120
  const current = stringList(groups[name])
109
121
  const merged = [...current]
110
122
  let added = 0
@@ -116,18 +128,20 @@ export function applyMarketGroups(profileDir, additions) {
116
128
  if (added === 0 && groups[name] !== undefined) continue
117
129
  groups[name] = merged
118
130
  if (!order.includes(name)) order.push(name)
131
+ if (origins[name] === undefined || origins[name] === '') origins[name] = packKey
119
132
  changedParts.push(name + '(+' + added + ')')
120
133
  }
121
- if (changedParts.length === 0) return { changed: false, summary: '' }
134
+ if (changedParts.length === 0) return { changed: false, summary: '', renames }
122
135
  raw.groups = groups
123
136
  raw.groupOrder = order
137
+ raw.groupOrigins = origins
124
138
  try {
125
- fs.mkdirSync(path.dirname(file), { recursive: true })
126
- const tmp = file + '.tmp-' + process.pid
139
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true })
140
+ const tmp = stateFile + '.tmp-' + process.pid
127
141
  fs.writeFileSync(tmp, JSON.stringify(raw, null, 2) + '\n', 'utf8')
128
- fs.renameSync(tmp, file)
142
+ fs.renameSync(tmp, stateFile)
129
143
  } catch (error) {
130
- return { changed: false, summary: '', error: String((error && error.message) || error) }
144
+ return { changed: false, summary: '', renames, error: String((error && error.message) || error) }
131
145
  }
132
- return { changed: true, summary: changedParts.join('、') }
146
+ return { changed: true, summary: changedParts.join('、'), renames }
133
147
  }
package/lib/install.mjs CHANGED
@@ -185,6 +185,7 @@ export async function installPack(input) {
185
185
  const profile = targetName && targetName !== 'profiles' ? targetName : config.profile || 'desktop'
186
186
  const installed = listInstalled(profileDir)
187
187
  const compat = checkCompatibility(manifest.plugins, {
188
+ format: manifest && manifest.format,
188
189
  installed,
189
190
  dshVersion: dshVersion(profileDir),
190
191
  nodeVersion: process.versions.node,
@@ -344,7 +345,13 @@ export async function installPack(input) {
344
345
  memoryEntries = await context.resolveSourceEntries(plugin)
345
346
  if (!Array.isArray(memoryEntries) || memoryEntries.length === 0) throw new Error('取回来的包里没有文件')
346
347
  } catch (error) {
347
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '取包失败:' + String(error?.message || error) })
348
+ const why = String(error?.message || error)
349
+ actions.push({
350
+ plugin: plugin.name,
351
+ action: 'install',
352
+ ok: false,
353
+ message: '取包失败:' + why + (/没有版本满足|没有版本信息|元数据缺少|registry 都失败|notarget|E404/u.test(why) ? '(轻量包只记版本号,市场上没有这个版本时就装不回来:改用完整包或混合包,把插件本体带在包里)' : ''),
354
+ })
348
355
  continue
349
356
  }
350
357
  if (plugin.version && String(plugin.version) !== '0.0.0') resolvedSpec = plugin.name + '@' + plugin.version
@@ -368,7 +375,13 @@ export async function installPack(input) {
368
375
  try {
369
376
  dir = await context.resolveSource(plugin, packRoot)
370
377
  } catch (error) {
371
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '取包失败:' + String(error?.message || error) })
378
+ const why = String(error?.message || error)
379
+ actions.push({
380
+ plugin: plugin.name,
381
+ action: 'install',
382
+ ok: false,
383
+ message: '取包失败:' + why + (/没有版本满足|没有版本信息|元数据缺少|registry 都失败|notarget|E404/u.test(why) ? '(轻量包只记版本号,市场上没有这个版本时就装不回来:改用完整包或混合包,把插件本体带在包里)' : ''),
384
+ })
372
385
  continue
373
386
  }
374
387
  } else {
@@ -377,6 +390,7 @@ export async function installPack(input) {
377
390
  }
378
391
 
379
392
  if (!embedded) {
393
+ if (!resolvedSpec && plugin.latest === true) resolvedSpec = plugin.name
380
394
  if (!resolvedSpec && plugin.version && String(plugin.version) !== '0.0.0') resolvedSpec = plugin.name + '@' + plugin.version
381
395
  // 轻量包本体不夹带源码,真正的代码是刚下载回来的:装之前必须补扫一遍,否则「安装前检测」是空转
382
396
  try {
@@ -421,6 +435,21 @@ export async function installPack(input) {
421
435
  if (attempt.output) lines.push(attempt.output)
422
436
  appendLog('install ' + plugin.name + ' exit=' + code + ' via=' + (usedManager ? 'manager' : 'cli') + (marketHit ? '/market' : '/pack') + (application ? ' ' + application : ''))
423
437
 
438
+ // 包里记的那一版在市场上下架了(或者本来就没这个版本号)时,先退回不带版本号的 latest 再试一次:
439
+ // 反正市场只认「是不是 file:」,记哪一版都算市场版,装最新的比装不上强。
440
+ if (code !== 0 && marketHit && marketHit.fromPack && !dir && pluginPayload(entries, plugin.dirName || plugin.name).length === 0) {
441
+ const latestAttempt = await installSpec(plugin.name, null)
442
+ if (latestAttempt.code === 0) {
443
+ lines.push('包里记的 ' + marketHit.spec + ' 装不上(退出码 ' + code + '),改按市场最新版 ' + plugin.name + ' 装上了')
444
+ code = latestAttempt.code
445
+ application = latestAttempt.application
446
+ usedManager = latestAttempt.manager
447
+ if (application === 'restart-required') restartFromManager = true
448
+ marketHit = { spec: plugin.name, version: '', fromPack: true, latest: true }
449
+ if (latestAttempt.output) lines.push(latestAttempt.output)
450
+ }
451
+ }
452
+
424
453
  // registry 这条路断了时,退回包里/本地已有的那份——能装上比装不上强,但依赖会写成 file:,
425
454
  // 插件市场会把它当成本地安装,所以下面要明确提示。
426
455
  if (code !== 0 && marketHit && marketHit.fromPack && !dir && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
@@ -630,10 +659,13 @@ export async function installPack(input) {
630
659
  } else if (options.dryRun) {
631
660
  lines.push('演练:将把 ' + entriesText + ' 并进插件市场分组')
632
661
  } else {
633
- const applied = applyMarketGroups(profileDir, Object.fromEntries(groupAdds))
662
+ const applied = applyMarketGroups(profileDir, Object.fromEntries(groupAdds), { packKey: manifest.id || manifest.name || '' })
634
663
  if (applied.changed) {
635
- lines.push('已按包内分组并入插件市场:' + applied.summary)
636
- actions.push({ plugin: '', action: 'group', ok: true, message: '并入市场分组:' + applied.summary })
664
+ const renamed = applied.renames && Object.keys(applied.renames).length > 0
665
+ ? '(重名已避让:' + Object.entries(applied.renames).map(([from, to]) => from + ' → ' + to).join('、') + ')'
666
+ : ''
667
+ lines.push('已按包内分组并入插件市场:' + applied.summary + renamed)
668
+ actions.push({ plugin: '', action: 'group', ok: true, message: '并入市场分组:' + applied.summary + renamed })
637
669
  } else if (applied.error) {
638
670
  lines.push('市场分组没能写入(' + applied.error + ');插件已经装好,分组可以在插件市场里手动加')
639
671
  }
package/lib/manifest.mjs CHANGED
@@ -29,7 +29,9 @@ function normalizePlugin(raw) {
29
29
  }
30
30
  return {
31
31
  name,
32
- version: str(raw.version, 64) || '0.0.0',
32
+ // latest = true 表示「安装时取市场最新」,此时 version 可以为空
33
+ version: str(raw.version, 64) || (raw.latest === true ? '' : '0.0.0'),
34
+ latest: raw.latest === true,
33
35
  requested: str(raw.requested, 64),
34
36
  source: ['profile', 'npm', 'file', 'url', 'vendor'].includes(raw.source) ? raw.source : 'npm',
35
37
  registry: str(raw.registry, 300),
@@ -77,9 +77,8 @@ export function categoriesOf(raw) {
77
77
  const en = text(title && title.en) || zh
78
78
  if (zh) out.push({ id, zh, en })
79
79
  }
80
- // 顺序按内置表来,内置没有的接在后面:市场自己的顺序是声明顺序,这里保持稳定。
81
- const order = new Map(CATEGORY_FALLBACK.map((item, i) => [item.id, i]))
82
- out.sort((a, b) => (order.get(a.id) ?? 99) - (order.get(b.id) ?? 99))
80
+ // 顺序就是市场目录 metadata.categories 的声明顺序(跟插件市场界面里那一列一致);
81
+ // 内置表只在这种顺序缺失时兜底,不要拿它重排,否则两边的分类次序会对不上。
83
82
  return out.length ? out : CATEGORY_FALLBACK.slice()
84
83
  }
85
84
 
@@ -264,7 +263,12 @@ function relevance(plugin, query, tokens, categoryLabels) {
264
263
  return field(label, -10)
265
264
  }
266
265
 
267
- const compareMarket = (sort) => (a, b) => {
266
+ const compareMarket = (sort, categoryOrder) => (a, b) => {
267
+ if (sort === 'market') {
268
+ const ca = categoryOrder ? (categoryOrder.get(a.category) ?? 99) : 0
269
+ const cb = categoryOrder ? (categoryOrder.get(b.category) ?? 99) : 0
270
+ if (ca !== cb) return ca - cb
271
+ }
268
272
  if (sort === 'new') {
269
273
  const ta = Date.parse(a.publishedAt) || 0
270
274
  const tb = Date.parse(b.publishedAt) || 0
@@ -344,7 +348,9 @@ export function searchCatalog(config, input = {}) {
344
348
  if (query && score === 0) continue
345
349
  rows.push({ plugin, score, installed: true, local: local.version || '' })
346
350
  }
347
- const marketCompare = compareMarket(sort)
351
+ // 分类次序取自市场目录(index.categories 已经是市场声明顺序)
352
+ const categoryOrder = new Map(index.categories.map((c, i) => [c.id, i]))
353
+ const marketCompare = compareMarket(sort, categoryOrder)
348
354
  rows.sort((a, b) => (b.installed ? 1 : 0) - (a.installed ? 1 : 0) || b.score - a.score || marketCompare(a.plugin, b.plugin))
349
355
 
350
356
  const total = rows.length