dsh-modpack-kit 0.1.9 → 0.2.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.
package/docs/DETAIL.md CHANGED
@@ -1,36 +1,43 @@
1
1
  # 整合包(dsh-modpack-kit)
2
2
 
3
- 类似 HMCL / PCL 这类我的世界启动器的整合包工具:把多个 DSH 插件连同配置与数据打成一个 `.dshpack`,一次装好。支持完整包(自带插件文件,裸 DSH 也能装)与轻量包(只记名字与版本,安装时联网取包)。
3
+ 把多个 DSH 插件连同配置与数据打成一个 `.dshpack`,在另一台机器上一次装好。有插件市场时按市场版本装、识别成分组;没有市场时裸 DSH 也能用包内的独立安装器装完。
4
4
 
5
5
  ## 能做什么
6
6
 
7
- - **打包**:从「本机已装」或「插件市场目录」挑插件,逐个可选版本;两种形态——完整包(插件文件进包,目标机器只装 DSH 本体即可装)、轻量包(只记名字/版本,安装时从市场取包)。
8
- - **逐插件定制**:「插件预设」只打插件默认配置;「自定义配置」带上本机配置条目与数据快照(来源是本机时连代码改动一起打)。默认插件预设,每行最左边的徽标显示来源(市场版 / 本机版)。
9
- - **只列真正的插件**:`listInstalled` 从 profile 依赖 + `bundles` 出发递归,把父插件带进来的组件标成 `isDirect: false` 并记 `transitiveOf`;打包、安装、安装器都跳过它们,避免一个插件被当成九个。
10
- - **安装**:读包 → 校验完整性 → 扫描 → 兼容检查 → 逐插件交给宿主 `pluginManager.installBundle`(不可用或报错时退回命令行 `dsh plugin add`)→ 登记启用清单 → 回填配置与数据。
11
- - **已装先跳过**:按插件名判定,先跳过其余照装;装完列出「本机版本 → 包内版本」,由你选「直接完成」或「替换为包内版本」。
12
- - **市场版身份**:市场版来源直接按 `名字@版本` 装,不先问 registry;轻量包取回代码后也按版本装,失败才退回 `file:` 副本并提示「市场会显示成本地安装」。
13
- - **分组**:读插件市场的 `.dsh-market/state.json`,按你的分组折叠展示「已装」,组头带「一键加入 / 清空本组」;按组打包会把组名写进清单,装到同样装了市场的机器上并进同名分组。
14
- - **分类 / 搜索 / 分页**:分类即市场 23 个分区;首屏只列本机已装、不联网,搜索或点分类才查目录,服务端分页(默认每页 20 条),底部「加载更多」。
15
- - **三处入口**:设置页、侧边栏、插件页各一个开关,改了立刻挂上或撤下;接口层拒绝三处全关,免得没有入口关回来。
16
- - **装完是否启用**:「安装后直接启用」默认关;关的时候依赖照写,但把 `dsh.profile.bundles` 精确撤回原样——重启也不加载。
17
- - **读取方式**:「选择文件…」「浏览文件夹…」、手写目录、「已导入的整合包」列表(内存里最多 8 份,显示打包时的名字/作者/描述),或 https 链接。拖拽入口已去掉(外壳会接管文件拖放)。
7
+ - **打包**:从「本机已装」或「插件市场目录」挑插件,逐个选版本与来源;三种策略——完整包、仅下载码、混合包。
8
+ - **逐插件定制**:「插件预设」只带插件默认配置,「自定义配置」带上本机配置条目与数据快照(本机来源时连代码改动一起打)。
9
+ - **只列真正的插件**:从 profile 依赖与 `bundles` 递归,父插件带进来的组件标 `isDirect: false`,打包、安装、安装器一致跳过。
10
+ - **安装**:读包 → 校验 sha256 → 扫描 → 兼容检查 → 逐插件交给宿主 `pluginManager.installBundle`(不可用或报错退回 `dsh plugin add`)→ 登记启用 → 回填配置与数据。
11
+ - **已装先跳过**:按插件名跳过,装完列出「本机 → 包内」,由你决定是否替换为包内版本。
12
+ - **入口**:设置页、侧边栏、插件页三处各一开关,接口层拒绝三处全关。
13
+ - **读取方式**:「选择文件…」「浏览文件夹…」、手写目录、「已导入的整合包」列表(内存里最多 8 份,带打包时的名字/作者/描述)、https 链接。
18
14
 
19
15
  ## 怎么用
20
16
 
21
17
  1. 从左侧栏、设置页或插件页进入「整合包」。
