@dsh-plugin/dsh-pack-plugin 0.0.0-stage → 0.0.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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -3
  3. package/cordis.patch.yml +9 -0
  4. package/icons/folder-zip-line.svg +1 -0
  5. package/lib/ball.js +597 -0
  6. package/lib/client.js +2934 -0
  7. package/lib/host.js +51745 -0
  8. package/lib/migrate-helper.js +35346 -0
  9. package/lib/progress-main.cjs +79 -0
  10. package/lib/progress-window.ps1 +114 -0
  11. package/lib/progress.html +126 -0
  12. package/lib/publish-to-github/SKILL.md +132 -0
  13. package/package.json +77 -4
  14. package/src/ball-entry.js +5 -0
  15. package/src/ball-host.js +99 -0
  16. package/src/ball-settings.js +352 -0
  17. package/src/ball.js +418 -0
  18. package/src/channel.js +12 -0
  19. package/src/client-plugin.js +58 -0
  20. package/src/client-rpc.js +14 -0
  21. package/src/client.js +5 -0
  22. package/src/core/discovery.js +192 -0
  23. package/src/core/dspack.js +93 -0
  24. package/src/core/extension-files.js +102 -0
  25. package/src/core/extension-install.js +295 -0
  26. package/src/core/extension-patch.js +369 -0
  27. package/src/core/extension-skills.js +164 -0
  28. package/src/core/extension-validate.js +127 -0
  29. package/src/core/extensions.js +207 -0
  30. package/src/core/home-store.js +32 -0
  31. package/src/core/host.js +149 -0
  32. package/src/core/index.js +59 -0
  33. package/src/core/inspect.js +162 -0
  34. package/src/core/install.js +775 -0
  35. package/src/core/managed-install.js +84 -0
  36. package/src/core/manifest.js +717 -0
  37. package/src/core/market.js +268 -0
  38. package/src/core/mcp-composition.js +189 -0
  39. package/src/core/mcp-install.js +112 -0
  40. package/src/core/mcp-transport.js +116 -0
  41. package/src/core/pack.js +371 -0
  42. package/src/core/plugin-metadata.js +355 -0
  43. package/src/core/registry.js +316 -0
  44. package/src/core/repo.js +339 -0
  45. package/src/core/scan.js +78 -0
  46. package/src/core/security.js +101 -0
  47. package/src/core/special.js +50 -0
  48. package/src/core/tar.js +103 -0
  49. package/src/core/update-config.js +234 -0
  50. package/src/core/update.js +792 -0
  51. package/src/core/vendored.js +715 -0
  52. package/src/core/workspace.js +95 -0
  53. package/src/endpoints.js +455 -0
  54. package/src/ensure-manager.js +186 -0
  55. package/src/host-node.js +625 -0
  56. package/src/host.js +17 -0
  57. package/src/index.d.ts +7 -0
  58. package/src/index.js +39 -0
  59. package/src/junction.js +142 -0
  60. package/src/migrate-helper.js +225 -0
  61. package/src/migrate.js +56 -0
  62. package/src/packaged.js +9 -0
  63. package/src/profiles.js +106 -0
  64. package/src/progress-main.cjs +79 -0
  65. package/src/progress-window.ps1 +114 -0
  66. package/src/progress.html +126 -0
  67. package/src/progress.js +132 -0
  68. package/src/rpc.js +157 -0
  69. package/src/runtime.js +43 -0
  70. package/src/section-gate.js +50 -0
  71. package/src/settings-nav-icon.js +188 -0
  72. package/src/settings.js +1611 -0
  73. package/src/skills/index.js +90 -0
  74. package/src/skills/publish-to-github/SKILL.md +132 -0
  75. package/src/tasks.js +145 -0
  76. package/src/v6-dialogs.js +312 -0
