@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.
- package/LICENSE +21 -0
- package/README.md +178 -3
- package/cordis.patch.yml +9 -0
- package/icons/folder-zip-line.svg +1 -0
- package/lib/ball.js +597 -0
- package/lib/client.js +2934 -0
- package/lib/host.js +51745 -0
- package/lib/migrate-helper.js +35346 -0
- package/lib/progress-main.cjs +79 -0
- package/lib/progress-window.ps1 +114 -0
- package/lib/progress.html +126 -0
- package/lib/publish-to-github/SKILL.md +132 -0
- package/package.json +77 -4
- package/src/ball-entry.js +5 -0
- package/src/ball-host.js +99 -0
- package/src/ball-settings.js +352 -0
- package/src/ball.js +418 -0
- package/src/channel.js +12 -0
- package/src/client-plugin.js +58 -0
- package/src/client-rpc.js +14 -0
- package/src/client.js +5 -0
- package/src/core/discovery.js +192 -0
- package/src/core/dspack.js +93 -0
- package/src/core/extension-files.js +102 -0
- package/src/core/extension-install.js +295 -0
- package/src/core/extension-patch.js +369 -0
- package/src/core/extension-skills.js +164 -0
- package/src/core/extension-validate.js +127 -0
- package/src/core/extensions.js +207 -0
- package/src/core/home-store.js +32 -0
- package/src/core/host.js +149 -0
- package/src/core/index.js +59 -0
- package/src/core/inspect.js +162 -0
- package/src/core/install.js +775 -0
- package/src/core/managed-install.js +84 -0
- package/src/core/manifest.js +717 -0
- package/src/core/market.js +268 -0
- package/src/core/mcp-composition.js +189 -0
- package/src/core/mcp-install.js +112 -0
- package/src/core/mcp-transport.js +116 -0
- package/src/core/pack.js +371 -0
- package/src/core/plugin-metadata.js +355 -0
- package/src/core/registry.js +316 -0
- package/src/core/repo.js +339 -0
- package/src/core/scan.js +78 -0
- package/src/core/security.js +101 -0
- package/src/core/special.js +50 -0
- package/src/core/tar.js +103 -0
- package/src/core/update-config.js +234 -0
- package/src/core/update.js +792 -0
- package/src/core/vendored.js +715 -0
- package/src/core/workspace.js +95 -0
- package/src/endpoints.js +455 -0
- package/src/ensure-manager.js +186 -0
- package/src/host-node.js +625 -0
- package/src/host.js +17 -0
- package/src/index.d.ts +7 -0
- package/src/index.js +39 -0
- package/src/junction.js +142 -0
- package/src/migrate-helper.js +225 -0
- package/src/migrate.js +56 -0
- package/src/packaged.js +9 -0
- package/src/profiles.js +106 -0
- package/src/progress-main.cjs +79 -0
- package/src/progress-window.ps1 +114 -0
- package/src/progress.html +126 -0
- package/src/progress.js +132 -0
- package/src/rpc.js +157 -0
- package/src/runtime.js +43 -0
- package/src/section-gate.js +50 -0
- package/src/settings-nav-icon.js +188 -0
- package/src/settings.js +1611 -0
- package/src/skills/index.js +90 -0
- package/src/skills/publish-to-github/SKILL.md +132 -0
- package/src/tasks.js +145 -0
- package/src/v6-dialogs.js +312 -0
|
@@ -0,0 +1,775 @@
|
|
|
1
|
+
import { managedInstall } from './managed-install.js';
|
|
2
|
+
import { applyPluginSources, verifyActivePluginSources } from './registry.js';
|
|
3
|
+
import { parseDspack, decodeText } from './dspack.js';
|
|
4
|
+
import { validateManifest, coordsToPkgDeps, sanitizeSlug, parseGitCoord, normalizeLaunchers, compareLauncherVersions } from './manifest.js';
|
|
5
|
+
import { listInstalledDshVersions, sortVersionsDesc } from './discovery.js';
|
|
6
|
+
import { storeHomeRel } from './home-store.js';
|
|
7
|
+
import { resolveVendoredPlan, isDialectSpec, directMount, materializeVendorBlobs, blobRelPath, computeOfflineCoverage, allDependencyCoords } from './vendored.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 一键安装:读取本地/URL 的 .dspack → 校验头 & manifest → 按 type 分支安装。
|
|
11
|
+
* - profile(v5):单 profile,装到 $DSH_HOME/profiles/<name>(现有语义,假设 DSH 已装);
|
|
12
|
+
* - dshhome(v5):整个 DSH_HOME 快照,顺序为「先确保 dshVersion 已装 → 建 home →
|
|
13
|
+
* 逐 profile install → home 级资源 → files[]/skills[] 下载」。任一环节失败整体回滚。
|
|
14
|
+
*
|
|
15
|
+
* 安全要点:
|
|
16
|
+
* - .dspack 为标准 ZIP,格式合法性由 parseDspack(dspack.json 标记)与 manifest 校验共同保证;
|
|
17
|
+
* - overrides/ 与 files[].path 的相对路径禁用 `..` 段(防逃逸);
|
|
18
|
+
* - target 名经 sanitizeSlug 规范化;同名目标无 --force 时报错;
|
|
19
|
+
* - 指定 expectedSha256/expectedSize 时先做完整性校验。
|
|
20
|
+
*
|
|
21
|
+
* @param {Host} host
|
|
22
|
+
* @param {object} opts { source, profilesRoot?, home?, name?, registry?, force?, noInstall?, dryRun?,
|
|
23
|
+
* timeoutMs?, installedDshVersions?, expectedSha256?, expectedSize? }
|
|
24
|
+
* @returns {Promise<object>}
|
|
25
|
+
*/
|
|
26
|
+
export async function installPack(host, opts = {}) {
|
|
27
|
+
const { source } = opts;
|
|
28
|
+
if (!source) throw new Error('请指定要安装的整合包(本地 .dspack 路径或 URL)');
|
|
29
|
+
|
|
30
|
+
// 进度回调(GUI 用它避免「卡住」观感):onProgress(stage, detail)
|
|
31
|
+
const progress = (stage, detail) => {
|
|
32
|
+
if (typeof opts.onProgress === 'function') opts.onProgress(stage, detail);
|
|
33
|
+
};
|
|
34
|
+
// 行式日志回调(任务中心 logSink):落盘细节逐文件 print。
|
|
35
|
+
const log = makeLog(opts.onOutput);
|
|
36
|
+
|
|
37
|
+
// 第一条日志先写清「走了哪个代理 / 还是直连」,便于定位网络问题。
|
|
38
|
+
const proxy = proxyLine(host);
|
|
39
|
+
if (proxy) log(proxy);
|
|
40
|
+
|
|
41
|
+
const profilesRoot = opts.profilesRoot || host.joinPath(host.homedir(), '.dsh', 'profiles');
|
|
42
|
+
|
|
43
|
+
progress('download', typeof source === 'string' && /^https?:\/\//i.test(source) ? '下载整合包' : '读取整合包');
|
|
44
|
+
const { path: packPath, tempDir } = await resolvePackSource(host, source);
|
|
45
|
+
log(`整合包:${source} → ${packPath}`);
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
await verifyIntegrity(host, packPath, opts);
|
|
49
|
+
|
|
50
|
+
progress('extract', '解析并校验整合包');
|
|
51
|
+
const bytes = await host.readFile(packPath);
|
|
52
|
+
if (!bytes) throw new Error('无法读取整合包文件');
|
|
53
|
+
const { entries } = parseDspack(bytes);
|
|
54
|
+
|
|
55
|
+
if (!entries['manifest.json']) throw new Error('整合包缺少 manifest.json(不是有效的 .dspack)');
|
|
56
|
+
const manifest = parseJson(decodeText(entries['manifest.json']));
|
|
57
|
+
// lockText:full 闭包包的 vendored 闭包条目不在直接依赖里,须对照随包 pnpm-lock.yaml 放行(v5 §12 约束 1)
|
|
58
|
+
const errors = validateManifest(manifest, {
|
|
59
|
+
lockText: entries['pnpm-lock.yaml'] ? decodeText(entries['pnpm-lock.yaml']) : null,
|
|
60
|
+
});
|
|
61
|
+
if (errors.length) throw new Error(`整合包不合法:${errors.join(';')}`);
|
|
62
|
+
|
|
63
|
+
log(`manifest v${manifest.manifestVersion} type=${manifest.type ?? 'profile'} name=${manifest.name}`);
|
|
64
|
+
|
|
65
|
+
// 阶段 0(v5 r2 §8.4):launchers 判定(六行判定表)——警告放行、不硬拒。
|
|
66
|
+
// selfId 默认官方桌面端(本插件注入 DSH 桌面端),opts.launcherId / opts.launcherVersion 可覆盖;
|
|
67
|
+
// launcherVersion 无法自报时按「版本未知」轻提示放行(launcher-registry §2)。
|
|
68
|
+
const launcherSelfId = opts.launcherId || 'official-desktop';
|
|
69
|
+
const launcherSelfVersion = typeof opts.launcherVersion === 'string' && opts.launcherVersion.trim()
|
|
70
|
+
? opts.launcherVersion
|
|
71
|
+
: null;
|
|
72
|
+
const launchersResult = {
|
|
73
|
+
selfId: launcherSelfId,
|
|
74
|
+
warnings: judgeLaunchers(normalizeLaunchers(manifest.launchers), launcherSelfId, launcherSelfVersion),
|
|
75
|
+
};
|
|
76
|
+
for (const w of launchersResult.warnings) {
|
|
77
|
+
log(`launchers ${w.level === 'warn' ? '警告' : '提示'}:${w.message}`);
|
|
78
|
+
}
|
|
79
|
+
if (launchersResult.warnings.length) log('launchers 警告已放行(用户已确认继续,安装不受影响)');
|
|
80
|
+
|
|
81
|
+
// 阶段 0(v5 r2):vendored 归一 + 对账 + 逐 tarball sha256/size 预验——装前发现优于装到一半。
|
|
82
|
+
// r1 包(无 vendor/)立即返回 active:false,行为与修订前完全一致。
|
|
83
|
+
const vendoredPlan = await resolveVendoredPlan(host, manifest, entries, log);
|
|
84
|
+
// 闭包完整性(v3 §8.3):vendored 覆盖 lockfile 全部依赖 → 严格 --offline(零网络、缺件即报错);
|
|
85
|
+
// 局部覆盖 / 无法判定 → --prefer-offline(本地优先,未覆盖的走 registry 兜底)。
|
|
86
|
+
if (vendoredPlan.active && entries['pnpm-lock.yaml']) {
|
|
87
|
+
const coverage = computeOfflineCoverage(decodeText(entries['pnpm-lock.yaml']), vendoredPlan);
|
|
88
|
+
if (coverage) {
|
|
89
|
+
// 闭包条目(key ∉ 直接依赖,如 full 档收集的传递依赖)tarball 已校验,但尚未经
|
|
90
|
+
// store 预填充喂给 pnpm——硬切 --offline 会在闭包元数据解析时失败,保守用 --prefer-offline。
|
|
91
|
+
const depCoords = allDependencyCoords(manifest);
|
|
92
|
+
const closureCount = [...vendoredPlan.byCoord.keys()].filter((c) => !depCoords.has(c)).length;
|
|
93
|
+
if (coverage.complete && closureCount > 0) {
|
|
94
|
+
log(`vendored 闭包完整(lockfile ${coverage.total} 个包全部内嵌,其中传递闭包 ${closureCount} 个)→ store 预填充待实现,保守本地优先:--prefer-offline`);
|
|
95
|
+
} else if (coverage.complete) {
|
|
96
|
+
vendoredPlan.offline = true;
|
|
97
|
+
log(`vendored 闭包完整(lockfile ${coverage.total} 个包全部内嵌)→ 离线模式:pnpm install --offline`);
|
|
98
|
+
} else {
|
|
99
|
+
const head = coverage.missing.slice(0, 5).join(', ');
|
|
100
|
+
log(`vendored 局部覆盖:lockfile ${coverage.total} 个包中 ${coverage.missing.length} 个未内嵌(${head}${coverage.missing.length > 5 ? '…' : ''})→ 本地优先:--prefer-offline`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const stage = (home, authProfilesRoot) => {
|
|
105
|
+
const staged = { ...opts, home, authProfilesRoot, dryRun: false, noInstall: true, force: false };
|
|
106
|
+
const profiles = host.joinPath(home, 'profiles');
|
|
107
|
+
return manifest.type === 'dshhome'
|
|
108
|
+
? installDshHome(host, manifest, entries, staged, progress, vendoredPlan, launchersResult)
|
|
109
|
+
: installProfile(host, manifest, entries, staged, progress, profiles, vendoredPlan, launchersResult);
|
|
110
|
+
};
|
|
111
|
+
if (manifest.manifestVersion === 6 || opts.update) {
|
|
112
|
+
return await managedInstall(host, manifest, entries, opts, {
|
|
113
|
+
stage,
|
|
114
|
+
verify: (dir, unit, verified) => verifyActivePluginSources(host, dir, unit, verified, {prepareLock:false}),
|
|
115
|
+
skillRoot: (home, profile) => profile ? host.joinPath(home, storeHomeRel('skills', profile)) : undefined,
|
|
116
|
+
previous: async (previousHome) => {
|
|
117
|
+
if (!/^[a-f0-9]{64}$/i.test(opts.previousSha256 ?? '')) {
|
|
118
|
+
throw new Error('旧包需要可核验的 SHA-256');
|
|
119
|
+
}
|
|
120
|
+
const oldPack = await resolvePackSource(host, opts.previousSource);
|
|
121
|
+
try {
|
|
122
|
+
await verifyIntegrity(host, oldPack.path, { expectedSha256: opts.previousSha256 });
|
|
123
|
+
const old = parseDspack(await host.readFile(oldPack.path));
|
|
124
|
+
const baseline = JSON.parse(decodeText(old.entries['manifest.json']));
|
|
125
|
+
if (baseline.name !== manifest.name || (baseline.type ?? 'profile') !== (manifest.type ?? 'profile') ||
|
|
126
|
+
baseline.manifestVersion >= 6) {
|
|
127
|
+
throw new Error('用于迁移的旧包必须是同一整合包的历史格式和相同类型');
|
|
128
|
+
}
|
|
129
|
+
await installPack(host, {
|
|
130
|
+
source: oldPack.path, expectedSha256: opts.previousSha256, noInstall: true,
|
|
131
|
+
profilesRoot: host.joinPath(previousHome, 'profiles'), home: previousHome,
|
|
132
|
+
name: opts.name || manifest.profileName || manifest.name, installedDshVersions: opts.installedDshVersions,
|
|
133
|
+
});
|
|
134
|
+
return { stagedHome: previousHome, manifest: baseline, sha256: opts.previousSha256, expectedSha256: opts.previousSha256 };
|
|
135
|
+
} finally {
|
|
136
|
+
if (oldPack.tempDir) await host.rm(oldPack.tempDir, { recursive: true, force: true });
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
finalize: async ({ affectedProfiles, stagedProfiles }) => {
|
|
140
|
+
for (const dir of affectedProfiles) {
|
|
141
|
+
const pkg = JSON.parse(await host.readTextFile(host.joinPath(dir, 'package.json')));
|
|
142
|
+
const unit = manifest.type === 'dshhome' ? manifest.profiles[host.basename(dir)] : manifest;
|
|
143
|
+
await verifyActivePluginSources(host, dir, unit, host.joinPath(stagedProfiles, host.basename(dir)));
|
|
144
|
+
progress('install', '安装配置档依赖 ' + host.basename(dir));
|
|
145
|
+
await pnpmInstall(host, dir, opts, !!(await host.stat(host.joinPath(dir, 'pnpm-lock.yaml'))), vendorMode(vendoredPlan));
|
|
146
|
+
await mountDialectDeps(host, dir, unit?.dependencies ?? {}, vendoredPlan, log);
|
|
147
|
+
const check = await reconcileProfile(host, dir, { dependencies: pkg.dependencies, bundles: pkg.dsh?.profile?.bundles });
|
|
148
|
+
if (check.missing.length) throw new Error('无法解析插件层栈:' + check.missing.join(', '));
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
if (manifest.manifestVersion === 5 && manifest.type === 'dshhome') {
|
|
154
|
+
return await installDshHome(host, manifest, entries, opts, progress, vendoredPlan, launchersResult);
|
|
155
|
+
}
|
|
156
|
+
return await installProfile(host, manifest, entries, opts, progress, profilesRoot, vendoredPlan, launchersResult);
|
|
157
|
+
} finally {
|
|
158
|
+
if (tempDir) await host.rm(tempDir, { recursive: true, force: true }).catch(() => {});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 单 profile(v5)安装:现有语义,装到 profilesRoot/<name>。 */
|
|
163
|
+
async function installProfile(host, manifest, entries, opts, progress, profilesRoot, vendoredPlan, launchersResult) {
|
|
164
|
+
const profileName = sanitizeSlug(opts.name || manifest.profileName || manifest.name);
|
|
165
|
+
if (!profileName) throw new Error('无法确定 Profile 名称');
|
|
166
|
+
const target = host.joinPath(profilesRoot, profileName);
|
|
167
|
+
const log = makeLog(opts.onOutput);
|
|
168
|
+
|
|
169
|
+
// dshVersions(r2)交集决策:profile 形态做软提示(DSH 基线只硬校验 dshhome 形态)。
|
|
170
|
+
const dshDecision = await decideDshVersion(host, manifest, opts, log);
|
|
171
|
+
|
|
172
|
+
// dry-run 只读预览:即便目标已存在也照常返回计划(真实安装才要求 --force)。
|
|
173
|
+
if (opts.dryRun) {
|
|
174
|
+
const exists = (await host.stat(target)) != null;
|
|
175
|
+
return {
|
|
176
|
+
profileName, dir: target, manifest, dryRun: true, installed: false, reconcile: null,
|
|
177
|
+
filesDownloaded: 0, exists, dshVersion: dshDecision?.version ?? null,
|
|
178
|
+
vendored: summarizeVendored(vendoredPlan, manifest.dependencies ?? {}),
|
|
179
|
+
launchers: launchersResult,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if ((await host.stat(target)) != null && !opts.force) {
|
|
184
|
+
throw new Error(`Profile「${profileName}」已存在:${target}(使用 --force 覆盖)`);
|
|
185
|
+
}
|
|
186
|
+
if ((await host.stat(target)) != null) {
|
|
187
|
+
log(`覆盖已存在的 profile:${target}`);
|
|
188
|
+
await host.rm(target, { recursive: true, force: true });
|
|
189
|
+
}
|
|
190
|
+
await host.mkdir(target);
|
|
191
|
+
log(`创建 profile 目录:${target}`);
|
|
192
|
+
|
|
193
|
+
try {
|
|
194
|
+
progress('extract', '写入 overrides/ 与 package.json');
|
|
195
|
+
await materializePackage(host, target, manifest, entries, log, vendoredPlan);
|
|
196
|
+
if (manifest.manifestVersion === 6) {
|
|
197
|
+
await applyPluginSources(host, target, manifest, {
|
|
198
|
+
vendored: manifest.vendored, entries, authDir: host.joinPath(opts.authProfilesRoot, profileName),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// home/ → $DSH_HOME 根(上一级目录内容:全局 skill / 预设),与 overrides/(profile 根)并列。
|
|
203
|
+
await materializeHome(host, host.joinPath(profilesRoot, '..'), entries, profileName, log);
|
|
204
|
+
|
|
205
|
+
let installed = false;
|
|
206
|
+
let reconcile = null;
|
|
207
|
+
const mounted = [];
|
|
208
|
+
if (!opts.noInstall) {
|
|
209
|
+
installed = true;
|
|
210
|
+
progress('install', '运行 pnpm install(依赖重建,可能较慢)');
|
|
211
|
+
await pnpmInstall(host, target, opts, !!entries['pnpm-lock.yaml'], vendorMode(vendoredPlan));
|
|
212
|
+
// DSHL 方言依赖:pnpm 之后直挂进 node_modules(须在层栈对账之前)
|
|
213
|
+
mounted.push(...await mountDialectDeps(host, target, manifest.dependencies ?? {}, vendoredPlan, log));
|
|
214
|
+
reconcile = await reconcileProfile(host, target, manifest);
|
|
215
|
+
if (reconcile.missing.length > 0) {
|
|
216
|
+
throw new Error(
|
|
217
|
+
`整合包层栈有 ${reconcile.missing.length} 个 bundle 无法解析为补丁层:` +
|
|
218
|
+
`${reconcile.missing.join(', ')}。这些包未声明 dsh.bundle.patch,属于无效的整合包。`,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const files = manifest.files ?? [];
|
|
224
|
+
if (files.length) progress('files', `下载 ${files.length} 个 files[] 条目`);
|
|
225
|
+
const filesDownloaded = await downloadFiles(host, target, files, log);
|
|
226
|
+
|
|
227
|
+
progress('done', profileName);
|
|
228
|
+
return {
|
|
229
|
+
profileName, dir: target, manifest, dryRun: false, installed, reconcile, filesDownloaded,
|
|
230
|
+
dshVersion: dshDecision?.version ?? null,
|
|
231
|
+
vendored: summarizeVendored(vendoredPlan, manifest.dependencies ?? {}, mounted),
|
|
232
|
+
launchers: launchersResult,
|
|
233
|
+
};
|
|
234
|
+
} catch (e) {
|
|
235
|
+
await host.rm(target, { recursive: true, force: true }).catch(() => {});
|
|
236
|
+
throw e;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** dshhome(v5)安装:整个 DSH_HOME 快照,顺序「先装 DSH → 建 home → 逐 profile → home 级资源 → 指针下载」。 */
|
|
241
|
+
async function installDshHome(host, manifest, entries, opts, progress, vendoredPlan, launchersResult) {
|
|
242
|
+
const log = makeLog(opts.onOutput);
|
|
243
|
+
|
|
244
|
+
// ① 先确保 dshVersion / dshVersions(r2 交集决策)选定的 DSH 已安装:多个 profile 的 bundle 都靠安装基线解析。
|
|
245
|
+
const dshDecision = await ensureDsh(host, manifest, opts);
|
|
246
|
+
if (dshDecision) log(`DSH 基线 ${dshDecision.version} 已就绪(来源:${dshDecision.source})`);
|
|
247
|
+
|
|
248
|
+
const homeRoot = opts.home ? host.resolvePath(opts.home) : host.joinPath(host.homedir(), '.dsh');
|
|
249
|
+
log(`目标 DSH_HOME:${homeRoot}`);
|
|
250
|
+
|
|
251
|
+
if (opts.dryRun) {
|
|
252
|
+
const exists = (await host.stat(homeRoot)) != null;
|
|
253
|
+
return {
|
|
254
|
+
type: 'dshhome', dir: homeRoot, manifest, dryRun: true, installed: false, exists,
|
|
255
|
+
profiles: Object.keys(manifest.profiles), defaultProfile: manifest.defaultProfile, filesDownloaded: 0,
|
|
256
|
+
dshVersion: dshDecision?.version ?? null,
|
|
257
|
+
vendored: summarizeVendored(vendoredPlan, aggregateDeps(manifest)),
|
|
258
|
+
launchers: launchersResult,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if ((await host.stat(homeRoot)) != null && !opts.force) {
|
|
263
|
+
throw new Error(`目标 DSH_HOME 已存在:${homeRoot}(使用 --force 覆盖)`);
|
|
264
|
+
}
|
|
265
|
+
if ((await host.stat(homeRoot)) != null) {
|
|
266
|
+
log(`覆盖已存在的 DSH_HOME:${homeRoot}`);
|
|
267
|
+
await host.rm(homeRoot, { recursive: true, force: true });
|
|
268
|
+
}
|
|
269
|
+
await host.mkdir(homeRoot);
|
|
270
|
+
|
|
271
|
+
try {
|
|
272
|
+
// ② 逐 profile:overrides/profiles/<name>/ 落盘 → pnpm install → 对账(各自独立)
|
|
273
|
+
const installed = [];
|
|
274
|
+
const mountedAll = [];
|
|
275
|
+
for (const [name, unit] of Object.entries(manifest.profiles)) {
|
|
276
|
+
const profileDir = host.joinPath(homeRoot, 'profiles', name);
|
|
277
|
+
progress('extract', `写入 profile「${name}」`);
|
|
278
|
+
await materializeProfile(host, profileDir, name, unit, entries, log, vendoredPlan);
|
|
279
|
+
if (manifest.manifestVersion === 6) {
|
|
280
|
+
await applyPluginSources(host, profileDir, unit, {
|
|
281
|
+
vendored: manifest.vendored, entries, authDir: host.joinPath(opts.authProfilesRoot, name),
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (!opts.noInstall) {
|
|
286
|
+
progress('install', `运行 pnpm install(${name},可能较慢)`);
|
|
287
|
+
await pnpmInstall(host, profileDir, opts, !!entries['pnpm-lock.yaml'], vendorMode(vendoredPlan));
|
|
288
|
+
mountedAll.push(...await mountDialectDeps(host, profileDir, unit.dependencies ?? {}, vendoredPlan, log));
|
|
289
|
+
const reconcile = await reconcileProfile(host, profileDir, unit);
|
|
290
|
+
if (reconcile.missing.length > 0) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`profile「${name}」层栈有 ${reconcile.missing.length} 个 bundle 无法解析为补丁层:` +
|
|
293
|
+
`${reconcile.missing.join(', ')}。这些包未声明 dsh.bundle.patch。`,
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
installed.push(name);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ③ home 级 overrides:.agent-presets/ skills/ AGENTS.md data/ 等
|
|
301
|
+
progress('extract', '写入 home 级资源(preset / skill / 指令 / 数据)');
|
|
302
|
+
await materializeHomeOverrides(host, homeRoot, entries, log);
|
|
303
|
+
|
|
304
|
+
// ④ files[] + 重 skills[] 指针下载
|
|
305
|
+
const heavySkills = (manifest.skills ?? [])
|
|
306
|
+
.filter((s) => s.sha256 && s.size)
|
|
307
|
+
.map((s) => ({ path: s.path, sha256: s.sha256, size: s.size, urls: s.urls }));
|
|
308
|
+
const all = [...(manifest.files ?? []), ...heavySkills];
|
|
309
|
+
if (all.length) progress('files', `下载 ${all.length} 个 files[]/skills[] 条目`);
|
|
310
|
+
const filesDownloaded = await downloadFiles(host, homeRoot, all, log);
|
|
311
|
+
|
|
312
|
+
progress('done', manifest.name);
|
|
313
|
+
return {
|
|
314
|
+
type: 'dshhome', dir: homeRoot, manifest, dryRun: false, installed: true,
|
|
315
|
+
profiles: installed, defaultProfile: manifest.defaultProfile, filesDownloaded,
|
|
316
|
+
dshVersion: dshDecision?.version ?? null,
|
|
317
|
+
vendored: summarizeVendored(vendoredPlan, aggregateDeps(manifest), mountedAll),
|
|
318
|
+
launchers: launchersResult,
|
|
319
|
+
};
|
|
320
|
+
} catch (e) {
|
|
321
|
+
await host.rm(homeRoot, { recursive: true, force: true }).catch(() => {});
|
|
322
|
+
throw e;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** dshhome 各 profile 依赖坐标并集(vendored 摘要用)。 */
|
|
327
|
+
function aggregateDeps(manifest) {
|
|
328
|
+
const out = {};
|
|
329
|
+
for (const u of Object.values(manifest.profiles ?? {})) Object.assign(out, u?.dependencies ?? {});
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* launchers 判定(v3 §8.4 六行判定表):按归一化后的 launchers map 评估当前安装端,
|
|
335
|
+
* 产出警告列表(警告放行、不硬拒——调用方逐条 log 并透出 result.launchers 供 UI 确认)。
|
|
336
|
+
*
|
|
337
|
+
* | 条目 / 查表结果 | 行为 |
|
|
338
|
+
* | --- | --- |
|
|
339
|
+
* | supported:true,无 minVersion | 静默 |
|
|
340
|
+
* | supported:true,本启动器版本 ≥ minVersion | 静默 |
|
|
341
|
+
* | supported:true,版本不足 / 版本未知 | 轻提示(info) |
|
|
342
|
+
* | supported:false | 重警告(warn,显示 reason) |
|
|
343
|
+
* | 未列出,map 无任何 supported:true(纯黑名单) | 静默 |
|
|
344
|
+
* | 未列出,map 有 supported:true(白名单) | 轻提示(info,列出支持项) |
|
|
345
|
+
*
|
|
346
|
+
* @param {object} normalized normalizeLaunchers 归一化后的 map
|
|
347
|
+
* @param {string} selfId 当前安装端启动器 ID(launcher-registry §1)
|
|
348
|
+
* @param {string|null} selfVersion 当前启动器自报版本(无法自报时 null → 按「版本未知」处理)
|
|
349
|
+
* @returns {{ level: 'info'|'warn', message: string }[]}
|
|
350
|
+
*/
|
|
351
|
+
export function judgeLaunchers(normalized, selfId, selfVersion) {
|
|
352
|
+
const warnings = [];
|
|
353
|
+
const map = normalized && typeof normalized === 'object' && !Array.isArray(normalized) ? normalized : {};
|
|
354
|
+
const ids = Object.keys(map);
|
|
355
|
+
if (!ids.length) return warnings; // launchers 缺省 = 通用包(现状不变)
|
|
356
|
+
|
|
357
|
+
const self = map[selfId];
|
|
358
|
+
if (self) {
|
|
359
|
+
if (self.supported === false) {
|
|
360
|
+
// 判定表第 4 行:重警告(显示 reason)→ 放行
|
|
361
|
+
warnings.push({
|
|
362
|
+
level: 'warn',
|
|
363
|
+
message: self.reason
|
|
364
|
+
? `包作者声明不支持当前启动器「${selfId}」:${self.reason}`
|
|
365
|
+
: `包作者声明不支持当前启动器「${selfId}」(未提供原因)`,
|
|
366
|
+
});
|
|
367
|
+
} else if (self.minVersion) {
|
|
368
|
+
// 判定表第 2/3 行:版本达标静默;不足或未知(启动器无法自报)轻提示放行
|
|
369
|
+
const known = typeof selfVersion === 'string' && selfVersion.trim();
|
|
370
|
+
if (!known || compareLauncherVersions(selfVersion, self.minVersion) < 0) {
|
|
371
|
+
warnings.push({
|
|
372
|
+
level: 'info',
|
|
373
|
+
message: `需要 ${selfId} ≥ ${self.minVersion}(当前${known ? `:${selfVersion}` : '版本未知'}),可能存在兼容问题`,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// 判定表第 1 行:supported:true 且无 minVersion → 静默
|
|
378
|
+
} else {
|
|
379
|
+
// 未列出(三态第三态):纯黑名单静默;白名单轻提示列出支持项
|
|
380
|
+
const supportedIds = ids.filter((id) => map[id]?.supported === true);
|
|
381
|
+
if (supportedIds.length) {
|
|
382
|
+
warnings.push({
|
|
383
|
+
level: 'info',
|
|
384
|
+
message: `本整合包声明支持:${supportedIds.join('、')}(未声明当前启动器「${selfId}」,仅供参考)`,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return warnings;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** dshVersions(r2 §13)交集决策(确定性,永有唯一答案):
|
|
392
|
+
* dshVersions ∩ 本机已装 ≠ ∅ → 命中多个时优先 dshVersion 指定者、其次集合内最新;
|
|
393
|
+
* 无交集 → null(调用方按 dshVersion 提示安装)。
|
|
394
|
+
*/
|
|
395
|
+
export function resolveDshVersion(manifest, installedVersions) {
|
|
396
|
+
const versions = Array.isArray(installedVersions) ? installedVersions : [];
|
|
397
|
+
if (manifest.dshVersion && versions.includes(manifest.dshVersion)) {
|
|
398
|
+
return { version: manifest.dshVersion, source: 'dshVersion' };
|
|
399
|
+
}
|
|
400
|
+
const hits = (Array.isArray(manifest.dshVersions) ? manifest.dshVersions : []).filter((v) => versions.includes(v));
|
|
401
|
+
if (hits.length) {
|
|
402
|
+
const pick = manifest.dshVersion && hits.includes(manifest.dshVersion)
|
|
403
|
+
? manifest.dshVersion
|
|
404
|
+
: sortVersionsDesc(hits)[0];
|
|
405
|
+
return { version: pick, source: 'dshVersions' };
|
|
406
|
+
}
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** profile 形态的软决策(不硬校验):有 dshVersion/dshVersions 声明时记录选定版本或提示未装。 */
|
|
411
|
+
async function decideDshVersion(host, manifest, opts, log) {
|
|
412
|
+
if (!manifest.dshVersion && !Array.isArray(manifest.dshVersions)) return null;
|
|
413
|
+
const installed = opts.installedDshVersions ?? (await listInstalledDshVersions(host));
|
|
414
|
+
const decision = resolveDshVersion(manifest, installed);
|
|
415
|
+
if (decision) log(`DSH 版本决策:${decision.version}(来源:${decision.source})`);
|
|
416
|
+
else log(`提示:声明的 DSH 版本(${manifest.dshVersion || (manifest.dshVersions ?? []).join(' / ')})本机均未安装,安装后如异常请先装对应版本`);
|
|
417
|
+
return decision;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 检查 dshVersion / dshVersions 选定的 DSH 是否已安装(均未声明则跳过);未装报错提示先用启动器装。 */
|
|
421
|
+
async function ensureDsh(host, manifest, opts) {
|
|
422
|
+
if (!manifest.dshVersion && !Array.isArray(manifest.dshVersions)) return null;
|
|
423
|
+
const installed = opts.installedDshVersions ?? (await listInstalledDshVersions(host));
|
|
424
|
+
const decision = resolveDshVersion(manifest, installed);
|
|
425
|
+
if (decision) return decision;
|
|
426
|
+
const declared = manifest.dshVersion
|
|
427
|
+
? `DSH ${manifest.dshVersion}`
|
|
428
|
+
: `dshVersions [${(manifest.dshVersions ?? []).join(', ')}] 中的任一版本`;
|
|
429
|
+
const have = Array.isArray(installed) ? installed.join(', ') || '无' : '未知';
|
|
430
|
+
throw new Error(`dshhome 依赖 ${declared},但本机未安装(已装:${have})。请先用启动器安装该版本后再导入。`);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** vendored 摘要(安装结果 / dry-run 计划展示用)。 */
|
|
434
|
+
function summarizeVendored(plan, deps, mounted = []) {
|
|
435
|
+
if (!plan?.active) return { active: false, used: [], mounted: [], offline: false };
|
|
436
|
+
const used = [];
|
|
437
|
+
for (const coord of Object.keys(deps ?? {})) {
|
|
438
|
+
const e = plan.byCoord.get(coord);
|
|
439
|
+
if (e && !e.dialect) used.push(coord);
|
|
440
|
+
}
|
|
441
|
+
return { active: true, used, mounted, offline: plan.offline === true };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** DSHL 方言依赖直挂(v3 §8.3 direct-mount):pnpm install 之后、层栈对账之前执行。 */
|
|
445
|
+
async function mountDialectDeps(host, target, deps, plan, log) {
|
|
446
|
+
if (!plan?.active) return [];
|
|
447
|
+
const mounted = [];
|
|
448
|
+
for (const [name, spec] of Object.entries(deps ?? {})) {
|
|
449
|
+
if (!isDialectSpec(spec)) continue;
|
|
450
|
+
const entry = plan.byCoord.get(name);
|
|
451
|
+
if (!entry) throw new Error(`方言依赖「${name}」在 vendor/vendor.json 中无对应条目(拒装)`);
|
|
452
|
+
await directMount(host, target, name, entry, log);
|
|
453
|
+
mounted.push(name);
|
|
454
|
+
}
|
|
455
|
+
return mounted;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/* ------------------------------------------------------------------ */
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* 归一化用户粘贴的路径/URL:去首尾空白 + 去掉包裹的成对引号。
|
|
462
|
+
* Windows「复制路径」(资源管理器 / 属性)会给带空格或中文的路径套一对双引号;
|
|
463
|
+
* 不剥掉的话,`path.resolve` 会把 `"C:\…\x.dspack"` 当成相对路径拼到 cwd 后面,
|
|
464
|
+
* 得到 `cwd\"C:\…\x.dspack"` 这种错得离谱的「找不到整合包文件」。
|
|
465
|
+
*/
|
|
466
|
+
function normalizeSource(source) {
|
|
467
|
+
const trimmed = String(source ?? '').trim();
|
|
468
|
+
const quote = trimmed[0];
|
|
469
|
+
if ((quote === '"' || quote === "'") && trimmed.length >= 2 && trimmed.endsWith(quote)) {
|
|
470
|
+
return trimmed.slice(1, -1).trim();
|
|
471
|
+
}
|
|
472
|
+
return trimmed;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** 把「本地路径 | http(s) URL」统一解析为本地文件路径;URL 会下载到临时目录(调用方负责清理返回的 tempDir)。 */
|
|
476
|
+
export async function resolvePackSource(host, source) {
|
|
477
|
+
const normalized = normalizeSource(source);
|
|
478
|
+
if (/^https?:\/\//i.test(normalized)) {
|
|
479
|
+
const tempDir = await host.mkdtemp('dspack-dl-');
|
|
480
|
+
const dest = host.joinPath(tempDir, 'pack.dspack');
|
|
481
|
+
await host.download(normalized, dest);
|
|
482
|
+
return { path: dest, tempDir };
|
|
483
|
+
}
|
|
484
|
+
const local = host.resolvePath(normalized);
|
|
485
|
+
const st = await host.stat(local);
|
|
486
|
+
if (!st?.isFile) throw new Error(`找不到整合包文件:${local}`);
|
|
487
|
+
return { path: local, tempDir: null };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** 完整性校验(可选,来自市场索引的 sha256/size)。 */
|
|
491
|
+
export async function verifyIntegrity(host, packPath, opts = {}) {
|
|
492
|
+
// 只有「正整数」的 expectedSize 才参与校验:0 / 缺失 / 非数字一律视为未提供,
|
|
493
|
+
// 避免市场条目缺 size 时把 0 当成「期望 0 字节」误判(files 不可能为 0 字节)。
|
|
494
|
+
if (Number.isInteger(opts.expectedSize) && opts.expectedSize > 0) {
|
|
495
|
+
const st = await host.stat(packPath);
|
|
496
|
+
if (!st || st.size !== opts.expectedSize) {
|
|
497
|
+
throw new Error(`大小不符:期望 ${opts.expectedSize} 字节,实际 ${st?.size ?? '未知'}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (opts.expectedSha256) {
|
|
501
|
+
const actual = await host.sha256File(packPath);
|
|
502
|
+
if (actual !== opts.expectedSha256.toLowerCase()) {
|
|
503
|
+
throw new Error(`sha256 校验失败(可能被篡改):期望 ${opts.expectedSha256},实际 ${actual}`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** 单 profile:overrides/* 落盘 + 重建 package.json + 快照机器文件 + vendored tarball 落盘(r2)。 */
|
|
509
|
+
async function materializePackage(host, dir, manifest, entries, log, plan) {
|
|
510
|
+
// 0) vendored tarball → vendor-blobs/(file: 引用的实体;manifest 不动,改写只发生在重建的 package.json)
|
|
511
|
+
if (plan?.active) await materializeVendorBlobs(host, dir, plan, Object.keys(manifest.dependencies ?? {}), log);
|
|
512
|
+
|
|
513
|
+
// 1) overrides/* → profile 根
|
|
514
|
+
for (const [entryPath, data] of Object.entries(entries)) {
|
|
515
|
+
if (!entryPath.startsWith('overrides/')) continue;
|
|
516
|
+
const rel = safeRel(entryPath.slice('overrides/'.length));
|
|
517
|
+
if (!rel) continue;
|
|
518
|
+
const dest = host.joinPath(dir, rel);
|
|
519
|
+
await host.writeFile(dest, data);
|
|
520
|
+
log(`写入 overrides/${rel} → ${dest}`);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 2) package.json:以 manifest 为唯一事实源重建 dependencies / bundles;保留快照其余字段
|
|
524
|
+
const base = parseJson(decodeText(entries['package.json'] || new Uint8Array())) ?? {};
|
|
525
|
+
const pkg = base && typeof base === 'object' && !Array.isArray(base) ? base : {};
|
|
526
|
+
pkg.dependencies = coordsToPkgDeps(manifest.dependencies ?? {});
|
|
527
|
+
applyVendoredSpecs(pkg.dependencies, manifest.dependencies ?? {}, plan);
|
|
528
|
+
pkg.dsh = { ...(pkg.dsh ?? {}), profile: { ...(pkg.dsh?.profile ?? {}), bundles: manifest.bundles ?? [] } };
|
|
529
|
+
const pkgPath = host.joinPath(dir, 'package.json');
|
|
530
|
+
await host.writeTextFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
531
|
+
log(`重建 package.json → ${pkgPath}`);
|
|
532
|
+
|
|
533
|
+
// 3) pnpm 设置 / 锁文件快照(根机器文件,可选)
|
|
534
|
+
for (const name of ['pnpm-workspace.yaml', 'pnpm-lock.yaml']) {
|
|
535
|
+
if (entries[name]) {
|
|
536
|
+
const dest = host.joinPath(dir, name);
|
|
537
|
+
await host.writeFile(dest, entries[name]);
|
|
538
|
+
log(`写入 ${name} → ${dest}`);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// 4) cordis.patch.yml:overrides 已优先落地;缺则回退 manifest.patch
|
|
543
|
+
const patchPath = host.joinPath(dir, 'cordis.patch.yml');
|
|
544
|
+
if ((await host.stat(patchPath)) == null && typeof manifest.patch === 'string') {
|
|
545
|
+
await host.writeTextFile(patchPath, manifest.patch);
|
|
546
|
+
log(`回退 manifest.patch → ${patchPath}`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** 单 profile 包携带的 home 级内容:home/* → $DSH_HOME 根;skills / .agent-presets 落到 .dsh-pack/<store>/<profileName>/(换指 slot)。 */
|
|
551
|
+
async function materializeHome(host, homeRoot, entries, profileName, log) {
|
|
552
|
+
for (const [entryPath, data] of Object.entries(entries)) {
|
|
553
|
+
if (!entryPath.startsWith('home/')) continue;
|
|
554
|
+
const rel = safeRel(entryPath.slice('home/'.length));
|
|
555
|
+
if (!rel) continue;
|
|
556
|
+
const dest = host.joinPath(homeRoot, storeHomeRel(rel, profileName));
|
|
557
|
+
await host.writeFile(dest, data);
|
|
558
|
+
log(`写入 home/${rel} → ${dest}`);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** dshhome 单个 profile:overrides/profiles/<name>/ 落盘 + 以 ProfileUnit 重建 package.json / patch。 */
|
|
563
|
+
async function materializeProfile(host, profileDir, name, unit, entries, log, plan) {
|
|
564
|
+
await host.mkdir(profileDir);
|
|
565
|
+
log(`创建 profile 目录:${profileDir}`);
|
|
566
|
+
|
|
567
|
+
// 0) vendored tarball → vendor-blobs/(vendor/ 是包级的,各 profile 各放一份 file: 引用实体)
|
|
568
|
+
if (plan?.active) await materializeVendorBlobs(host, profileDir, plan, Object.keys(unit.dependencies ?? {}), log);
|
|
569
|
+
|
|
570
|
+
// 1) overrides/profiles/<name>/* → profile 根
|
|
571
|
+
const prefix = `overrides/profiles/${name}/`;
|
|
572
|
+
for (const [entryPath, data] of Object.entries(entries)) {
|
|
573
|
+
if (!entryPath.startsWith(prefix)) continue;
|
|
574
|
+
const rel = safeRel(entryPath.slice(prefix.length));
|
|
575
|
+
if (!rel) continue;
|
|
576
|
+
const dest = host.joinPath(profileDir, rel);
|
|
577
|
+
await host.writeFile(dest, data);
|
|
578
|
+
log(`写入 ${prefix}${rel} → ${dest}`);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// 2) package.json:以 ProfileUnit 为唯一事实源(bundle 层栈 + 坐标→依赖)
|
|
582
|
+
const pkg = {
|
|
583
|
+
name: `dsh-profile-${name}`,
|
|
584
|
+
private: true,
|
|
585
|
+
dependencies: coordsToPkgDeps(unit.dependencies ?? {}),
|
|
586
|
+
dsh: { profile: { bundles: unit.bundles ?? [] } },
|
|
587
|
+
};
|
|
588
|
+
applyVendoredSpecs(pkg.dependencies, unit.dependencies ?? {}, plan);
|
|
589
|
+
const pkgPath = host.joinPath(profileDir, 'package.json');
|
|
590
|
+
await host.writeTextFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
591
|
+
log(`重建 package.json → ${pkgPath}`);
|
|
592
|
+
|
|
593
|
+
// 3) cordis.patch.yml:overrides 优先;缺则回退 unit.patch
|
|
594
|
+
const patchPath = host.joinPath(profileDir, 'cordis.patch.yml');
|
|
595
|
+
if ((await host.stat(patchPath)) == null && typeof unit.patch === 'string') {
|
|
596
|
+
await host.writeTextFile(patchPath, unit.patch);
|
|
597
|
+
log(`回退 unit.patch → ${patchPath}`);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** dshhome:home 级 overrides(.agent-presets/ skills/ AGENTS.md data/ 等,profiles/ 除外)落盘。 */
|
|
602
|
+
async function materializeHomeOverrides(host, homeRoot, entries, log) {
|
|
603
|
+
for (const [entryPath, data] of Object.entries(entries)) {
|
|
604
|
+
if (!entryPath.startsWith('overrides/')) continue;
|
|
605
|
+
const rel = safeRel(entryPath.slice('overrides/'.length));
|
|
606
|
+
if (!rel) continue;
|
|
607
|
+
if (rel.startsWith('profiles/')) continue; // profile 已在逐 profile 阶段单独落盘
|
|
608
|
+
const dest = host.joinPath(homeRoot, rel);
|
|
609
|
+
await host.writeFile(dest, data);
|
|
610
|
+
log(`写入 overrides/${rel} → ${dest}`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* vendored 坐标在**重建的 package.json** 上的 spec 决策(v3 §8.3 统一算法):
|
|
616
|
+
* - 显式 vendored 条目 → `file:vendor-blobs/...`(本地优先;其余坐标照常走 registry,互为兜底);
|
|
617
|
+
* - DSHL 方言 spec(`vendor:<file>.tgz`)→ 从依赖中剔除(tarball 直挂,不传给 pnpm);
|
|
618
|
+
* - 非 vendored 坐标 → 原样。manifest 不动(规范禁止安装端改写包内字节,改写仅发生在重建产物上)。
|
|
619
|
+
*/
|
|
620
|
+
function applyVendoredSpecs(pkgDeps, manifestDeps, plan) {
|
|
621
|
+
if (!plan?.active) return;
|
|
622
|
+
for (const [coord, spec] of Object.entries(manifestDeps ?? {})) {
|
|
623
|
+
const entry = plan.byCoord.get(coord);
|
|
624
|
+
const git = parseGitCoord(coord);
|
|
625
|
+
const pkgName = git ? git.name : coord;
|
|
626
|
+
if (isDialectSpec(spec)) {
|
|
627
|
+
delete pkgDeps[pkgName]; // 方言:直挂,不传给 pnpm(v3 §8.5)
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
if (entry && !entry.dialect) {
|
|
631
|
+
pkgDeps[pkgName] = `file:${blobRelPath(coord, entry)}`;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** vendored 安装模式:false=纯网络(r1)| 'prefer'=本地优先 | 'offline'=严格离线(闭包完整)。 */
|
|
637
|
+
function vendorMode(plan) {
|
|
638
|
+
if (!plan?.active) return false;
|
|
639
|
+
return plan.offline ? 'offline' : 'prefer';
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async function pnpmInstall(host, target, opts, frozen, mode) {
|
|
643
|
+
// 依赖重建可能较慢(尤其 git 依赖走 git clone),给足超时但绝不无限卡死。
|
|
644
|
+
const timeoutMs = opts.timeoutMs > 0 ? opts.timeoutMs : 10 * 60 * 1000;
|
|
645
|
+
// 优先走 host.pnpm(桌面端复用 DSH 自带 node+pnpm,不依赖用户 PATH 上的 node/pnpm);无此能力则回退 PATH 上的 pnpm。
|
|
646
|
+
const runPnpm = typeof host.pnpm === 'function'
|
|
647
|
+
? (args, o) => host.pnpm(args, o)
|
|
648
|
+
: (args, o) => host.exec('pnpm', args, o);
|
|
649
|
+
const args = ['install'];
|
|
650
|
+
// vendored 激活(r2 统一算法):--prefer-offline 本地优先(未覆盖的走 registry 兜底);
|
|
651
|
+
// 闭包完整时升级为严格 --offline(零网络、缺件即报错)。file: spec 与随包 lockfile 必然
|
|
652
|
+
// 不匹配,两种模式都跳过 --frozen-lockfile(否则每次都白跑一遍 frozen 再回退)。
|
|
653
|
+
if (mode === 'offline') args.push('--offline');
|
|
654
|
+
else if (mode === 'prefer') args.push('--prefer-offline');
|
|
655
|
+
if (frozen && !mode) args.push('--frozen-lockfile');
|
|
656
|
+
if (opts.registry) args.push('--registry', opts.registry);
|
|
657
|
+
let r = await runPnpm(args, { cwd: target, timeoutMs, onOutput: opts.onOutput });
|
|
658
|
+
// frozen-lockfile 失配时回退普通安装(v4/v5 导入语义)
|
|
659
|
+
if (frozen && !mode && r.status !== 0) {
|
|
660
|
+
r = await runPnpm(['install', ...(opts.registry ? ['--registry', opts.registry] : [])], { cwd: target, timeoutMs, onOutput: opts.onOutput });
|
|
661
|
+
}
|
|
662
|
+
if (r.error) throw new Error(`pnpm install 执行失败:${r.error}`);
|
|
663
|
+
if (r.status !== 0) throw new Error(`pnpm install 失败(退出码 ${r.status ?? '未知'})`);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** files[] 重内容:每个 url 依次尝试下载 → sha256+size 校验 → 落到 path。 */
|
|
667
|
+
async function downloadFiles(host, target, files, log) {
|
|
668
|
+
let count = 0;
|
|
669
|
+
const tmp = await host.mkdtemp('dspack-files-');
|
|
670
|
+
try {
|
|
671
|
+
for (const f of files ?? []) {
|
|
672
|
+
const rel = safeRel(f.path);
|
|
673
|
+
const dest = host.joinPath(target, rel);
|
|
674
|
+
const tmpFile = host.joinPath(tmp, `dl-${count}`);
|
|
675
|
+
let ok = false;
|
|
676
|
+
let lastErr = null;
|
|
677
|
+
for (const url of f.urls) {
|
|
678
|
+
log(`下载 ${rel} ← ${url}`);
|
|
679
|
+
try {
|
|
680
|
+
await host.download(url, tmpFile);
|
|
681
|
+
ok = true;
|
|
682
|
+
break;
|
|
683
|
+
} catch (e) {
|
|
684
|
+
lastErr = e;
|
|
685
|
+
log(` 失败:${e?.message ?? e}(尝试下一源)`);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
if (!ok) throw new Error(`files[] 下载失败:${rel}(${lastErr?.message ?? '无可用源'})`);
|
|
689
|
+
|
|
690
|
+
const sha = await host.sha256File(tmpFile);
|
|
691
|
+
const st = await host.stat(tmpFile);
|
|
692
|
+
if (sha !== String(f.sha256).toLowerCase() || (st?.size ?? -1) !== f.size) {
|
|
693
|
+
throw new Error(`files[] 完整性校验失败:${rel}`);
|
|
694
|
+
}
|
|
695
|
+
await host.move(tmpFile, dest);
|
|
696
|
+
log(`写入 ${rel} → ${dest}`);
|
|
697
|
+
count += 1;
|
|
698
|
+
}
|
|
699
|
+
return count;
|
|
700
|
+
} finally {
|
|
701
|
+
await host.rm(tmp, { recursive: true, force: true }).catch(() => {});
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* 安装后对账(v4/v5 沿用 DSH 语义:Bundle 唯一判据 = dsh.bundle.patch 声明存在)。
|
|
707
|
+
* 对 dshhome 的 ProfileUnit 同样适用(unit 含 bundles / dependencies)。
|
|
708
|
+
* @returns {{ missing: string[], added: string[] }}
|
|
709
|
+
* - missing:层栈中「同时是依赖」的包,装完无 dsh.bundle.patch → 无效,需回滚;
|
|
710
|
+
* - added:依赖里声明了 dsh.bundle.patch 却未进层栈 → 自动补进(调用方需写回 manifests)。
|
|
711
|
+
*/
|
|
712
|
+
export async function reconcileProfile(host, profileDir, manifest) {
|
|
713
|
+
const missing = [];
|
|
714
|
+
const added = [];
|
|
715
|
+
const pkgDeps = coordsToPkgDeps(manifest.dependencies ?? {});
|
|
716
|
+
const bundles = [...(manifest.bundles ?? [])];
|
|
717
|
+
|
|
718
|
+
for (const name of bundles) {
|
|
719
|
+
if (!Object.hasOwn(pkgDeps, name)) continue; // 模板型 bundle:由 DSH 安装目录 fallback 兜底
|
|
720
|
+
const pkg = await readJson(host, host.joinPath(profileDir, 'node_modules', name, 'package.json'));
|
|
721
|
+
if (!pkg || pkg.dsh?.bundle?.patch === undefined) missing.push(name);
|
|
722
|
+
}
|
|
723
|
+
for (const name of Object.keys(pkgDeps)) {
|
|
724
|
+
const pkg = await readJson(host, host.joinPath(profileDir, 'node_modules', name, 'package.json'));
|
|
725
|
+
if (pkg && pkg.dsh?.bundle?.patch !== undefined && !bundles.includes(name)) {
|
|
726
|
+
bundles.push(name);
|
|
727
|
+
added.push(name);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return { missing, added };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/* ------------------- 工具 ------------------- */
|
|
734
|
+
|
|
735
|
+
/** 把 host.proxyStatus() 转成一条日志行;宿主不支持或无信息时返回 null。 */
|
|
736
|
+
function proxyLine(host) {
|
|
737
|
+
if (typeof host.proxyStatus !== 'function') return null;
|
|
738
|
+
const ps = host.proxyStatus();
|
|
739
|
+
if (!ps) return null;
|
|
740
|
+
switch (ps.kind) {
|
|
741
|
+
case 'manual': return `代理:手动配置 ${ps.url}`;
|
|
742
|
+
case 'direct': return '代理:直连(用户已禁用代理)';
|
|
743
|
+
case 'auto-env': return `代理:环境变量 ${ps.url}`;
|
|
744
|
+
case 'auto-system': return `代理:系统代理 ${ps.url}`;
|
|
745
|
+
case 'auto-direct': return '代理:直连(未检测到代理)';
|
|
746
|
+
default: return null;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** 把 onOutput(任务中心 logSink)转成行式日志回调;无 sink 时为空操作。 */
|
|
751
|
+
function makeLog(onOutput) {
|
|
752
|
+
if (typeof onOutput !== 'function') return () => {};
|
|
753
|
+
return (s) => onOutput(String(s) + '\n');
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function parseJson(raw) {
|
|
757
|
+
if (raw == null || raw === '') return null;
|
|
758
|
+
try {
|
|
759
|
+
return raw instanceof Uint8Array ? JSON.parse(decodeText(raw)) : JSON.parse(raw);
|
|
760
|
+
} catch {
|
|
761
|
+
return null;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
async function readJson(host, p) {
|
|
766
|
+
return parseJson(await host.readTextFile(p));
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** 归一化相对路径并拒绝危险段(防路径穿越)。 */
|
|
770
|
+
function safeRel(rel) {
|
|
771
|
+
const r = String(rel).replace(/\\/g, '/');
|
|
772
|
+
if (!r || r.startsWith('/') || /^[a-zA-Z]:/.test(r)) throw new Error(`非法相对路径:${rel}`);
|
|
773
|
+
if (r.split('/').includes('..')) throw new Error(`路径含危险段 '..':${rel}`);
|
|
774
|
+
return r;
|
|
775
|
+
}
|