22
- 2. 「打包」页勾选插件(首屏是本机已装)→ 设包名与选项 → 打包;看完安全报告与兼容提示后下载或存档。
23
- 3. 换到目标机器:装本插件,或直接跑包里的 `install/` 安装器 → 选文件或填链接 → 检测 → 安装。
24
- 4. 重启 DSH 让新插件生效。
18
+ 2. 勾选插件 → 选打包策略 → 打包;看完安全报告与兼容提示后下载或存档。
19
+ 3. 目标机器:装本插件,或直接跑包里的 `install/` 安装器 → 选文件或填链接 → 检测 → 安装。
20
+ 4. 重启 DSH 生效。
21
+
22
+ ## 三种打包策略
23
+
24
+ 界面这一栏叫「打包策略(必选)」,三块卡片按你勾的插件实时判定,不能选的整块灰显、点一下只弹原因。
25
+
26
+ | 策略 | 进包内容 | 安装时 | 体积 |
27
+ | --- | --- | --- | --- |
28
+ | `full` | 清单 + `plugins/` + 配置 + 数据 + 报告 + 安装器 | 先按 `名字@版本` 从市场装,失败/离线退回包内副本 | 最大 |
29
+ | `lite` | 清单 + 版本号 + 报告 | 联网按版本取包,代码进内存扫 | 最小 |
30
+ | `hybrid` | 清单 + 版本号 + 配置/数据;没有确定版本或选了「连本机改动一起打」的插件才带 `plugins/` | 包里有目录的直接装(不联网),其余按版本取 | 接近 `lite` |
31
+
32
+ 判定只有一份:`index.js` 的 `computePlan(selection)`,`POST /pack/plan` 返回它,`POST /pack` 打包前再算一次,`lite` / `hybrid` 不可用直接 400。`lite` 的硬条件是有确定版本且没有插件选「自定义配置」;`hybrid` 只拦「没版本、本机又没代码」。
25
33
 
26
34
  ## 安全模型
27
35
 
28
- - 检测是**静态**的:只读文件比对规则,不执行、不 import、不跑安装脚本。拦得住明显的密钥夹带与可疑写法,但**不替代杀毒软件**,也不证明插件安全。
29
- - 打包前**强制**扫描:开关显示但点不动,API 写 `scanBeforePack: false` 也会被拉回 `true`。安装前再扫一次(可关,默认开)。
30
- - 命中原文只在内存里比对;报告与历史只留规则名、文件、行号与掩码(如 `sk****(32 字符已隐藏)`)。
31
- - 检出高危时任务停在 `paused`,确认「我知道在干什么」后从检测点续跑(不重新收集、不重复检测),清单记 `security.acknowledged`。
32
- - `integrity.json` 记每个文件的 sha256;安装前校验,缺失或对不上直接阻断(只有显式 force 才越过)。
33
- - 解压有上限:条目数、单文件、总大小、压缩比;拒绝绝对路径、`..`、盘符、反斜杠、符号链接与加密条目。
36
+ - 检测是静态的:只读文件比对规则,不执行、不 import、不跑安装脚本。能拦明显的密钥夹带与可疑写法,但不替代杀毒软件。
37
+ - 打包前强制扫描(开关点不动,写 `scanBeforePack: false` 会被拉回);安装前再扫一次(默认开)。
38
+ - 命中原文只在内存比对;报告与历史只留规则名、文件、行号与掩码。
39
+ - 高危先停在 `paused`,确认后从检测点续跑(不重新收集、不重复检测),清单记 `security.acknowledged`。
40
+ - `integrity.json` 记每个文件 sha256,安装前校验,缺失或对不上直接阻断(显式 force 才越过);解压有条目数、单文件、总大小、压缩比上限,拒绝绝对路径、`..`、符号链接与加密条目。
34
41
  - 只放 https 与白名单域名,逐跳校验重定向,流式限体积。
35
42
 
36
43
  ## 包格式
@@ -38,67 +45,61 @@
38
45
  ```
39
46
  dsh-modpack.json 清单:格式、插件、选项、安全摘要
40
47
  README.txt 不依赖本插件的手工安装说明
41
- security/report.txt 检测报告(只有类型、位置、掩码)
48
+ security/report.txt 检测报告(规则、位置、掩码)
42
49
  integrity.json sha256 清单
43
50
  install/install.mjs 独立安装器(裸 DSH 可用)
44
51
  install/install.cmd Windows 双击入口
45
52
  install/install.sh shell 入口
46
- plugins/<name>/** 完整版才有
53
+ plugins/<name>/** 只有带本体的策略才有
47
54
  configs/<name>.json 抓到的配置条目
48
- data/<目录名>/** 插件数据快照(小体积文本)
55
+ data/<目录名>/** 插件数据快照(小文本)
49
56
  ```
50
57
 
51
- 文件名 `<包名>-<日期>-<full|lite>.dshpack`。完整版先去 `~/.dsh/dsh-modpack/vendor/<包>-<hash>/` 再登记,删了解压目录也不会断。
58
+ 文件名 `<包名>-<日期>-<full|lite|hybrid>.dshpack`。安装侧判断「要不要联网」只看包里有没有 `plugins/<目录>/`,不看整包 `format`,所以混合包可以一部分带本体、一部分只记版本。完整包会先把本体复制到 `~/.dsh/dsh-modpack/vendor/<包>-<hash>/` 再登记,删掉解压目录也不断。
52
59
 
53
60
  ## 配置与数据
54
61
 