@@ -0,0 +1,715 @@
1
+ // v5 r2 vendored 依赖内嵌(specs/manifest/v5.md §12 + specs/pack-structure/v3.md §8)——消费侧实现。
2
+ //
3
+ // 职责:把「显式 vendored{}」与「DSHL vendor: 方言(v3 §8.5)」统一归一为
4
+ // 「坐标 → 校验过的 tarball」,并在**阶段 0(未动任何文件)**完成对账与逐 tarball
5
+ // sha256/size 预验——装前发现损坏优于装到一半发现(manifest v5 §11.1)。
6
+ //
7
+ // 安装路径(统一算法 v3 §8.3):
8
+ // - 显式 vendored 条目:tarball 落盘到 <target>/vendor-blobs/,重建 package.json 时把
9
+ // 该坐标的依赖 spec 改写为 `file:vendor-blobs/...`(manifest 不动;规范对 git 坐标
10
+ // 明确允许 file: 引用,npm 坐标以 file: 达到与「store 预填充」等价的本地优先效果),
11
+ // 随后 `pnpm install --prefer-offline`——本地命中的直接用副本,未命中的走 registry。
12
+ // - DSHL 方言条目(dependencies 值 = `vendor:<file>.tgz`):tarball 校验后直挂
13
+ // (direct-mount,v3 §8.3)进 node_modules/<name>,并从重建的 package.json 依赖中剔除。
14
+ import { untar, buildTarball } from './tar.js';
15
+ import { parseGitCoord, parsePkgGitSpec, VENDORED_REASONS } from './manifest.js';
16
+ import { fetchPluginTarball, installedPluginSource, registryUrl } from './registry.js';
17
+
18
+ const decoder = new TextDecoder();
19
+
20
+ /** DSHL 方言依赖 spec 前缀(v3 §8.5:`vendor:<file>.tgz`)。 */
21
+ const DIALECT_SPEC = /^vendor:/i;
22
+
23
+ /** zip entries 里 vendor/ 下的**文件**条目(排除 vendor.json 本身与目录占位)。 */
24
+ function vendorFileEntries(entries) {
25
+ return Object.keys(entries).filter((p) => p.startsWith('vendor/') && p !== 'vendor/vendor.json' && !p.endsWith('/'));
26
+ }
27
+
28
+ /** 所有形态的依赖坐标合集(profile:dependencies;dshhome:各 profile 依赖并集)。 */
29
+ export function allDependencyCoords(manifest) {
30
+ if (manifest?.type === 'dshhome') {
31
+ const set = new Set();
32
+ for (const u of Object.values(manifest.profiles ?? {})) {
33
+ for (const k of Object.keys(u?.dependencies ?? {})) set.add(k);
34
+ }
35
+ return set;
36
+ }
37
+ return new Set(Object.keys(manifest?.dependencies ?? {}));
38
+ }
39
+
40
+ /**
41
+ * 解析 DSHL 方言(消费宽容,生产禁止):vendor/vendor.json `{packages:[{file,name,sha256}]}`
42
+ * → 隐式 vendored 条目(key = 包名)。无方言痕迹时返回 {}。
43
+ */
44
+ function dialectEntries(manifest, entries) {
45
+ const raw = entries['vendor/vendor.json'];
46
+ if (!raw) return {};
47
+ let json;
48
+ try {
49
+ json = JSON.parse(decoder.decode(raw));
50
+ } catch {
51
+ throw new Error('vendor/vendor.json 不是有效 JSON(DSHL 方言包损坏)');
52
+ }
53
+ const out = {};
54
+ for (const p of json?.packages ?? []) {
55
+ if (!p || typeof p.file !== 'string' || !p.file) continue;
56
+ if (typeof p.name !== 'string' || !p.name) continue;
57
+ if (typeof p.sha256 !== 'string' || !/^[0-9a-f]{64}$/i.test(p.sha256)) continue;
58
+ // 方言 file 名同样禁止路径穿越
59
+ if (p.file.includes('..') || p.file.startsWith('/') || /^[a-zA-Z]:/.test(p.file)) continue;
60
+ out[p.name] = { path: `vendor/${p.file}`, sha256: p.sha256.toLowerCase(), size: null, version: null, dialect: true };
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /** 安全的 vendor/ 内相对路径校验:必须落在 vendor/ 下、以 .tgz 结尾、无 `..` / 盘符 / 绝对路径。 */
66
+ function safeVendorPath(p) {
67
+ const rel = String(p ?? '').replace(/\\/g, '/');
68
+ if (!rel.startsWith('vendor/')) throw new Error(`vendored[].path 必须位于 vendor/ 下:${p}`);
69
+ if (!rel.endsWith('.tgz')) throw new Error(`vendored[].path 必须是 .tgz:${p}`);
70
+ if (rel.split('/').includes('..')) throw new Error(`vendored[].path 含危险段 '..':${p}`);
71
+ return rel;
72
+ }
73
+
74
+ /** 依赖 spec 是否为 DSHL 方言(`vendor:<file>.tgz`)。 */
75
+ export function isDialectSpec(spec) {
76
+ return typeof spec === 'string' && DIALECT_SPEC.test(spec);
77
+ }
78
+
79
+ /**
80
+ * 阶段 0:归一显式 vendored{} 与 DSHL 方言 → 对账 → 逐 tarball sha256/size 预验。
81
+ * 任一不满足立即抛错(拒装),保证「装前发现」。
82
+ *
83
+ * @returns {{
84
+ * active: boolean,
85
+ * byCoord: Map<string, {path:string, sha256:string, size:number|null, version:string|null,
86
+ * dialect?:boolean, bytes:Uint8Array}>,
87
+ * }}
88
+ * active=false 表示包内无任何 vendored 内容(r1 包,行为与修订前完全一致)。
89
+ */
90
+ export async function resolveVendoredPlan(host, manifest, entries, log = () => {}) {
91
+ const files = vendorFileEntries(entries);
92
+ const explicit = manifest.vendored && typeof manifest.vendored === 'object' && !Array.isArray(manifest.vendored) ? manifest.vendored : {};
93
+ const dialect = dialectEntries(manifest, entries);
94
+ if (!files.length && !Object.keys(explicit).length && !Object.keys(dialect).length) {
95
+ return { active: false, byCoord: new Map() };
96
+ }
97
+
98
+ // 显式条目优先(§8.5:与方言并存时显式 vendored{} 优先)
99
+ const byCoord = new Map(Object.entries(dialect).map(([k, v]) => [k, { ...v }]));
100
+ for (const [coord, e] of Object.entries(explicit)) byCoord.set(coord, { ...e });
101
+
102
+ // 对账:vendored key 必须 ∈ dependencies(dshhome 为各 profile 依赖并集)∪ lockfile packages
103
+ // (v5 §12 约束 1:full 档闭包条目以随包 pnpm-lock.yaml 为准放行,key = npm 包名)
104
+ const deps = allDependencyCoords(manifest);
105
+ let lockNames = null;
106
+ if (entries['pnpm-lock.yaml']) lockNames = lockfilePackageNames(decoder.decode(entries['pnpm-lock.yaml']));
107
+ for (const coord of byCoord.keys()) {
108
+ if (!deps.has(coord) && !lockNames?.has(coord)) {
109
+ throw new Error(`vendored 条目「${coord}」不在 dependencies ∪ lockfile packages 中(对账失败,见 manifest v5 §12 约束 1)`);
110
+ }
111
+ }
112
+
113
+ // vendor/ 内只允许 .tgz 且必须逐一经 vendored 登记(§8.2:未登记文件 → 拒装)
114
+ const registered = new Set([...byCoord.values()].map((e) => safeVendorPath(e.path)));
115
+ for (const p of files) {
116
+ if (!p.endsWith('.tgz')) throw new Error(`vendor/ 内只允许 .tgz 文件(发现 ${p})`);
117
+ if (!registered.has(p)) throw new Error(`vendor/ 内存在未登记文件:${p}(vendored 清单无此条目)→ 拒装`);
118
+ }
119
+
120
+ // 逐 tarball sha256 + size 预验(装前发现优于装到一半发现)
121
+ for (const [coord, e] of byCoord) {
122
+ const rel = safeVendorPath(e.path);
123
+ const bytes = entries[rel];
124
+ if (!bytes || !bytes.length) throw new Error(`vendored 条目「${coord}」的 tarball 缺失或为空:${rel}`);
125
+ if (Number.isInteger(e.size) && e.size > 0 && e.size !== bytes.length) {
126
+ throw new Error(`vendored「${coord}」size 不符:期望 ${e.size},实际 ${bytes.length}`);
127
+ }
128
+ const sha = await host.sha256(bytes);
129
+ if (sha !== String(e.sha256 || '').toLowerCase()) {
130
+ throw new Error(`vendored「${coord}」sha256 校验失败:期望 ${e.sha256},实际 ${sha}`);
131
+ }
132
+ e.bytes = bytes;
133
+ log(`vendored 预检通过:${coord} → ${rel}(${bytes.length} 字节)`);
134
+ }
135
+
136
+ return { active: true, byCoord };
137
+ }
138
+
139
+ /**
140
+ * 直挂(direct-mount,v3 §8.3):把方言 tarball 解进 node_modules/<name>(剥掉 `package/` 前缀)。
141
+ * 只用于 DSHL 方言叶子插件;带传递依赖的包必须走统一算法。
142
+ */
143
+ export async function directMount(host, target, name, entry, log = () => {}) {
144
+ const files = untar(entry.bytes);
145
+ let count = 0;
146
+ for (const [p, data] of Object.entries(files)) {
147
+ const rel = p.replace(/^package\//, '');
148
+ if (!rel || rel === 'package') continue;
149
+ if (rel.split('/').includes('..')) throw new Error(`tarball 内路径含 '..':${p}(拒绝直挂)`);
150
+ const dest = host.joinPath(target, 'node_modules', name, ...rel.split('/'));
151
+ await host.writeFile(dest, data);
152
+ count += 1;
153
+ }
154
+ if (!count) throw new Error(`vendored tarball 直挂失败:${name}(tarball 内无 package/ 文件)`);
155
+ log(`直挂 ${name} → node_modules/${name}(${count} 个文件)`);
156
+ return count;
157
+ }
158
+
159
+ /**
160
+ * 重建 package.json 时的依赖 spec 决策:
161
+ * - DSHL 方言 spec → 返回 null(从依赖中剔除,走直挂);
162
+ * - 显式 vendored 坐标 → 返回 `file:vendor-blobs/<dir>/<file>`(tarball 已由调用方落盘);
163
+ * - 其余 → 原样(coordsToPkgDeps 的产物)。
164
+ *
165
+ * @param {string} pkgName coordsToPkgDeps 产出的包名(git 坐标已折算为短名)
166
+ * @param {string} coord manifest 侧原始坐标
167
+ */
168
+ export function vendorDepSpec(plan, coord, pkgName, blobRel) {
169
+ const entry = plan.byCoord.get(coord);
170
+ if (!entry) return undefined; // 非 vendored 坐标,调用方保持原 spec
171
+ if (entry.dialect) return null; // 方言:剔除依赖 + 直挂
172
+ return `file:${blobRel}`;
173
+ }
174
+
175
+ /** 坐标 → vendor-blobs 子目录名(§8.1 建议编码:非 [a-z0-9-] 段替换为 __)。 */
176
+ export function coordDirName(coord) {
177
+ return String(coord).replace(/[^a-zA-Z0-9-]+/g, '__');
178
+ }
179
+
180
+ /** tarball 在 vendor-blobs 下的相对路径('/' 分隔,供 file: spec 使用)。 */
181
+ export function blobRelPath(coord, entry) {
182
+ return `vendor-blobs/${coordDirName(coord)}/${entry.path.replace(/^vendor\//, '')}`;
183
+ }
184
+
185
+ /** 把 vendored tarball 落盘到 <target>/vendor-blobs/(file: 引用的实体)。 */
186
+ export async function materializeVendorBlobs(host, target, plan, coords, log = () => {}) {
187
+ const written = [];
188
+ for (const coord of coords) {
189
+ const entry = plan.byCoord.get(coord);
190
+ if (!entry || entry.dialect) continue;
191
+ const rel = blobRelPath(coord, entry);
192
+ await host.writeFile(host.joinPath(target, ...rel.split('/')), entry.bytes);
193
+ log(`写入 ${rel}(vendored tarball,${entry.bytes.length} 字节)`);
194
+ written.push(rel);
195
+ }
196
+ return written;
197
+ }
198
+
199
+ /* ---------------------------------------------------------------------------
200
+ * 闭包完整性检测(v3 §8.3:「离线可装」是覆盖完整性派生的属性,不是包的声明)
201
+ * 对照随包 pnpm-lock.yaml 的 packages:/snapshots: 区块,检查 vendored 是否覆盖全部依赖。
202
+ * 完整 → 启动器可自选严格 `pnpm install --offline`(零网络、缺件即报错)。
203
+ * ------------------------------------------------------------------------- */
204
+
205
+ /**
206
+ * 从 pnpm-lock.yaml 的 packages:/snapshots: 区块收集全部依赖条目(key `name@version` → {name, version})。
207
+ * 区块内条目缩进一致(标准 2 空格,以首个条目缩进为准),嵌套字段(resolution/dependencies…)更深,不收集。
208
+ * scoped 条目(`@scope/pkg@1.0.0`)取 lastIndexOf('@') 前为名;git 条目(`pkg@github:owner/repo#sha`)
209
+ * 版本为 `github:...` 整段;解析器别名 key(`pkg@1.0.0(browser)`)取括号前。
210
+ * packages: 与 snapshots: 会对同一 `name@version` 重复登记 → 按 `name@version` 去重。
211
+ * @returns {Array<{name: string, version: string}>|null} 无 packages/snapshots 条目时返回 null(无法判定)。
212
+ */
213
+ export function lockfilePackageEntries(lockText) {
214
+ if (!lockText) return null;
215
+ const out = [];
216
+ const seen = new Set();
217
+ let inSection = false;
218
+ let entryIndent = -1;
219
+ for (const line of String(lockText).split(/\r?\n/)) {
220
+ const trimmed = line.trim();
221
+ if (!trimmed) continue;
222
+ if (!inSection) {
223
+ if (/^(packages|snapshots):\s*$/.test(trimmed)) inSection = true;
224
+ continue;
225
+ }
226
+ const indent = line.length - line.trimStart().length;
227
+ if (indent === 0) {
228
+ // 其它顶层区块(importers: 等)→ 当前区块结束;packages:/snapshots: 连续出现则继续
229
+ if (!/^(packages|snapshots):\s*$/.test(trimmed)) inSection = false;
230
+ entryIndent = -1;
231
+ continue;
232
+ }
233
+ // key 匹配到行尾的 ':'(git 条目 key 含 ':',如 `'pkg@github:owner/repo#sha':`,不能用 [^:]+)
234
+ const key = line.match(/^\s*(.+):\s*$/);
235
+ if (!key) continue;
236
+ if (entryIndent === -1) entryIndent = indent;
237
+ if (indent !== entryIndent) continue; // 嵌套字段(resolution: / dependencies: / …)
238
+ let k = key[1].replace(/^['"]|['"]$/g, '').trim();
239
+ const paren = k.indexOf('('); // 解析器别名 key(如 "pkg@1.0.0(browser)")取括号前
240
+ if (paren > 0) k = k.slice(0, paren);
241
+ const name = k.startsWith('@') ? k.slice(0, k.lastIndexOf('@')) : k.split('@')[0];
242
+ if (!name) continue;
243
+ // 版本 = 名后余段(scoped 用 lastIndexOf;git 条目版本为 `github:...` 整段)
244
+ const version = k.length > name.length + 1 ? k.slice(name.length + 1) : '';
245
+ const dedupe = `${name}@${version}`;
246
+ if (seen.has(dedupe)) continue;
247
+ seen.add(dedupe);
248
+ out.push({ name, version });
249
+ }
250
+ return out.length ? out : null;
251
+ }
252
+
253
+ /**
254
+ * 从 pnpm-lock.yaml 的 packages:/snapshots: 区块收集全部依赖包名(`name@version` → `name`)。
255
+ * lockfilePackageEntries 的包名投影(既有调用方 computeOfflineCoverage 的兼容包装)。
256
+ * @returns {Set<string>|null} 无 packages/snapshots 条目时返回 null(无法判定)。
257
+ */
258
+ export function lockfilePackageNames(lockText) {
259
+ const entries = lockfilePackageEntries(lockText);
260
+ if (!entries) return null;
261
+ const names = new Set(entries.map((e) => e.name));
262
+ return names.size ? names : null;
263
+ }
264
+
265
+ /**
266
+ * 对照 lockfile 判定 vendored 闭包覆盖:lockfile 里每个依赖包名都能由 vendored 坐标提供 → complete。
267
+ * @returns {{complete: boolean, missing: string[], total: number}|null}
268
+ * null = 无法判定(无 vendor 活动条目 / lockfile 无 packages 条目),调用方保持 --prefer-offline。
269
+ */
270
+ export function computeOfflineCoverage(lockText, plan) {
271
+ if (!plan?.active) return null;
272
+ const names = lockfilePackageNames(lockText);
273
+ if (!names) return null;
274
+ const vendoredNames = new Set();
275
+ for (const [coord, e] of plan.byCoord) {
276
+ const git = parseGitCoord(coord);
277
+ vendoredNames.add(git ? git.name : coord);
278
+ // git 坐标:lockfile 以**包名**登记(如 `other-theme@github:owner/repo#sha`),
279
+ // 与仓库名折算可能不同 → 把 tarball 内 package.json 的真实包名一并计入覆盖集。
280
+ const tp = e?.bytes ? tarballPackageJson(e.bytes) : null;
281
+ if (tp?.name) vendoredNames.add(tp.name);
282
+ }
283
+ const missing = [...names].filter((n) => !vendoredNames.has(n));
284
+ return { complete: missing.length === 0, missing, total: names.size };
285
+ }
286
+
287
+ /* ---------------------------------------------------------------------------
288
+ * 导出侧(v3 §8.6 打包端义务):依赖清单(供 UI 手动勾选)+ 按选择内嵌 vendored。
289
+ *
290
+ * 设计:**手动选择为主**——UI 经 listProfileDependencies 列出依赖让作者勾选;
291
+ * 勾选后按坐标类型取件:
292
+ * - `file:vendor-blobs/...`(装过 vendored 包的 profile)→ 直接复用原 tarball 字节(round-trip);
293
+ * - npm 精确版本 → 先试 registry 取原件(字节一致);取不到(上游消失 / 断网)→ 从
294
+ * node_modules 重打包,版本按 §8.6 加 `-local.N` 后缀(上游不存在的 prerelease);
295
+ * - git 坐标 → 从 node_modules 重打包(不依赖 git 环境)。
296
+ * 重打包版本的「三处一致」(dependencies 值 / vendored[].version / tarball 内 version)
297
+ * 由本模块统一保证;安装端禁止改写包内字节(§8.6 第 6 条)。
298
+ * ------------------------------------------------------------------------- */
299
+
300
+ /** 上游不存在的本地版本后缀(§8.6 第 3 条:禁止 `+` build metadata,npm 匹配会忽略)。 */
301
+ const LOCAL_VERSION_SUFFIX = /-local\.\d+$/;
302
+
303
+ /** registry 缺省地址(与安装侧一致,可被 opts.registry 覆盖)。 */
304
+ const DEFAULT_REGISTRY = 'https://registry.npmjs.org/';
305
+
306
+ /** 读 tarball 内 package.json(不落盘;损坏/缺失 → null)。 */
307
+ function tarballPackageJson(tgz) {
308
+ try {
309
+ const files = untar(tgz);
310
+ const raw = files['package/package.json'];
311
+ if (!raw) return null;
312
+ return JSON.parse(new TextDecoder().decode(raw));
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ /**
319
+ * 从 vendor-blobs 子目录名反推坐标(round-trip 展示用,非权威):
320
+ * `github__owner__repo` → `github:owner/repo`;`@scope__pkg` → `@scope/pkg`;
321
+ * 其余(普通 npm 名,无 `__`)原样;反推不出的回落 tarball 包名。
322
+ */
323
+ export function coordFromDirName(dir, fallbackName = '') {
324
+ const parts = String(dir ?? '').split('__');
325
+ if (parts[0] === 'github' && parts.length === 3) return `github:${parts[1]}/${parts[2]}`;
326
+ if (String(dir).startsWith('@') && parts.length === 2) return parts.join('/');
327
+ return fallbackName || String(dir);
328
+ }
329
+
330
+ /**
331
+ * 列出 profile(一个或多个目录)的依赖清单(UI 勾选列表的数据源)。
332
+ * @param {Host} host
333
+ * @param {string[]} dirs 依赖来源目录(profile 形态传 [profileDir];dshhome 传各 profile 目录)
334
+ * @returns {Promise<Array<{pkgName, spec, coord, kind, version, vendored, installed, dir}>>}
335
+ * kind ∈ 'npm'(registry 精确版本)| 'git'(github sha)| 'vendored'(file:vendor-blobs 复用)。
336
+ */
337
+ export async function listProfileDependencies(host, dirs) {
338
+ const out = [];
339
+ const seen = new Set();
340
+ for (const dir of dirs ?? []) {
341
+ const pkgRaw = await host.readTextFile(host.joinPath(dir, 'package.json'));
342
+ const profile = pkgRaw ? JSON.parse(pkgRaw) : null;
343
+ const deps = profile?.dependencies;
344
+ if (!deps || typeof deps !== 'object') continue;
345
+ for (const [pkgName, spec] of Object.entries(deps)) {
346
+ if (typeof spec !== 'string' || !spec) continue;
347
+ const item = { pkgName, spec, coord: pkgName, kind: 'npm', version: spec, vendored: false, installed: false, dir };
348
+ if (spec.startsWith('file:vendor-blobs/')) {
349
+ const rel = spec.slice('file:'.length);
350
+ const bytes = await host.readFile(host.joinPath(dir, ...rel.split('/')));
351
+ const tp = bytes ? tarballPackageJson(bytes) : null;
352
+ if (bytes && tp) {
353
+ item.kind = 'vendored';
354
+ item.vendored = true;
355
+ item.coord = coordFromDirName(rel.split('/')[1], tp.name || pkgName);
356
+ item.version = typeof tp.version === 'string' ? tp.version : '';
357
+ } else {
358
+ item.version = '(tarball 缺失)';
359
+ }
360
+ } else {
361
+ const git = parsePkgGitSpec(spec);
362
+ if (git) {
363
+ item.kind = 'git';
364
+ item.coord = `github:${git.owner}/${git.repo}${git.subpath ? `#path:/${git.subpath}` : ''}`;
365
+ item.version = git.sha || 'latest';
366
+ }
367
+ }
368
+ const installedRaw = await host.readTextFile(host.joinPath(dir, 'node_modules', pkgName, 'package.json'));
369
+ let installedMeta = null;
370
+ try { installedMeta = installedRaw ? JSON.parse(installedRaw) : null; } catch { installedMeta = null; }
371
+ item.installed = installedMeta != null;
372
+ // npm 范围 spec(`^x.y.z`)不能直接进 registry URL(`^` 会 404),且 vendored 三处一致
373
+ // 要求精确版本 → 用已安装 node_modules 的真实版本折算。
374
+ if (item.kind === 'npm' && installedMeta && typeof installedMeta.version === 'string' && installedMeta.version) {
375
+ item.version = installedMeta.version;
376
+ }
377
+ const source = installedPluginSource(profile, pkgName);
378
+ if (source) {
379
+ item.version = source.version;
380
+ }
381
+ // 同名依赖出现在多个 profile(dshhome):保留首个带 vendor-blobs 的,否则首个
382
+ const key = `${item.coord}`;
383
+ if (seen.has(key)) {
384
+ const prev = out.find((x) => x.coord === key);
385
+ if (prev && !prev.vendored && item.vendored) Object.assign(prev, item);
386
+ continue;
387
+ }
388
+ seen.add(key);
389
+ out.push(item);
390
+ }
391
+ }
392
+ return out;
393
+ }
394
+
395
+ /** 递归收集目录内文件(跳过任意层级的 node_modules;返回 { rel: bytes },rel 用 '/' 分隔)。 */
396
+ async function collectDirFiles(host, absDir, prefix = '') {
397
+ const out = {};
398
+ const entries = await host.readdir(absDir);
399
+ if (!entries) return out;
400
+ for (const e of entries) {
401
+ if (e.name === 'node_modules') continue;
402
+ const rel = prefix ? `${prefix}/${e.name}` : e.name;
403
+ if (e.type === 'dir') {
404
+ Object.assign(out, await collectDirFiles(host, e.abs, rel));
405
+ } else if (e.type === 'file') {
406
+ const data = await host.readFile(e.abs);
407
+ if (data) out[rel] = data;
408
+ }
409
+ }
410
+ return out;
411
+ }
412
+
413
+ /**
414
+ * 从 node_modules/<pkgName> 重打包 npm tarball(§8.6 第 3 条):
415
+ * - 版本加 `-local.N` 后缀(已是本地后缀则保留)——上游不存在的 prerelease,老启动器响亮失败;
416
+ * - tarball 内 package.json 的 version 与返回值一致(三处一致的「包内」一侧)。
417
+ * @returns {{bytes, version, fileCount}}
418
+ */
419
+ export async function repackageFromNodeModules(host, lookupDirs, pkgName, pinnedVersion) {
420
+ for (const dir of lookupDirs) {
421
+ const pkgDir = host.joinPath(dir, 'node_modules', pkgName);
422
+ const pkgRaw = await host.readTextFile(host.joinPath(pkgDir, 'package.json'));
423
+ if (pkgRaw == null) continue;
424
+ let pkg;
425
+ try { pkg = JSON.parse(pkgRaw); } catch { pkg = null; }
426
+ if (!pkg || typeof pkg !== 'object') throw new Error(`node_modules/${pkgName}/package.json 不是有效 JSON,无法重打包`);
427
+ const base = typeof pkg.version === 'string' && pkg.version ? pkg.version : pinnedVersion;
428
+ const version = LOCAL_VERSION_SUFFIX.test(base) ? base : `${base}-local.1`;
429
+ const files = await collectDirFiles(host, pkgDir);
430
+ if (!Object.keys(files).length) throw new Error(`node_modules/${pkgName} 目录为空,无法重打包`);
431
+ pkg.version = version;
432
+ files['package.json'] = new TextEncoder().encode(JSON.stringify(pkg, null, 2) + '\n');
433
+ const tarFiles = {};
434
+ for (const [rel, data] of Object.entries(files)) tarFiles[`package/${rel}`] = data;
435
+ return { bytes: buildTarball(tarFiles), version, fileCount: Object.keys(files).length };
436
+ }
437
+ throw new Error(`本地找不到 ${pkgName}(node_modules 未安装该包),且无法从上游取件——无法内嵌`);
438
+ }
439
+
440
+ /** pnpm 虚拟 store(node_modules/.pnpm/)目录名编码:`/` → `+`(`@scope/pkg` → `@scope+pkg`;git 版本段同理)。 */
441
+ function pnpmStoreKey(s) {
442
+ return String(s).replace(/\//g, '+');
443
+ }
444
+
445
+ /**
446
+ * 从 node_modules/.pnpm/<name>@<version>/node_modules/<name> 重打包闭包条目(v3 §8.6 思路 + .pnpm 查找)。
447
+ * 与 repackageFromNodeModules 的关键差异:闭包条目**保持 lockfile 版本**(不加 `-local.N` 后缀)——
448
+ * 离线解析时 pnpm 按 lockfile 的 `name@version` 找件,版本漂移会导致永不命中;闭包条目不在
449
+ * dependencies 中,无「老启动器静默装上游」风险,无需响亮失败标记。
450
+ * 查找顺序:每个 lookupDir 的 .pnpm 下先试精确 `name@version`(含原样 / '+' 编码两种形态),
451
+ * 再前缀匹配 peer 后缀变体(`name@version(peer...)`)。
452
+ * @returns {{bytes, version, fileCount}|null} 各 lookupDir 均未命中时返回 null(调用方 skip + note)。
453
+ */
454
+ async function repackageFromPnpmStore(host, lookupDirs, pkgName, version) {
455
+ const candidates = [`${pkgName}@${version}`, `${pnpmStoreKey(pkgName)}@${pnpmStoreKey(version)}`];
456
+ for (const dir of lookupDirs) {
457
+ const listing = await host.readdir(host.joinPath(dir, 'node_modules', '.pnpm'));
458
+ if (!listing) continue;
459
+ const hit = listing.find((e) => e.type === 'dir' && candidates.some(
460
+ (c) => e.name === c || e.name.startsWith(`${c}(`),
461
+ ));
462
+ if (!hit) continue;
463
+ const pkgDir = host.joinPath(hit.abs, 'node_modules', pkgName);
464
+ const pkgRaw = await host.readTextFile(host.joinPath(pkgDir, 'package.json'));
465
+ if (pkgRaw == null) continue;
466
+ let pkg = null;
467
+ try { pkg = JSON.parse(pkgRaw); } catch { pkg = null; }
468
+ if (!pkg || typeof pkg !== 'object') continue;
469
+ const files = await collectDirFiles(host, pkgDir);
470
+ if (!Object.keys(files).length) continue;
471
+ pkg.version = version; // 与 lockfile 一致(闭包条目的版本基准是 lockfile,非上游)
472
+ files['package.json'] = new TextEncoder().encode(JSON.stringify(pkg, null, 2) + '\n');
473
+ const tarFiles = {};
474
+ for (const [rel, data] of Object.entries(files)) tarFiles[`package/${rel}`] = data;
475
+ return { bytes: buildTarball(tarFiles), version, fileCount: Object.keys(files).length };
476
+ }
477
+ return null;
478
+ }
479
+
480
+ /** 从 registry 拉 npm 原件 tarball(字节与上游一致);失败返回 null(调用方回落重打包)。 */
481
+ async function fetchRegistryTarball(host, pkgName, version, registry, log) {
482
+ const base = pkgName.includes('/') ? pkgName.slice(pkgName.lastIndexOf('/') + 1) : pkgName;
483
+ // registry 缺省值带尾斜杠(`https://registry.npmjs.org/`),再拼 `/` 会产生双斜杠——部分
484
+ // registry 会 404。这里归一尾斜杠,保证单斜杠。
485
+ const root = String(registry).replace(/\/+$/u, '');
486
+ const url = `${root}/${pkgName}/-/${base}-${version}.tgz`;
487
+ const tmp = await host.mkdtemp('dspack-vendor-');
488
+ try {
489
+ const dest = host.joinPath(tmp, 'pkg.tgz');
490
+ await host.download(url, dest);
491
+ const bytes = await host.readFile(dest);
492
+ return bytes && bytes.length ? bytes : null;
493
+ } catch (e) {
494
+ log(`registry 取件失败(${url}):${e?.message ?? e} → 回落本地重打包`);
495
+ return null;
496
+ } finally {
497
+ await host.rm(tmp, { recursive: true, force: true }).catch(() => {});
498
+ }
499
+ }
500
+
501
+ /**
502
+ * 展开手动选择为最终内嵌清单(vendor 档位,workspace-config v1 r2 / pack-structure v3 §8.6):
503
+ * - `'off'`:清空(禁用内嵌,手动选择也忽略);
504
+ * - `'auto'`(默认):手动选择 ∪ { vendor-blobs round-trip }——不联网探测,只复用已内嵌与手动勾选;
505
+ * - `'full'`:手动选择 ∪ 全部直接依赖 ∪ 传递闭包(离线包形态;闭包沿 pnpm-lock.yaml 由
506
+ * collectVendoredForExport 的 closure 阶段收齐,安装端 computeOfflineCoverage 判定完整性)。
507
+ * @returns {{selection: object, probed: string[]}} probed = 自动补选的坐标(供日志/结果展示)。
508
+ */
509
+ export async function expandVendorSelection(host, lookupDirs, manualSel, knob, opts = {}) {
510
+ if (knob === 'off') return { selection: {}, probed: [] };
511
+ const mode = knob === 'full' ? 'full' : 'auto';
512
+ const selection = { ...(manualSel ?? {}) };
513
+ const probed = [];
514
+
515
+ const items = await listProfileDependencies(host, lookupDirs);
516
+ for (const item of items) {
517
+ if (Object.hasOwn(selection, item.coord)) continue;
518
+ if (item.kind === 'vendored' || mode === 'full') {
519
+ // round-trip:装过 vendored 包的 profile 默认保持内嵌(字节复用,零探测);
520
+ // full:直接依赖全部内嵌。
521
+ selection[item.coord] = 'explicit';
522
+ probed.push(item.coord);
523
+ }
524
+ }
525
+ return { selection, probed };
526
+ }
527
+
528
+ /**
529
+ * 按手动选择内嵌 vendored 依赖(导出侧核心入口)。
530
+ * @param {Host} host
531
+ * @param {string[]} lookupDirs 依赖与 node_modules 的来源目录(profile 形态 [profileDir];dshhome 各 profile 目录)
532
+ * @param {object} baseDependencies 导出 manifest 的 dependencies(坐标 → 版本/file:spec)
533
+ * @param {object} selection UI 勾选结果:{ 坐标: reason }(reason 缺省 'explicit',须 ∈ VENDORED_REASONS)
534
+ * @param {object} opts { registry?, log?, closure?, lockText? }
535
+ * closure=true(vendor=full 档)且提供 lockText 时,直接依赖内嵌完成后沿 pnpm-lock.yaml
536
+ * 收齐传递闭包(未覆盖条目逐个取件:registry 原件优先 → .pnpm 重打包回退 → skip + note)。
537
+ * @returns {Promise<{vendored, dependencies, entries, notes}>}
538
+ * entries 为归档内 `vendor/...` 条目;dependencies 为改写后的 manifest dependencies(三处一致)。
539
+ * 闭包条目 vendored key = npm 包名(不在 dependencies 中,由 §12 约束 1 的闭包规则放行)。
540
+ */
541
+ export async function collectVendoredForExport(host, lookupDirs, baseDependencies, selection, opts = {}) {
542
+ const log = typeof opts.log === 'function' ? opts.log : () => {};
543
+ const registry = opts.registry || DEFAULT_REGISTRY;
544
+ const sel = selection && typeof selection === 'object' ? selection : {};
545
+ const wantClosure = opts.closure === true;
546
+ const lockEntries = wantClosure ? lockfilePackageEntries(opts.lockText) : null;
547
+ const notes = [];
548
+ if (wantClosure && !opts.lockText) {
549
+ notes.push('未找到 pnpm-lock.yaml:full 档无法收集传递闭包(导出包非离线完整形态)');
550
+ log('警告:full 档缺少 pnpm-lock.yaml,跳过闭包收集');
551
+ }
552
+ if (!Object.keys(sel).length && !lockEntries) {
553
+ return { vendored: {}, dependencies: { ...baseDependencies }, entries: {}, notes };
554
+ }
555
+
556
+ for (const [coord, reason] of Object.entries(sel)) {
557
+ if (!VENDORED_REASONS.has(reason)) {
558
+ throw new Error(`vendored reason「${reason}」非法(仅支持 ${[...VENDORED_REASONS].join(' / ')})`);
559
+ }
560
+ }
561
+
562
+ const items = await listProfileDependencies(host, lookupDirs);
563
+ const byCoord = new Map(items.map((i) => [i.coord, i]));
564
+
565
+ const vendored = {};
566
+ const entries = {};
567
+ const dependencies = { ...baseDependencies };
568
+ const units = opts.profileUnits?.length ? opts.profileUnits : [{ dependencies: baseDependencies, plugins: opts.pluginSources }];
569
+ const sourcePins = new Map();
570
+ for (const unit of units) {
571
+ for (const [id, plugin] of Object.entries(unit.plugins || {})) {
572
+ if (plugin.source) {
573
+ sourcePins.set(id, { version: unit.dependencies[id], registry: registryUrl(plugin.source.registry) });
574
+ }
575
+ }
576
+ }
577
+ // 覆盖集合(full 档闭包收集用):坐标折算名 + tarball 真实包名(git 坐标的 lockfile 名是包名)
578
+ const covered = new Set();
579
+ const cover = (coord, bytes) => {
580
+ const git = parseGitCoord(coord);
581
+ covered.add(git ? git.name : coord);
582
+ const tp = tarballPackageJson(bytes);
583
+ if (tp?.name) covered.add(tp.name);
584
+ };
585
+
586
+ for (const [coord, reason] of Object.entries(sel)) {
587
+ const item = byCoord.get(coord);
588
+ if (!item) throw new Error(`选择内嵌的依赖「${coord}」不在 profile 依赖中`);
589
+ let bytes = null;
590
+ let version = item.version;
591
+
592
+ const pin = sourcePins.get(coord);
593
+ if (pin) {
594
+ for (const unit of units) {
595
+ if (!Object.hasOwn(unit.dependencies || {}, coord)) {
596
+ continue;
597
+ }
598
+ const source = unit.plugins?.[coord]?.source;
599
+ if (!source || unit.dependencies[coord] !== pin.version || registryUrl(source.registry) !== pin.registry) {
600
+ throw new Error(coord + ' 在不同 profile 使用不同来源或版本,无法共用内嵌副本');
601
+ }
602
+ }
603
+ version = pin.version;
604
+ bytes = await fetchPluginTarball(host, coord, version, pin.registry, { authDir: item.dir });
605
+ } else if (item.kind === 'vendored') {
606
+ // round-trip:直接复用安装时落盘的 tarball 字节(版本后缀已固化,无需改写)
607
+ const rel = item.spec.slice('file:'.length);
608
+ bytes = await host.readFile(host.joinPath(item.dir, ...rel.split('/')));
609
+ if (!bytes) throw new Error(`vendor-blobs tarball 缺失:${rel}(请重新安装该包)`);
610
+ const tp = tarballPackageJson(bytes);
611
+ version = typeof tp?.version === 'string' ? tp.version : item.version;
612
+ log(`vendored「${coord}」:复用 vendor-blobs 原件(${bytes.length} 字节,v${version})`);
613
+ } else if (item.kind === 'npm') {
614
+ // 先取 registry 原件(字节一致);取不到 → 从 node_modules 重打包 + -local.N 后缀
615
+ bytes = await fetchRegistryTarball(host, item.pkgName, item.version, registry, log);
616
+ if (bytes) {
617
+ log(`vendored「${coord}」:registry 原件(${bytes.length} 字节,v${item.version})`);
618
+ } else {
619
+ const r = await repackageFromNodeModules(host, lookupDirs, item.pkgName, item.version);
620
+ bytes = r.bytes;
621
+ version = r.version;
622
+ notes.push(`${coord}:上游取件失败,已从本地重打包为 v${r.version}(${r.fileCount} 个文件)`);
623
+ log(`vendored「${coord}」:本地重打包 v${r.version}(${r.fileCount} 个文件)`);
624
+ }
625
+ } else {
626
+ // git 坐标:从 node_modules 重打包(不依赖 git 环境;版本 = 钉死的 sha)
627
+ const r = await repackageFromNodeModules(host, lookupDirs, item.pkgName, item.version);
628
+ bytes = r.bytes;
629
+ version = item.version;
630
+ notes.push(`${coord}:git 依赖按 node_modules 内容重打包`);
631
+ log(`vendored「${coord}」:git 依赖本地重打包(${r.fileCount} 个文件)`);
632
+ }
633
+
634
+ // 归档路径:vendor/<坐标编码>/<原文件名>;manifest vendored[].path 是权威
635
+ const base = item.spec.startsWith('file:vendor-blobs/')
636
+ ? item.spec.slice(item.spec.lastIndexOf('/') + 1)
637
+ : `${item.pkgName.includes('/') ? item.pkgName.slice(item.pkgName.lastIndexOf('/') + 1) : item.pkgName}-${version}.tgz`;
638
+ const entryPath = `vendor/${coordDirName(coord)}/${base}`;
639
+ if (entries[entryPath]) throw new Error(`vendored 归档路径冲突:${entryPath}`);
640
+ entries[entryPath] = bytes;
641
+
642
+ // dependencies 改写:删旧 key(file: 场景是 pkgName),写 坐标 → 最终版本(三处一致)
643
+ delete dependencies[item.pkgName];
644
+ delete dependencies[coord];
645
+ dependencies[coord] = version;
646
+
647
+ vendored[coord] = {
648
+ version,
649
+ sha256: await host.sha256(bytes),
650
+ size: bytes.length,
651
+ path: entryPath,
652
+ ...(reason ? { reason } : {}),
653
+ };
654
+ cover(coord, bytes);
655
+ }
656
+
657
+ /* ------------------- 闭包收集(vendor=full 档,v3 §8.6 打包端义务) -------------------
658
+ * 直接依赖内嵌完成后,对照 pnpm-lock.yaml 的 packages:/snapshots: 闭包,把未被覆盖的
659
+ * 传递依赖逐个取件:registry 原件优先(字节一致)→ node_modules/.pnpm 重打包回退
660
+ * (保持 lockfile 版本)→ 再失败 skip 并记 note(宁缺勿错,安装端 coverage 如实判缺)。
661
+ * 闭包条目 vendored key = npm 包名(git 坐标直接依赖按 parseGitCoord 折算后对账覆盖)。
662
+ * ---------------------------------------------------------------------------------- */
663
+ if (lockEntries) {
664
+ for (const { name, version } of lockEntries) {
665
+ const pin = sourcePins.get(name);
666
+ if (covered.has(name)) {
667
+ if (pin && pin.version !== version) {
668
+ throw new Error(name + ' 的多个版本无法在 vendored 中共用同一条目');
669
+ }
670
+ continue;
671
+ }
672
+ if (!version) {
673
+ notes.push(`闭包条目「${name}」在 lockfile 中无版本信息 → 跳过`);
674
+ log(`闭包条目「${name}」缺少版本,跳过`);
675
+ continue;
676
+ }
677
+ let bytes = pin?.version === version
678
+ ? await fetchPluginTarball(host, name, version, pin.registry)
679
+ : await fetchRegistryTarball(host, name, version, registry, log);
680
+ let ok = false;
681
+ if (bytes) {
682
+ // 防御 registry 返回非 tarball / 名实不符(别名包等):名不符视作取件失败回落
683
+ const tp = tarballPackageJson(bytes);
684
+ if (tp?.name === name) {
685
+ ok = true;
686
+ log(`闭包条目「${name}」:registry 原件(${bytes.length} 字节,v${version})`);
687
+ }
688
+ }
689
+ if (!ok) {
690
+ const r = await repackageFromPnpmStore(host, lookupDirs, name, version);
691
+ if (!r) {
692
+ notes.push(`闭包条目「${name}@${version}」取件失败(registry 与本地 .pnpm 均无原件)→ 跳过`);
693
+ log(`闭包条目「${name}@${version}」取件失败,跳过`);
694
+ continue;
695
+ }
696
+ bytes = r.bytes;
697
+ notes.push(`${name}:registry 取件失败,已从本地 .pnpm 重打包为 v${r.version}(${r.fileCount} 个文件)`);
698
+ log(`闭包条目「${name}」:.pnpm 重打包 v${r.version}(${r.fileCount} 个文件)`);
699
+ }
700
+ const base = `${name.includes('/') ? name.slice(name.lastIndexOf('/') + 1) : name}-${version}.tgz`;
701
+ const entryPath = `vendor/${coordDirName(name)}/${base}`;
702
+ if (entries[entryPath]) throw new Error(`vendored 归档路径冲突:${entryPath}`);
703
+ entries[entryPath] = bytes;
704
+ vendored[name] = {
705
+ version,
706
+ sha256: await host.sha256(bytes),
707
+ size: bytes.length,
708
+ path: entryPath,
709
+ reason: 'explicit',
710
+ };
711
+ covered.add(name);
712
+ }
713
+ }
714
+ return { vendored, dependencies, entries, notes };
715
+ }