55
- - 配置来源是 profile 的 `cordis.patch.yml`:按 `name`/`id` 取该插件整段 `config`(含 `disabled`)存进 `configs/<name>.json`;安装时只替换这一条,其它字节原样保留,包里没有的追加在末尾。
56
- - 保真:嵌套映射、数组、空数组/空对象、中文、多行字符串、布尔与数字都原样往返(空容器写成 `key: []` / `key: {}`)。
57
- - 擦除:`redactConfig` 按归一化键名完全相等判凭据(`apiKeyEnv` 不误伤),值命中 `sk-` / `gh[pousr]_` / `xox[baprs]-` / `AKIA` 也换成 `${REDACTED}`;路径写进 `configRedacted`,安装时提示重填。安装时不再二次擦除。
58
- - 数据快照:只收 `~/.dsh/<目录>` 下的文本小文件(`.json/.md/.txt/.yml/.yaml/.csv/.toml/.ini`,单文件 ≤1 MB、整包 ≤8 MB),凭证类文件名跳过;文本再经 `scrubText` 擦一遍,命中数记 `dataRedacted`。安装时写回 `~/.dsh/<目录>`,**默认不覆盖已有文件**(`--replace` 才覆盖)。
62
+ - 配置来自 profile 的 `cordis.patch.yml`:按 `name`/`id` 取整段 `config`(含 `disabled`)存进 `configs/<name>.json`;安装时只替换这一条,其它字节原样保留,没有的追加在末尾。
63
+ - 保真:嵌套映射、数组、空容器、中文、多行字符串、布尔与数字都原样往返。
64
+ - 擦除:`redactConfig` 按归一化键名完全相等判凭据(`apiKeyEnv` 不误伤),值命中 `sk-` / `gh[pousr]_` / `xox[baprs]-` / `AKIA` 也换成 `${REDACTED}`;路径写进 `configRedacted`,安装时提示重填。
65
+ - 数据快照:只收 `~/.dsh/<目录>` 下的文本小文件(≤1 MB/个、整包 ≤8 MB),凭证类文件名跳过,文本再过一遍 `scrubText`;安装时写回,默认不覆盖已有文件(`--replace` 才覆盖)。
59
66
  - 插件内安装与包内安装器两条路径规则一致。
60
67
 
61
68
  ## 与插件市场
62
69
 
63
- - 目录:读市场自己的 `dsh-plugin-catalog`(CDN `index.json` 优先,失败退 npm tarball);分区名与条目数跟市场一致,索引落在 `<DSH_HOME>/dsh-modpack/catalog/market.json`。
64
- - 市场判定只看依赖写法:`file:` / `link:` 算本地,semver 算市场版。所以市场来源的插件一律 `名字@版本` 装。
65
- - 没装市场:打包、装包、强制检测、完整性/兼容/许可证校验、配置回填、三处入口都照常,只少 Discover 界面与目录搜索(建一次索引即恢复)。
66
- - 分组:`readMarketGroups` 只读不写;`applyMarketGroups` 在安装时做「同名组并成员、新组追加、其它键原样保留」;目标没装市场(没有 `.dsh-market`)就不写,只说明一句。
67
-
68
- - 入口形态:设置里是一整节;侧边栏是独立页面;插件页里只是一条标签,渲染时不再重复页头,也不自己造滚动区(交给插件页滚),高度由内容决定(`Home` 的 `surface === "plugins"` 分支)。首屏读状态失败会自动退避重试三次并给一个「重试」按钮——宿主刚起来时会话还没就绪,第一次常常拿不到 401 之外的东西。
70
+ - 目录与市场同源(`dsh-plugin-catalog` 的 `index.json`,失败退 npm tarball),分区即市场 23 类;首屏只列本机已装,搜索或点分类才查目录,服务端分页。
71
+ - 市场判定只看依赖写法:`file:` / `link:` 算本地,semver 算市场版。所以市场来源一律按 `名字@版本` 装;完整包失败或离线才退回 `file:` 副本,并明确提示「市场会显示成本地安装」。
72
+ - 分组:只读 `.dsh-market/state.json` 做折叠展示;按组打包会把组名写进清单,装到同样装了市场的机器上并进同名分组(`applyMarketGroups`,同名组并成员、其它键原样保留)。
73
+ - 没装市场:打包、装包、检测、校验、配置回填、三处入口照常,只少 Discover 界面与目录搜索。
69
74
 
70
75
  ## 安装顺序与进度窗
71
76
 
72
77
  - 打包与安装共用任务队列:`POST /pack|/install { async: true }` 立即返回 job,`GET /jobs` 轮询;`/jobs/cancel` 终止(包在内存组装,取消不落盘)、`/jobs/ack` 续跑、`/jobs/dismiss` 删记录、`/jobs/clear` 清收尾。
73
- - 悬浮进度窗:左下角起,按住标题可拖,位置存 `localStorage`(`dsh-modpack-kit:dock-pos`);没任务自动收起,只留「进度」按钮唤出。标题栏按钮与拖动不共享判定(`closest("button")` 直接返回)。
74
- - 收尾:`jobKeepSeconds` 默认 0(留到重启或手动清);正数按秒清,失败/取消取 `min(该值, 15 秒)`;心跳超 10 分钟的 running 先判失败再清走;`paused` 永不自动清。
75
- - 完成任务可点「下载安装包」:切到打包页、回填结果并滚到下载区;结果存在客户端缓存里,切页签不丢。
76
- - 体积上限:`maxPackBytes` 默认 512 MB(16~4096),单个下载 `maxDownloadBytes` 默认 256 MB;允许同时打多个包。
78
+ - 悬浮进度窗可拖动(位置存 `localStorage`),没任务时收起只留「进度」按钮;收尾记录按 `jobKeepSeconds`(默认 0)与心跳(running 超 10 分钟判失败)处理。
79
+ - 安装预览:逐插件勾选、有问题的置顶(缺依赖 / 引擎版本不符)、每个带配置的插件可选「包内配置 / 保持本机」、「装后整体启用」、「装后同步市场分组」。
80
+ - 离线安装:勾「离线安装」或探不到 registry 时,只装带本体的插件;只记版本的会逐条说明「联网后再试」。
77
81
 
78
82
  ## 网络层(`lib/net.mjs`)
79
83
 
80
- - `assertAllowedUrl`:只放 https,主机名须在白名单(含子域),白名单版本号 `HOSTS_VERSION` 控制老配置合并。
81
- - `requestBuffer`:逐跳手动跟随重定向(最多 6 跳),每跳重新校验;超时 `netTimeoutSeconds`(默认 60)、`netRetries`;fetch 全失败且 `curlFallback` 为真时用系统 `curl -i`(不带 `-L`,重定向仍由我们校验),`--max-filesize` 与响应上限双保险。
84
+ - `requestBuffer`:逐跳校验重定向(最多 6 跳),白名单版本 `HOSTS_VERSION` 控制老配置合并;超时 `netTimeoutSeconds`(默认 60),失败可退系统 `curl`(不带 `-L`,重定向仍由我们校验)。
85
+ - `npmMetadata`:版本清单按「精简 → 完整 → 单版本」三层退让,上限 `maxMetadataBytes`(默认 64 MB,夹 4~512);超限提示调大上限或指定版本号。
86
+ - 传输压缩:fetch 带 `accept-encoding`,curl 兜底带 `--compressed`。
82
87
 
83
88
  ## 扩展接口
84
89
 
85
- - 路由:Host 能力全在 `/dsh-modpack-kit/api/*`,界面只是消费者,换 UI 不用动后端。
86
- - 安装:`installPack` 的 `context.installBundle` 优先(宿主 `pluginManager.installBundle(spec, { enabled, expected })`,pnpm、激活、回滚都归宿主),缺省或抛错退回 `context.runCli`。
87
- - 扫描:`scanEntries(entries, { extraRules })`;规则形状见 `SECRET_RULES` / `MALWARE_RULES`;同内容文件按 sha1 复用结论,文件名单独重算。
88
- - 擦除:`redactConfig(value)` + `SECRET_KEY_SET` / `SECRET_VALUE_PATTERN`;设置项 `extraScanRules` 直接写 `settings.json`,打包与安装都并入扫描器(页面不暴露)。
89
- - 压缩:`PRECOMPRESSED_EXT` 里的扩展名直接存储,>2 MiB 用 deflate 6 级,其余 9 级。
90
- - 清单:`extensions` 字段留给二次开发,安装端原样保留;`schema` 高于支持版本时报「请先升级 dsh-modpack-kit」。
91
- - 目录:`CATALOG_SOURCES` 换地址;`catalogRefreshHours`(1~168)与 `catalogPageSize`(5~100)可调;新增分区不用改代码,读 `metadata.categories`,`CATEGORY_FALLBACK` 只是首次同步前的兜底。
92
- - 显示位:`client.js` 的 `PLACEMENT_MOUNTS` 每组开关对应一组槽位,加第四个位置就往里加一组并在设置页加开关。
93
- - 分组:`lib/groups.mjs` 的 `readMarketGroups` / `groupViews` / `hasMarket` / `applyMarketGroups`;`status` 下发 `groups`、`ungrouped`、`groupSource`。
90
+ - 路由:Host 能力全在 `/dsh-modpack-kit/api/*`,界面只是消费者。
91
+ - 安装:`context.installBundle` 优先,缺省或抛错退回 `context.runCli`。
92
+ - 扫描 / 擦除:`scanEntries(entries, { extraRules })`、`redactConfig(value)`;设置项 `extraScanRules` 直接写 `settings.json` 即并入。
93
+ - 清单:`extensions` 字段留给二次开发;`schema` 高于支持版本时报「请先升级」。
94
+ - 目录:`CATALOG_SOURCES`、`catalogRefreshHours`、`catalogPageSize` 可调,分区读 `metadata.categories`。
95
+ - 显示位与分组:`PLACEMENT_MOUNTS` 加位置;`lib/groups.mjs` 的 `readMarketGroups` / `groupViews` / `hasMarket` / `applyMarketGroups`。
94
96
 
95
97
  ## 已知限制
96
98
 
97
- - 只打 npm 上发布的包或本机已装目录,不处理 git 仓库直装。
99
+ - 只处理 npm 上发布的包与本机已装目录,不处理 git 直装。
98
100
  - 配置抓取走 YAML 子集解析,遇到不支持的写法整体放弃并提示,不猜。
99
- - peer 依赖只报「缺失/冲突」;`optional` 的 peer 不影响结论。
100
- - 扫描是启发式的,会漏也会误报;安装效果需重启 DSH 才能确认。
101
- - 目录是市场 npm 侧的条目(约 5600 条),只能从 GitHub 装的不在其中;索引 24 小时内不重复取。
101
+ - peer 依赖只报「缺失/冲突」,`optional` 不影响结论;扫描是启发式的,会漏也会误报。
102
+ - 装完需重启 DSH 才能确认效果。
102
103
 
103
104
  ## 合规
104
105
 
package/index.js CHANGED
@@ -7,9 +7,9 @@
7
7
  import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import { randomBytes } from 'node:crypto'
10
- import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
10
+ import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, clearHistory, removeHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
11
11
  import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
12
- import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime } from './lib/registry.mjs'
12
+ import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime, probeRegistry } from './lib/registry.mjs'
13
13
  import { buildPack, PackRefused } from './lib/pack.mjs'
14
14
  import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
15
15
  import { checkCompatibility } from './lib/compat.mjs'
@@ -20,7 +20,7 @@ import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugi
20
20
  import { parseYaml } from './lib/yamlish.mjs'
21
21
  import { readPatch } from './lib/profile.mjs'
22
22
  import { buildReadme } from './lib/manifest.mjs'
23
- import { sendJson as json, readBody, readRawBody, asJson, MAX_JSON_BODY, MAX_DROP_BODY } from './lib/http.mjs'
23
+ import { sendJson as json, readBody, readRawBody, readJsonBody, MAX_JSON_BODY, MAX_DROP_BODY } from './lib/http.mjs'
24
24
 
25
25
  const VERSION = (() => {
26
26
  try { return JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version || '0.0.0' } catch { return '0.0.0' }
@@ -198,6 +198,73 @@ export default {
198
198
  try { return listInstalled(profileDir()) } catch { return [] }
199
199
  }
200
200
 
201
+ // 三种策略能不能选:按「这次勾了哪些插件」实时算,客户端拿去做卡片灰显与原因弹窗;
202
+ // 打包时也再算一遍,挡住「界面上换了插件、策略却没跟着变」的情况。
203
+ const computePlan = (selection) => {
204
+ const installed = installedOrEmpty()
205
+ // spec 可能是 名字@版本,也可能是纯版本;统一抠出版本号再判能不能按版本装
206
+ const versionOf = (item, entry) => {
207
+ const spec = String(item.spec || '')
208
+ const fromSpec = spec.includes('@') && !spec.startsWith('@') ? spec.slice(spec.lastIndexOf('@') + 1) : spec
209
+ const candidates = [item.version, fromSpec, entry && entry.version]
210
+ for (const value of candidates) {
211
+ const text = String(value || '')
212
+ if (/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(text) && text !== '0.0.0') return text
213
+ }
214
+ return ''
215
+ }
216
+ const rows = selection.map((item) => {
217
+ const name = String(item.name || '')
218
+ const entry = installed.find((p) => p.name === name)
219
+ const version = versionOf(item, entry)
220
+ const local = Boolean(entry)
221
+ const market = item.source === 'npm' || item.source === 'market'
222
+ const custom = item.choice === 'custom'
223
+ return { name, version, semver: Boolean(version), local, market, custom }
224
+ })
225
+ const noCode = rows.filter((r) => !r.local && r.market)
226
+ const noVersion = rows.filter((r) => !r.semver)
227
+ const customRows = rows.filter((r) => r.custom)
228
+ const names = (list) => list.slice(0, 6).map((r) => r.name).join('、') + (list.length > 6 ? ' 等 ' + list.length + ' 个' : '')
229
+ const liteBlockers = []
230
+ if (noVersion.length) liteBlockers.push({ kind: 'version', text: '这些插件没有确定的版本号,安装时找不到对应的包:' + names(noVersion) })
231
+ if (customRows.length) liteBlockers.push({ kind: 'config', text: '给这些插件选了「自定义配置」,轻量包只记版本、带不走配置与数据:' + names(customRows) + '(改回「插件预设」,或换完整包 / 混合包)' })
232
+ const hybridBlockers = []
233
+ const noCodeNoVersion = noVersion.filter((r) => !r.local)
234
+ if (noCodeNoVersion.length) hybridBlockers.push({ kind: 'version', text: '这些插件没有确定的版本号,本机又没装、取不到代码:' + names(noCodeNoVersion) })
235
+ const strategies = [
236
+ {
237
+ id: 'full',
238
+ title: '完整包(懒人包)',
239
+ online: false,
240
+ ok: true,
241
+ reason: '',
242
+ blockers: [],
243
+ note: '插件本体一起装进包,不联网也能装;有网时优先按市场版本装(profile 依赖是 ^版本,插件市场认成市场版),离线才退回包内副本、显示本地安装。允许带自定义配置与数据。',
244
+ },
245
+ {
246
+ id: 'lite',
247
+ title: '仅下载码(轻量包)',
248
+ online: true,
249
+ ok: liteBlockers.length === 0,
250
+ reason: liteBlockers.map((b) => b.text).join(';'),
251
+ blockers: liteBlockers,
252
+ note: '只记 名字@版本,体积最小;安装时必须联网从市场取包,不带自定义配置与数据。',
253
+ },
254
+ {
255
+ id: 'hybrid',
256
+ title: '混合包(轻量为主 + 必要的完整)',
257
+ online: true,
258
+ ok: hybridBlockers.length === 0,
259
+ reason: hybridBlockers.map((b) => b.text).join(';'),
260
+ blockers: hybridBlockers,
261
+ note: '能按版本装的就只记 名字@版本(安装时联网取包);没有确定版本、或者要带走本机改动的插件,连代码一起打进来(这部分安装时不用联网)。配置/数据/补丁片段照样带。',
262
+ },
263
+ ]
264
+ if (noCode.length > 0) strategies[0].note += '(其中 ' + names(noCode) + ' 本机没有代码,打包时要联网取一次)'
265
+ return { strategies, plugins: rows, counts: { selected: rows.length, custom: customRows.length, noVersion: noVersion.length, localOnly: rows.filter((r) => r.local).length } }
266
+ }
267
+
201
268
  const compatFor = (manifest) => checkCompatibility(manifest.plugins, {
202
269
  installed: installedOrEmpty(),
203
270
  dshVersion: (() => { try { return dshVersion(profileDir()) } catch { return '' } })(),
@@ -215,7 +282,7 @@ export default {
215
282
  route('/dsh-modpack-kit/api/settings', async (req, res) => {
216
283
  if (req.method === 'GET') { json(res, 200, { ok: true, config, defaults: DEFAULT_CONFIG }); return }
217
284
  if (!needPost(req, res)) return
218
- const body = asJson(await readBody(req), null)
285
+ const body = await readJsonBody(req, null)
219
286
  if (!body || typeof body !== 'object') { json(res, 400, { ok: false, error: '请求体不是对象' }); return }
220
287
  const patch = body.patch && typeof body.patch === 'object' ? body.patch : body
221
288
  const next = { ...config }
@@ -257,7 +324,7 @@ export default {
257
324
 
258
325
  route('/dsh-modpack-kit/api/catalog/lookup', async (req, res) => {
259
326
  if (!needPost(req, res)) return
260
- const body = asJson(await readBody(req), {}) || {}
327
+ const body = await readJsonBody(req)
261
328
  const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string').slice(0, 400) : []
262
329
  try {
263
330
  json(res, 200, { ok: true, items: lookupPlugins(config, names) })
@@ -268,7 +335,7 @@ export default {
268
335
 
269
336
  route('/dsh-modpack-kit/api/catalog/sync', async (req, res) => {
270
337
  if (!needPost(req, res)) return
271
- const body = asJson(await readBody(req), {}) || {}
338
+ const body = await readJsonBody(req)
272
339
  const hours = Math.max(1, Number(config.catalogRefreshHours) || 24)
273
340
  const result = await syncCatalog(config, { force: body.force === true, maxAgeMs: hours * 3600 * 1000 })
274
341
  if (result.ok && !result.skipped) appendLog(`目录同步 ${result.count} 条(${result.source},${Math.round((result.ms || 0) / 100) / 10}s)`)
@@ -277,7 +344,7 @@ export default {
277
344
 
278
345
  route('/dsh-modpack-kit/api/catalog/search', async (req, res) => {
279
346
  if (!needPost(req, res)) return
280
- const body = asJson(await readBody(req), {}) || {}
347
+ const body = await readJsonBody(req)
281
348
  const localPlugins = installedOrEmpty().filter((p) => p.isPlugin && p.isDirect)
282
349
  const localCategories = categoryMapFor(config, localPlugins.map((p) => p.name))
283
350
  const installed = localPlugins.map((p) => ({
@@ -303,10 +370,10 @@ export default {
303
370
  // —— 查某个包的可用版本 ——
304
371
  route('/dsh-modpack-kit/api/versions', async (req, res) => {
305
372
  if (!needPost(req, res)) return
306
- const body = asJson(await readBody(req), {})
373
+ const body = await readJsonBody(req)
307
374
  const name = String(body.name || '')
308
375
  try {
309
- const { meta, registry } = await npmMetadata(name, config)
376
+ const { meta, registry } = await npmMetadata(name, config, { full: true })
310
377
  const versions = Object.keys((meta && meta.versions) || {})
311
378
  .map((v) => ({ version: v, time: (meta.time && meta.time[v]) || '', deprecated: Boolean(meta.versions[v] && meta.versions[v].deprecated) }))
312
379
  .reverse()
@@ -456,6 +523,11 @@ export default {
456
523
  }
457
524
  }),
458
525
  options: {
526
+ strategy: (() => {
527
+ const raw = String(options.strategy || options.format || '').toLowerCase()
528
+ if (raw === 'lite' || raw === 'hybrid' || raw === 'full') return raw
529
+ return options.includePayload === false ? 'lite' : 'full'
530
+ })(),
459
531
  includePayload: options.includePayload !== false,
460
532
  includeConfig: options.includeConfig !== false,
461
533
  includeLocalEdits: options.includeLocalEdits === true,
@@ -597,11 +669,31 @@ export default {
597
669
  return job
598
670
  }
599
671
 
672
+ // 三种打包策略能不能选:客户端据此把卡片画成可点/灰掉,灰掉时给出原因。
673
+ route('/dsh-modpack-kit/api/pack/plan', async (req, res) => {
674
+ if (!needPost(req, res)) return
675
+ {
676
+ const body = await readJsonBody(req)
677
+ const selection = Array.isArray(body.selection) ? body.selection : []
678
+ if (selection.length === 0) return json(res, 400, { ok: false, error: '还没选插件' })
679
+ return json(res, 200, { ok: true, ...computePlan(selection) })
680
+ }
681
+ })
682
+
600
683
  route('/dsh-modpack-kit/api/pack', async (req, res) => {
601
684
  if (!needPost(req, res)) return
602
- const body = asJson(await readBody(req), {})
685
+ const body = await readJsonBody(req)
603
686
  const selection = Array.isArray(body.selection) ? body.selection : []
604
687
  if (selection.length === 0) { json(res, 400, { ok: false, error: '没有选择任何插件' }); return }
688
+ const strategy = String((body.options && body.options.strategy) || 'full')
689
+ if (strategy === 'lite' || strategy === 'hybrid') {
690
+ const plan = computePlan(selection)
691
+ const chosen = plan.strategies.find((entry) => entry.id === strategy)
692
+ if (chosen && chosen.ok === false) {
693
+ json(res, 400, { ok: false, error: '这个打包策略现在不适用:' + chosen.reason, plan })
694
+ return
695
+ }
696
+ }
605
697
  if (body.async === true || body.background === true) {
606
698
  const job = startPackJob(body)
607
699
  json(res, 200, { ok: true, async: true, job: publicJob(job) })
@@ -614,7 +706,7 @@ export default {
614
706
  // 风险停下来之后:只有「我知道在干什么」,点它就在同一个任务里接着跑完
615
707
  route('/dsh-modpack-kit/api/jobs/ack', async (req, res) => {
616
708
  if (!needPost(req, res)) return
617
- const body = asJson(await readBody(req), {})
709
+ const body = await readJsonBody(req)
618
710
  const job = jobs.get(String(body.id || ''))
619
711
  if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
620
712
  if (!job.risk) { json(res, 400, { ok: false, error: '这个任务没有风险项,不需要确认' }); return }
@@ -649,7 +741,7 @@ export default {
649
741
 
650
742
  route('/dsh-modpack-kit/api/jobs/dismiss', async (req, res) => {
651
743
  if (!needPost(req, res)) return
652
- const body = asJson(await readBody(req), {})
744
+ const body = await readJsonBody(req)
653
745
  const id = String(body.id || '')
654
746
  const job = jobs.get(id)
655
747
  if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已经删了)' }); return }
@@ -681,7 +773,7 @@ export default {
681
773
 
682
774
  route('/dsh-modpack-kit/api/jobs/cancel', async (req, res) => {
683
775
  if (!needPost(req, res)) return
684
- const body = asJson(await readBody(req), {})
776
+ const body = await readJsonBody(req)
685
777
  const job = jobs.get(String(body.id || ''))
686
778
  if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
687
779
  if (job.status !== 'running') {
@@ -711,7 +803,7 @@ export default {
711
803
  // —— 下载 / 落盘 ——
712
804
  route('/dsh-modpack-kit/api/download', async (req, res) => {
713
805
  if (!needPost(req, res)) return
714
- const body = asJson(await readBody(req), {})
806
+ const body = await readJsonBody(req)
715
807
  const item = pending.get(String(body.token || ''))
716
808
  if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
717
809
  const safeName = String(body.fileName || item.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
@@ -726,7 +818,7 @@ export default {
726
818
 
727
819
  route('/dsh-modpack-kit/api/save', async (req, res) => {
728
820
  if (!needPost(req, res)) return
729
- const body = asJson(await readBody(req), {})
821
+ const body = await readJsonBody(req)
730
822
  const item = pending.get(String(body.token || ''))
731
823
  if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
732
824
  const paths = pathsFor(config)
@@ -771,7 +863,7 @@ export default {
771
863
  return
772
864
  }
773
865
  if (req.method !== 'POST') { json(res, 405, { ok: false }); return }
774
- const body = asJson(await readBody(req), {})
866
+ const body = await readJsonBody(req)
775
867
  const raw = String(body.dir || '').trim()
776
868
  const dir = raw ? path.resolve(raw) : pathsFor(config).packs
777
869
  const listed = listPacks(dir)
@@ -786,7 +878,7 @@ export default {
786
878
  try {
787
879
  if (contentType.includes('application/json')) {
788
880
  // 有些环境不许 POST 二进制,界面会退回 base64:这里同样收
789
- const body = asJson(await readBody(req, MAX_DROP_BODY), {}) || {}
881
+ const body = await readJsonBody(req, {}, MAX_DROP_BODY)
790
882
  const raw = typeof body.data === 'string' ? body.data : ''
791
883
  if (!raw) { json(res, 400, { ok: false, error: '没有收到整合包内容' }); return }
792
884
  bytes = Buffer.from(raw, 'base64')
@@ -846,7 +938,7 @@ export default {
846
938
  // —— 预览 ——
847
939
  route('/dsh-modpack-kit/api/inspect', async (req, res) => {
848
940
  if (!needPost(req, res)) return
849
- const body = asJson(await readBody(req), {})
941
+ const body = await readJsonBody(req)
850
942
  try {
851
943
  const inspected = await inspectInput(body)
852
944
  const compat = compatFor(inspected.manifest)
@@ -898,6 +990,8 @@ export default {
898
990
  only: Array.isArray(body.only) && body.only.length > 0 ? body.only.map(String) : null,
899
991
  // 联网且有插件市场时优先按市场版本装(默认开;请求里能逐次关掉)
900
992
  preferMarket: typeof body.preferMarket === 'boolean' ? body.preferMarket : config.preferMarketOnInstall !== false,
993
+ // 离线安装:true = 不问 registry 直接用包里自带的;不给 = 由 installPack 先探一下网络决定
994
+ offline: typeof body.offline === 'boolean' ? body.offline : undefined,
901
995
  })
902
996
 
903
997
  const runInstall = async (inspected, body, job) => {
@@ -926,9 +1020,11 @@ export default {
926
1020
  manifest: inspected.manifest,
927
1021
  entries: inspected.entries,
928
1022
  config,
929
- options: { ...options, onProgress: (event) => push(event.pct, event.note) },
1023
+ options: { preferMarketOnInstall: options.preferMarketOnInstall !== false || config.preferMarketOnInstall !== false, ...options, onProgress: (event) => push(event.pct, event.note) },
930
1024
  context: {
931
1025
  profileDir: profileDir(),
1026
+ // 离线判断:registry 探不通就直接用包里自带的,别让每个插件都等超时
1027
+ probeRegistry: () => probeRegistry(config),
932
1028
  // 优先用宿主自带的插件管理器(pnpm、激活、重启判定都由它负责);
933
1029
  // 服务不在或调用抛错时 installPack 会自动退回 dsh 命令行。
934
1030
  installBundle: (() => {
@@ -939,7 +1035,7 @@ export default {
939
1035
  // 联网且市场可用时,优先按市场版本装(能用就返回 name@version,用不了返回 null 走包内)
940
1036
  resolveMarket: async (plugin) => {
941
1037
  try {
942
- const { meta } = await npmMetadata(plugin.name, config)
1038
+ const { meta } = await npmMetadata(plugin.name, config, { version: plugin.version || plugin.spec || '' })
943
1039
  const version = pickVersion(meta, plugin.version || plugin.spec || '') || pickVersion(meta, '')
944
1040
  if (!version) return null
945
1041
  appendLog('market ' + plugin.name + '@' + version + ' 优先于包内 ' + (plugin.version || '(未标版本)'))
@@ -949,6 +1045,12 @@ export default {
949
1045
  return null
950
1046
  }
951
1047
  },
1048
+ // 轻量包:只把条目取回内存(不落临时目录),扫描与安装都在内存里完成
1049
+ resolveSourceEntries: async (plugin) => {
1050
+ const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
1051
+ appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry + ' (memory, ' + downloaded.entries.length + ' files)')
1052
+ return downloaded.entries
1053
+ },
952
1054
  resolveSource: async (plugin, packRoot) => {
953
1055
  const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
954
1056
  const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
@@ -1021,7 +1123,7 @@ export default {
1021
1123
 
1022
1124
  route('/dsh-modpack-kit/api/install', async (req, res) => {
1023
1125
  if (!needPost(req, res)) return
1024
- const body = asJson(await readBody(req), {})
1126
+ const body = await readJsonBody(req)
1025
1127
  if (body.async === true || body.background === true) {
1026
1128
  const job = startInstallJob(body, body.label ? String(body.label) : undefined)
1027
1129
  json(res, 200, { ok: true, async: true, job: publicJob(job) })
@@ -1034,7 +1136,7 @@ export default {
1034
1136
  // 装完的追问:把刚才跳过的那些换成包内版本
1035
1137
  route('/dsh-modpack-kit/api/install/replace', async (req, res) => {
1036
1138
  if (!needPost(req, res)) return
1037
- const body = asJson(await readBody(req), {})
1139
+ const body = await readJsonBody(req)
1038
1140
  const token = String(body.token || '')
1039
1141
  const item = pendingInstalls.get(token)
1040
1142
  if (!item) { json(res, 400, { ok: false, error: '这次安装的上下文已过期,请重新读一遍整合包' }); return }
@@ -1063,6 +1165,21 @@ export default {
1063
1165
  json(res, 200, { ok: true, items: readHistory().slice().reverse() })
1064
1166
  })
1065
1167
 
1168
+ // 清空最近记录(文件留着,只是写空)
1169
+ route('/dsh-modpack-kit/api/history/clear', async (req, res) => {
1170
+ if (!needPost(req, res)) return
1171
+ json(res, 200, { ok: true, items: clearHistory() })
1172
+ })
1173
+
1174
+ // 删掉某一条:按 at 时间戳匹配
1175
+ route('/dsh-modpack-kit/api/history/remove', async (req, res) => {
1176
+ if (!needPost(req, res)) return
1177
+ const body = await readJsonBody(req)
1178
+ const items = removeHistory(body.at)
1179
+ appendLog('history remove ' + String((body && body.at) || '') + ' left=' + items.length)
1180
+ json(res, 200, { ok: true, items })
1181
+ })
1182
+
1066
1183
  route('/dsh-modpack-kit/api/plugin-summary', async (req, res) => {
1067
1184
  if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
1068
1185
  const installed = installedOrEmpty()
package/lib/http.mjs CHANGED
@@ -33,6 +33,9 @@ export const readBody = (req, limit = MAX_JSON_BODY) => collect(req, limit, '请
33
33
 
34
34
  export const readRawBody = (req, limit = MAX_DROP_BODY) => collect(req, limit, '整合包太大:上限 ' + Math.round(limit / 1024 / 1024) + ' MB')
35
35
 
36
+ // 大部分路由只要一个对象:读不到、不是 JSON、是 null 都给同一份缺省值,免得每处都写 asJson(await readBody(req), {}) || {}
37
+ export const readJsonBody = async (req, fallback = {}, limit = MAX_JSON_BODY) => asJson(await readBody(req, limit), fallback)
38
+
36
39
  export function asJson(text, fallback) {
37
40
  try { return JSON.parse(text) } catch { return fallback }
38
41
  }