@sparkelf/dsh-plus 0.2.9-alpha.81 → 0.2.9-alpha.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,852 @@
1
+ import { createRequire } from "node:module";
2
+ import { spawnSync } from "node:child_process";
3
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
+ import { dirname, isAbsolute, relative, resolve } from "node:path";
5
+ import { satisfies, valid, validRange } from "semver";
6
+ import { tmpdir } from "node:os";
7
+ import { parseDocument } from "yaml";
8
+ //#region lib/types/patch-set.js
9
+ /**
10
+ * Read the Plus distribution's embedded patch set.
11
+ *
12
+ * The distribution owns one patch set for official DSH and, separately, the patches it
13
+ * carries for third-party packages. Both live inside the distribution package: the
14
+ * manifest declares entries, and each entry's payload is a file under `patches/`. A
15
+ * consumer resolves no independently published patch package.
16
+ *
17
+ * The two lists are governed differently. A Plus entry must target an official package
18
+ * that the profile republishes and overrides; a third-party entry must name its upstream
19
+ * and a retirement condition, and never becomes part of the official patch set.
20
+ */
21
+ function object(value, label) {
22
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be an object");
23
+ return value;
24
+ }
25
+ function string(value, label) {
26
+ if (typeof value !== "string" || value === "") throw new Error(label + " must be a non-empty string");
27
+ return value;
28
+ }
29
+ function range(value, label) {
30
+ const text = string(value, label);
31
+ if (validRange(text) === null) throw new Error(label + " is not a semantic-version range: " + text);
32
+ return text;
33
+ }
34
+ /** A payload stays inside the distribution package it is declared by. */
35
+ function patchFile(distributionDirectory, declared, label) {
36
+ const absolute = resolve(distributionDirectory, declared);
37
+ const local = relative(distributionDirectory, absolute);
38
+ if (local === "" || isAbsolute(local) || local === ".." || local.startsWith("../")) throw new Error(label + " must stay inside the distribution package: " + declared);
39
+ if (!existsSync(absolute)) throw new Error(label + " does not exist: " + absolute);
40
+ return local.replaceAll("\\", "/");
41
+ }
42
+ function sourceTarget(value, sourceBaseRevision, label) {
43
+ const target = object(value, label);
44
+ if (target.kind !== "dsh-source") throw new Error(label + ".kind must be dsh-source");
45
+ if (!Array.isArray(target.paths) || target.paths.length === 0) throw new Error(label + ".paths must be a non-empty array");
46
+ const paths = target.paths.map((entry, index) => {
47
+ const path = string(entry, label + ".paths[" + String(index) + "]");
48
+ if (!path.endsWith("/")) throw new Error(label + ".paths entries must be repository directory prefixes");
49
+ return path;
50
+ });
51
+ if (!Array.isArray(target.packages) || target.packages.length === 0) throw new Error(label + ".packages must be a non-empty array");
52
+ return {
53
+ kind: "dsh-source",
54
+ baseRevision: sourceBaseRevision,
55
+ packages: target.packages.map((entry, index) => {
56
+ const name = string(entry, label + ".packages[" + String(index) + "]");
57
+ if (!name.startsWith("@deepseek-ai/")) throw new Error(label + ".packages entries must be official package names");
58
+ return name;
59
+ }),
60
+ paths
61
+ };
62
+ }
63
+ function npmTarget(value, label) {
64
+ const target = object(value, label);
65
+ if (target.kind !== "npm") throw new Error(label + ".kind must be npm");
66
+ return {
67
+ kind: "npm",
68
+ name: string(target.name, label + ".name"),
69
+ range: range(target.range, label + ".range")
70
+ };
71
+ }
72
+ function entry(value, scope, sourceBaseRevision, distributionDirectory, label) {
73
+ const record = object(value, label);
74
+ const id = string(record.id, label + ".id");
75
+ const dsh = range(record.dsh, label + ".dsh");
76
+ const file = patchFile(distributionDirectory, string(record.file, label + ".file"), label + ".file");
77
+ const retireWhen = string(record.retireWhen, label + ".retireWhen");
78
+ const targetLabel = label + ".target";
79
+ const target = scope === "plus" ? object(record.target, targetLabel).kind === "dsh-source" ? sourceTarget(record.target, sourceBaseRevision, targetLabel) : npmTarget(record.target, targetLabel) : npmTarget(record.target, targetLabel);
80
+ if (scope === "third-party") return {
81
+ id,
82
+ scope,
83
+ dsh,
84
+ file,
85
+ retireWhen,
86
+ upstreamUrl: string(record.upstreamUrl, label + ".upstreamUrl"),
87
+ target
88
+ };
89
+ return {
90
+ id,
91
+ scope,
92
+ dsh,
93
+ file,
94
+ retireWhen,
95
+ target
96
+ };
97
+ }
98
+ /**
99
+ * Read and validate the embedded patch set from an installed distribution.
100
+ * @param distributionDirectory - installed `@sparkelf/dsh-plus` directory.
101
+ * @param manifest - its parsed package manifest.
102
+ * @returns the ordered Plus entries, third-party entries, and the exact source base.
103
+ */
104
+ function readPatchSet(distributionDirectory, manifest) {
105
+ const plus = object(manifest.dshPlus, "dshPlus");
106
+ const sourceBaseRevision = string(object(plus.sourceBase, "dshPlus.sourceBase").revision, "dshPlus.sourceBase.revision");
107
+ const declaration = object(plus.patchSet, "dshPlus.patchSet");
108
+ if (declaration.formatVersion !== 1) throw new Error("dshPlus.patchSet.formatVersion must be 1");
109
+ if (!Array.isArray(declaration.entries) || declaration.entries.length === 0) throw new Error("dshPlus.patchSet.entries must be a non-empty array");
110
+ const entries = declaration.entries.map((value, index) => entry(value, "plus", sourceBaseRevision, distributionDirectory, "dshPlus.patchSet.entries[" + String(index) + "]"));
111
+ const thirdPartyRaw = plus.thirdPartyPatches;
112
+ const thirdParty = thirdPartyRaw === void 0 ? [] : Array.isArray(thirdPartyRaw) ? thirdPartyRaw.map((value, index) => entry(value, "third-party", sourceBaseRevision, distributionDirectory, "dshPlus.thirdPartyPatches[" + String(index) + "]")) : (() => {
113
+ throw new Error("dshPlus.thirdPartyPatches must be an array");
114
+ })();
115
+ const ids = /* @__PURE__ */ new Set();
116
+ for (const item of [...entries, ...thirdParty]) {
117
+ if (ids.has(item.id)) throw new Error("duplicate patch entry id: " + item.id);
118
+ ids.add(item.id);
119
+ }
120
+ return {
121
+ entries,
122
+ thirdPartyPatches: thirdParty,
123
+ sourceBaseRevision
124
+ };
125
+ }
126
+ //#endregion
127
+ //#region lib/types/apply.js
128
+ /** Materialize the Plus distribution's independent patch packages without Desktop. */
129
+ const FORMAT_VERSION = 1;
130
+ function isSelectedNpmPatch(patch) {
131
+ return patch.target.kind === "npm";
132
+ }
133
+ function readJsonObject(path, label) {
134
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
135
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(label + " must be a JSON object");
136
+ return parsed;
137
+ }
138
+ function requireObject(value, label) {
139
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be an object");
140
+ return value;
141
+ }
142
+ function requireString(value, label) {
143
+ if (typeof value !== "string" || value === "") throw new Error(label + " must be a non-empty string");
144
+ return value;
145
+ }
146
+ function requireRange(value, label) {
147
+ const range = requireString(value, label);
148
+ if (validRange(range) === null) throw new Error(label + " is not a semantic-version range: " + range);
149
+ return range;
150
+ }
151
+ function requireVersion(value, label) {
152
+ const version = requireString(value, label);
153
+ if (valid(version) === null) throw new Error(label + " is not a semantic version: " + version);
154
+ return version;
155
+ }
156
+ function requireStringArray(value, label) {
157
+ if (!Array.isArray(value) || value.length === 0) throw new Error(label + " must be a non-empty array");
158
+ const strings = value.map((entry, index) => requireString(entry, label + "[" + String(index) + "]"));
159
+ if (new Set(strings).size !== strings.length) throw new Error(label + " must not contain duplicates");
160
+ return strings;
161
+ }
162
+ /**
163
+ * Resolve one installed package's manifest directory.
164
+ *
165
+ * `require.resolve(name + '/package.json')` respects the package's `exports`
166
+ * map, so a dependency that publishes only `"."` — `@sparkelf/dsh-quant`
167
+ * 0.91.0-sparkelf.13 among the `personal` edition's packages — fails to
168
+ * resolve even though the package is installed. Reading a manifest is not a
169
+ * public-export lookup, so resolve the package entry and walk up to the
170
+ * manifest that names it.
171
+ * @param distributionDirectory - directory whose resolution anchors the lookup.
172
+ * @param packageName - dependency name to locate.
173
+ * @returns path of the `package.json` that declares `packageName`.
174
+ */
175
+ function resolvePackageManifest(distributionDirectory, packageName) {
176
+ const requireFromDistribution = createRequire(resolve(distributionDirectory, "package.json"));
177
+ try {
178
+ return requireFromDistribution.resolve(packageName + "/package.json");
179
+ } catch {}
180
+ let directory = dirname(requireFromDistribution.resolve(packageName));
181
+ for (;;) {
182
+ const candidate = resolve(directory, "package.json");
183
+ if (existsSync(candidate)) {
184
+ if (JSON.parse(readFileSync(candidate, "utf8")).name === packageName) return candidate;
185
+ }
186
+ const parent = dirname(directory);
187
+ if (parent === directory) throw new Error(packageName + " is installed but no package.json naming it was found");
188
+ directory = parent;
189
+ }
190
+ }
191
+ function resolveInstalledPackage(distributionDirectory, packageName) {
192
+ const manifestPath = resolvePackageManifest(distributionDirectory, packageName);
193
+ const manifest = readJsonObject(manifestPath, packageName + " manifest");
194
+ return {
195
+ name: packageName,
196
+ version: requireVersion(manifest.version, packageName + " version"),
197
+ directory: dirname(manifestPath),
198
+ manifest
199
+ };
200
+ }
201
+ function resolvePatchFile(packageDirectory, declared) {
202
+ const absoluteFile = resolve(packageDirectory, declared);
203
+ const local = relative(packageDirectory, absoluteFile);
204
+ if (isAbsolute(local) || local === ".." || local.startsWith("../")) throw new Error("patch file must stay inside its patch package: " + declared);
205
+ if (!existsSync(absoluteFile)) throw new Error("patch file does not exist: " + absoluteFile);
206
+ return {
207
+ relativeFile: local.replaceAll("\\", "/"),
208
+ absoluteFile
209
+ };
210
+ }
211
+ function parseVariant(value, index, patchPackage) {
212
+ const label = patchPackage.name + " dshPatch.variants[" + String(index) + "]";
213
+ const variant = requireObject(value, label);
214
+ const target = requireObject(variant.target, label + ".target");
215
+ const kind = requireString(target.kind, label + ".target.kind");
216
+ const common = {
217
+ id: requireString(variant.id, label + ".id"),
218
+ dsh: requireRange(variant.dsh, label + ".dsh"),
219
+ file: requireString(variant.file, label + ".file"),
220
+ patchPackage
221
+ };
222
+ if (kind === "npm") return {
223
+ ...common,
224
+ target: {
225
+ kind,
226
+ name: requireString(target.name, label + ".target.name"),
227
+ range: requireRange(target.range, label + ".target.range")
228
+ }
229
+ };
230
+ if (kind === "dsh-source") return {
231
+ ...common,
232
+ target: {
233
+ kind,
234
+ baseRevision: requireString(target.baseRevision, label + ".target.baseRevision")
235
+ }
236
+ };
237
+ throw new Error("unsupported patch target kind: " + kind);
238
+ }
239
+ function git(root, args, acceptFailure = false) {
240
+ const result = spawnSync("git", args, {
241
+ cwd: root,
242
+ encoding: "utf8"
243
+ });
244
+ if (result.status === 0) return result.stdout.trim();
245
+ if (acceptFailure) return void 0;
246
+ const detail = result.stderr.trim();
247
+ throw new Error("git " + args.join(" ") + " failed" + (detail === "" ? "" : ": " + detail));
248
+ }
249
+ function sourcePatchState(root, file) {
250
+ if (git(root, [
251
+ "apply",
252
+ "--check",
253
+ file
254
+ ], true) !== void 0) return "pending";
255
+ if (git(root, [
256
+ "apply",
257
+ "--reverse",
258
+ "--check",
259
+ file
260
+ ], true) !== void 0) return "applied";
261
+ git(root, [
262
+ "apply",
263
+ "--check",
264
+ file
265
+ ]);
266
+ throw new Error("unreachable");
267
+ }
268
+ /** 在隔离index中按真实顺序预演source patches,避免失败后污染official worktree。 */
269
+ function preflightSourcePatches(root, files) {
270
+ if (files.length === 0) return;
271
+ const directory = mkdtempSync(resolve(tmpdir(), "dsh-plus-source-patches-"));
272
+ const index = resolve(directory, "index");
273
+ const env = {
274
+ ...process.env,
275
+ GIT_INDEX_FILE: index
276
+ };
277
+ const run = (args) => {
278
+ const result = spawnSync("git", args, {
279
+ cwd: root,
280
+ encoding: "utf8",
281
+ env
282
+ });
283
+ if (result.status === 0) return;
284
+ const detail = result.stderr.trim();
285
+ throw new Error("git " + args.join(" ") + " failed" + (detail === "" ? "" : ": " + detail));
286
+ };
287
+ try {
288
+ run(["read-tree", "HEAD"]);
289
+ for (const file of files) run([
290
+ "apply",
291
+ "--cached",
292
+ "--3way",
293
+ file
294
+ ]);
295
+ } finally {
296
+ rmSync(directory, {
297
+ recursive: true,
298
+ force: true
299
+ });
300
+ }
301
+ }
302
+ function requireSourceBase(root, baseRevision) {
303
+ const checkoutRevision = requireString(git(root, ["rev-parse", "HEAD"]), "DSH checkout revision");
304
+ if (checkoutRevision !== baseRevision) throw new Error("DSH checkout must be exact official base " + baseRevision + ", found " + checkoutRevision);
305
+ return checkoutRevision;
306
+ }
307
+ /**
308
+ * Names of distribution dependencies that carry `dshPatch` variants.
309
+ *
310
+ * `patchPackageVariants()` resolves these names from the Plus install tree, so they must be
311
+ * packages this distribution actually depends on. The current manifest declares `dshPlus.patchSet`
312
+ * instead of a flat list: only entries whose target is an npm package name a `dshPatch` carrier
313
+ * (`dsh-source` entries name the source packages being patched, which are never Plus dependencies).
314
+ * An older tarball may still carry the flat `dshPlus.patchPackages` list, which wins when present.
315
+ *
316
+ * @param plus - Parsed `dshPlus` block of the distribution manifest.
317
+ * @returns Patch-carrier package names; empty when the distribution ships only source patches.
318
+ */
319
+ function resolvePatchPackageNames(plus) {
320
+ const declared = plus.patchPackages;
321
+ if (declared !== void 0) {
322
+ const names = requireStringArray(declared, "dshPlus.patchPackages");
323
+ if (names.length > 0) return names;
324
+ }
325
+ const entries = requireObject(plus.patchSet, "dshPlus.patchSet").entries;
326
+ if (!Array.isArray(entries)) throw new Error("dshPlus.patchSet.entries must be an array");
327
+ const names = /* @__PURE__ */ new Set();
328
+ for (const [index, value] of entries.entries()) {
329
+ const target = requireObject(requireObject(value, "dshPlus.patchSet.entries[" + String(index) + "]").target, "dshPlus.patchSet.entries[" + String(index) + "].target");
330
+ if (target.kind !== "npm") continue;
331
+ names.add(requireString(target.name, "dshPlus.patchSet.entries[" + String(index) + "].target.name"));
332
+ }
333
+ return [...names].sort();
334
+ }
335
+ function patchPackageVariants(distributionDirectory, names) {
336
+ const variants = [];
337
+ for (const name of names) {
338
+ const patchPackage = resolveInstalledPackage(distributionDirectory, name);
339
+ const declaration = requireObject(patchPackage.manifest.dshPatch, name + " dshPatch");
340
+ if (declaration.formatVersion !== FORMAT_VERSION) throw new Error("unsupported dshPatch formatVersion in " + name + ": " + String(declaration.formatVersion));
341
+ if (!Array.isArray(declaration.variants) || declaration.variants.length === 0) throw new Error(name + " dshPatch.variants must be a non-empty array");
342
+ for (const [index, value] of declaration.variants.entries()) variants.push(parseVariant(value, index, patchPackage));
343
+ }
344
+ return variants;
345
+ }
346
+ /**
347
+ * Build patch variants from the distribution's `dshPlus.patchSet`.
348
+ *
349
+ * The patch files live inside the Plus package (`./patches/*.patch`), so every variant points at
350
+ * the distribution itself as its patch package: `resolvePatchFile()` then resolves the declared
351
+ * path inside the tarball, and `materializePatchFiles()` copies it into the profile's stable
352
+ * patch directory. Unlike the retired `dshPatch` carrier packages, the source packages named in
353
+ * `target.packages` are never resolved from the Plus tree -- they are the packages being patched.
354
+ *
355
+ * @param distribution - Installed Plus distribution package.
356
+ */
357
+ function patchSetVariants(distribution) {
358
+ const patchSet = readPatchSet(distribution.directory, distribution.manifest);
359
+ return [...patchSet.entries, ...patchSet.thirdPartyPatches].map((entry) => ({
360
+ id: entry.id,
361
+ dsh: entry.dsh,
362
+ file: entry.file,
363
+ patchPackage: distribution,
364
+ target: entry.target.kind === "npm" ? {
365
+ kind: "npm",
366
+ name: entry.target.name,
367
+ range: entry.target.range
368
+ } : {
369
+ kind: "dsh-source",
370
+ baseRevision: entry.target.baseRevision
371
+ }
372
+ }));
373
+ }
374
+ function prepareSelection(distributionDirectory, profileDirectory, dshRoot) {
375
+ const distributionManifest = readJsonObject(resolve(distributionDirectory, "package.json"), "Plus distribution manifest");
376
+ const distributionName = requireString(distributionManifest.name, "Plus distribution name");
377
+ const distributionVersion = requireVersion(distributionManifest.version, "Plus distribution version");
378
+ const plus = requireObject(distributionManifest.dshPlus, "Plus distribution dshPlus");
379
+ if (plus.formatVersion !== FORMAT_VERSION) throw new Error("unsupported dshPlus formatVersion: " + String(plus.formatVersion));
380
+ const dshRange = requireRange(requireObject(plus.compatibility, "dshPlus.compatibility").dsh, "dshPlus.compatibility.dsh");
381
+ const baseRevision = requireString(requireObject(plus.sourceBase, "dshPlus.sourceBase").revision, "dshPlus.sourceBase.revision");
382
+ const profile = requireObject(plus.profile, "dshPlus.profile");
383
+ const bundles = requireStringArray(profile.bundles, "dshPlus.profile.bundles");
384
+ const rawProfileDependencySpecs = requireObject(profile.dependencies, "dshPlus.profile.dependencies");
385
+ const profileDependencySpecs = {};
386
+ for (const [name, spec] of Object.entries(rawProfileDependencySpecs)) profileDependencySpecs[name] = requireString(spec, "dshPlus.profile.dependencies." + name);
387
+ const rawAllowBuilds = requireObject(profile.allowBuilds, "dshPlus.profile.allowBuilds");
388
+ const allowBuilds = {};
389
+ for (const [name, allowed] of Object.entries(rawAllowBuilds)) {
390
+ if (typeof allowed !== "boolean") throw new Error("dshPlus.profile.allowBuilds." + name + " must be a boolean");
391
+ allowBuilds[name] = allowed;
392
+ }
393
+ const patchPackageNames = resolvePatchPackageNames(plus);
394
+ const dependencies = requireObject(distributionManifest.dependencies, "Plus distribution dependencies");
395
+ const dshVersion = requireVersion(readJsonObject(resolve(dshRoot, "package.json"), "DSH source manifest").version, "DSH source version");
396
+ if (!satisfies(dshVersion, dshRange, { includePrerelease: true })) throw new Error(distributionName + "@" + distributionVersion + " requires DSH " + dshRange + ", found " + dshVersion);
397
+ const checkoutRevision = requireSourceBase(dshRoot, baseRevision);
398
+ const variants = plus.patchPackages === void 0 ? patchSetVariants({
399
+ name: distributionName,
400
+ version: distributionVersion,
401
+ directory: distributionDirectory,
402
+ manifest: distributionManifest
403
+ }) : patchPackageVariants(distributionDirectory, patchPackageNames);
404
+ const groups = /* @__PURE__ */ new Map();
405
+ for (const variant of variants) {
406
+ const entries = groups.get(variant.id) ?? [];
407
+ entries.push(variant);
408
+ groups.set(variant.id, entries);
409
+ }
410
+ const sourceStates = /* @__PURE__ */ new Map();
411
+ const orderedGroups = [...groups].sort(([left], [right]) => left.localeCompare(right));
412
+ for (const [, variants] of orderedGroups) for (const variant of variants) {
413
+ if (variant.target.kind !== "dsh-source" || variant.target.baseRevision !== baseRevision || !satisfies(dshVersion, variant.dsh, { includePrerelease: true })) continue;
414
+ const file = resolvePatchFile(variant.patchPackage.directory, variant.file);
415
+ sourceStates.set(file.absoluteFile, sourcePatchState(dshRoot, file.absoluteFile));
416
+ }
417
+ preflightSourcePatches(dshRoot, [...sourceStates].flatMap(([file, state]) => state === "pending" ? [file] : []));
418
+ writeProfileRequirements(profileDirectory, profileDependencySpecs, allowBuilds);
419
+ runPnpm(profileDirectory, ["install", "--no-frozen-lockfile"], "pnpm install Plus profile dependencies");
420
+ const profileDependencies = Object.keys(profileDependencySpecs).sort().map((name) => {
421
+ return {
422
+ name,
423
+ version: resolveInstalledPackage(profileDirectory, name).version
424
+ };
425
+ });
426
+ const runtimePackages = [...Object.keys(dependencies).filter((name) => !patchPackageNames.includes(name)).sort().map((name) => {
427
+ return {
428
+ name,
429
+ version: resolveInstalledPackage(distributionDirectory, name).version
430
+ };
431
+ }), ...profileDependencies].sort((left, right) => left.name.localeCompare(right.name));
432
+ const selected = [];
433
+ for (const [id, variants] of orderedGroups) {
434
+ const candidates = variants.flatMap((variant) => {
435
+ if (!satisfies(dshVersion, variant.dsh, { includePrerelease: true })) return [];
436
+ const file = resolvePatchFile(variant.patchPackage.directory, variant.file);
437
+ if (variant.target.kind === "dsh-source") {
438
+ if (variant.target.baseRevision !== baseRevision) return [];
439
+ return [{
440
+ id,
441
+ patchPackage: {
442
+ name: variant.patchPackage.name,
443
+ version: variant.patchPackage.version
444
+ },
445
+ file: file.relativeFile,
446
+ absoluteFile: file.absoluteFile,
447
+ target: {
448
+ kind: "dsh-source",
449
+ baseRevision
450
+ },
451
+ alreadyApplied: sourceStates.get(file.absoluteFile) === "applied"
452
+ }];
453
+ }
454
+ const targetVersion = resolveInstalledPackage(variant.target.name in profileDependencySpecs ? profileDirectory : distributionDirectory, variant.target.name).version;
455
+ if (!satisfies(targetVersion, variant.target.range, { includePrerelease: true })) return [];
456
+ return [{
457
+ id,
458
+ patchPackage: {
459
+ name: variant.patchPackage.name,
460
+ version: variant.patchPackage.version
461
+ },
462
+ file: file.relativeFile,
463
+ absoluteFile: file.absoluteFile,
464
+ target: {
465
+ kind: "npm",
466
+ name: variant.target.name,
467
+ version: targetVersion
468
+ }
469
+ }];
470
+ });
471
+ const [candidate] = candidates;
472
+ if (candidate === void 0) throw new Error("no compatible patch variant for " + id + " on DSH " + dshVersion);
473
+ if (candidates.length > 1) throw new Error("multiple compatible patch variants for " + id + " on DSH " + dshVersion);
474
+ selected.push(candidate);
475
+ }
476
+ const lockPatches = selected.map((patch) => {
477
+ if ("alreadyApplied" in patch) {
478
+ const { absoluteFile: _absoluteFile, alreadyApplied: _alreadyApplied, ...locked } = patch;
479
+ return locked;
480
+ }
481
+ const { absoluteFile: _absoluteFile, ...locked } = patch;
482
+ return locked;
483
+ });
484
+ return {
485
+ patches: selected,
486
+ bundles,
487
+ runtimePackages,
488
+ profileDependencies,
489
+ allowBuilds,
490
+ lock: {
491
+ formatVersion: FORMAT_VERSION,
492
+ distribution: {
493
+ name: distributionName,
494
+ version: distributionVersion
495
+ },
496
+ dsh: {
497
+ version: dshVersion,
498
+ baseRevision,
499
+ checkoutRevision
500
+ },
501
+ runtimePackages,
502
+ patches: lockPatches
503
+ }
504
+ };
505
+ }
506
+ /** 保留每个独立payload,并为同一npm目标生成pnpm可消费的唯一组合patch。 */
507
+ function materializePatchFiles(profileDirectory, patches) {
508
+ const root = resolve(profileDirectory, ".dsh-plus", "patches");
509
+ rmSync(root, {
510
+ recursive: true,
511
+ force: true
512
+ });
513
+ const stablePatches = patches.map((patch) => {
514
+ const destination = resolve(root, patch.patchPackage.name, patch.patchPackage.version, patch.file);
515
+ mkdirSync(dirname(destination), { recursive: true });
516
+ copyFileSync(patch.absoluteFile, destination);
517
+ return {
518
+ ...patch,
519
+ absoluteFile: destination
520
+ };
521
+ });
522
+ const npmGroups = /* @__PURE__ */ new Map();
523
+ for (const patch of stablePatches) {
524
+ if (!isSelectedNpmPatch(patch)) continue;
525
+ const key = patch.target.name + "@" + patch.target.version;
526
+ const group = npmGroups.get(key);
527
+ if (group === void 0) npmGroups.set(key, [patch]);
528
+ else group.push(patch);
529
+ }
530
+ const npmPatchFiles = /* @__PURE__ */ new Map();
531
+ for (const [key, group] of npmGroups) {
532
+ const first = group[0];
533
+ if (group.length === 1) {
534
+ npmPatchFiles.set(key, first.absoluteFile);
535
+ continue;
536
+ }
537
+ const members = group.map((patch) => encodeURIComponent(patch.id + "@" + patch.patchPackage.version)).join("+");
538
+ const destination = resolve(root, "combined", encodeURIComponent(key), members + ".patch");
539
+ mkdirSync(dirname(destination), { recursive: true });
540
+ writeFileSync(destination, group.map((patch) => {
541
+ const content = readFileSync(patch.absoluteFile, "utf8");
542
+ return content.endsWith("\n") ? content : content + "\n";
543
+ }).join(""));
544
+ npmPatchFiles.set(key, destination);
545
+ }
546
+ return {
547
+ patches: stablePatches,
548
+ npmPatchFiles
549
+ };
550
+ }
551
+ function profilePatchConfiguration(profileDirectory, npmPatchFiles) {
552
+ const document = parseDocument(readFileSync(resolve(profileDirectory, "pnpm-workspace.yaml"), "utf8"));
553
+ const [documentError] = document.errors;
554
+ if (documentError !== void 0) throw new Error("Plus profile workspace is not valid YAML", { cause: documentError });
555
+ let changed = false;
556
+ const desiredKeys = new Set(npmPatchFiles.keys());
557
+ const workspace = requireObject(document.toJS(), "Plus profile workspace");
558
+ const configured = workspace.patchedDependencies === void 0 ? {} : requireObject(workspace.patchedDependencies, "Plus profile patchedDependencies");
559
+ for (const [key, value] of Object.entries(configured)) if (typeof value === "string" && value.startsWith(".dsh-plus/patches/") && !desiredKeys.has(key)) {
560
+ document.deleteIn(["patchedDependencies", key]);
561
+ changed = true;
562
+ }
563
+ for (const [key, file] of npmPatchFiles) {
564
+ const value = relative(profileDirectory, file).replaceAll("\\", "/");
565
+ const current = document.getIn(["patchedDependencies", key]);
566
+ if (current !== void 0 && current !== value && (typeof current !== "string" || !current.startsWith(".dsh-plus/patches/"))) throw new Error("profile patchedDependencies." + key + " is already owned by another payload");
567
+ if (current === value) continue;
568
+ document.setIn(["patchedDependencies", key], value);
569
+ changed = true;
570
+ }
571
+ return {
572
+ text: String(document),
573
+ changed
574
+ };
575
+ }
576
+ /**
577
+ * Profile-local pnpm hook that keeps the CDN-only xlsx dependency installable.
578
+ *
579
+ * `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` declares `xlsx` as
580
+ * `https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz`. SheetJS stopped publishing to npm
581
+ * after 0.18.5, so no registry mirror carries 0.20.3, and the build network cannot reach that
582
+ * CDN (measured 2026-11-06: every request times out). The image vendors the tarball at
583
+ * /opt/dsh-vendor; this hook rewrites the spec wherever it appears so a cold profile install
584
+ * never requests the CDN.
585
+ *
586
+ * Written into the profile root rather than a template: the Plus bundle has no profile
587
+ * template directory, the profile manifest and pnpm-workspace.yaml are generated here.
588
+ */
589
+ const PROFILE_PNPMFILE = `// Generated by @sparkelf/dsh-plus -- do not edit; rewritten on every apply.
590
+ const VENDORED_XLSX = '/opt/dsh-vendor/xlsx-0.20.3.tgz'
591
+ const CDN_XLSX = /^https?:\\/\\/cdn\\.sheetjs\\.com\\//
592
+ const FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']
593
+
594
+ module.exports = {
595
+ hooks: {
596
+ readPackage(pkg) {
597
+ for (const field of FIELDS) {
598
+ const deps = pkg && pkg[field]
599
+ if (deps && typeof deps.xlsx === 'string' && CDN_XLSX.test(deps.xlsx)) {
600
+ deps.xlsx = 'file:' + VENDORED_XLSX
601
+ }
602
+ }
603
+ return pkg
604
+ },
605
+ },
606
+ }
607
+ `;
608
+ /** Write the profile pnpmfile when its content changed; returns whether it wrote. */
609
+ function writeProfilePnpmfile(profileDirectory) {
610
+ const path = resolve(profileDirectory, ".pnpmfile.cjs");
611
+ if ((existsSync(path) ? readFileSync(path, "utf8") : void 0) === PROFILE_PNPMFILE) return false;
612
+ writeFileSync(path, PROFILE_PNPMFILE);
613
+ console.log("profile pnpmfile: xlsx -> /opt/dsh-vendor/xlsx-0.20.3.tgz");
614
+ return true;
615
+ }
616
+ function writeProfileRequirements(profileDirectory, dependencySpecs, allowBuilds) {
617
+ const manifestPath = resolve(profileDirectory, "package.json");
618
+ const manifest = readJsonObject(manifestPath, "DSH profile manifest");
619
+ const dependencies = requireObject(manifest.dependencies, "DSH profile dependencies");
620
+ let manifestChanged = false;
621
+ for (const [name, spec] of Object.entries(dependencySpecs)) {
622
+ const current = dependencies[name];
623
+ if (current !== void 0 && current !== spec) throw new Error("profile dependency " + name + " is configured as " + JSON.stringify(current) + ", expected " + spec);
624
+ if (current === void 0) {
625
+ dependencies[name] = spec;
626
+ manifestChanged = true;
627
+ }
628
+ }
629
+ const workspacePath = resolve(profileDirectory, "pnpm-workspace.yaml");
630
+ const document = parseDocument(readFileSync(workspacePath, "utf8"));
631
+ const [documentError] = document.errors;
632
+ if (documentError !== void 0) throw new Error("Plus profile workspace is not valid YAML", { cause: documentError });
633
+ let workspaceChanged = false;
634
+ const autoInstallPeers = document.get("autoInstallPeers");
635
+ if (autoInstallPeers !== void 0 && autoInstallPeers !== false) throw new Error("profile autoInstallPeers must be false because official peers come from the selected DSH source");
636
+ if (autoInstallPeers === void 0) {
637
+ document.set("autoInstallPeers", false);
638
+ workspaceChanged = true;
639
+ }
640
+ const managedFileAsset = (value) => value.startsWith("file:") && (/[\\/]\.dsh[\\/]releases[\\/]plus[\\/].*[\\/]packages[\\/]/u.test(value) || /[\\/]\.dsh-plus[\\/]packages[\\/]/u.test(value));
641
+ const retiredOverrides = new Set([
642
+ "@huanlin/dsh-plugin-better-sidebar-plugin-office",
643
+ "@sparkelf/dsh-office-viewer-fonts",
644
+ "dsh-better-sidebar",
645
+ "dsh-video-preview"
646
+ ]);
647
+ const workspace = requireObject(document.toJS(), "Plus profile workspace");
648
+ const configuredOverrides = workspace.overrides === void 0 ? {} : requireObject(workspace.overrides, "Plus profile overrides");
649
+ for (const [name, value] of Object.entries(configuredOverrides)) if (retiredOverrides.has(name) || typeof value === "string" && managedFileAsset(value)) {
650
+ document.deleteIn(["overrides", name]);
651
+ workspaceChanged = true;
652
+ }
653
+ for (const [name, allowed] of Object.entries(allowBuilds)) {
654
+ const current = document.getIn(["allowBuilds", name]);
655
+ if (current !== void 0 && current !== allowed) throw new Error("profile allowBuilds." + name + " is configured as " + JSON.stringify(current) + ", expected " + String(allowed));
656
+ if (current === void 0) {
657
+ document.setIn(["allowBuilds", name], allowed);
658
+ workspaceChanged = true;
659
+ }
660
+ }
661
+ if (manifestChanged) {
662
+ manifest.dependencies = dependencies;
663
+ writeFileSync(manifestPath, JSON.stringify(manifest, void 0, 2) + "\n");
664
+ }
665
+ if (workspaceChanged) writeFileSync(workspacePath, String(document));
666
+ const pnpmfileChanged = writeProfilePnpmfile(profileDirectory);
667
+ return manifestChanged || workspaceChanged || pnpmfileChanged;
668
+ }
669
+ function writeProfileComposition(profileDirectory, bundles, runtimePackages) {
670
+ const path = resolve(profileDirectory, "package.json");
671
+ const manifest = readJsonObject(path, "DSH profile manifest");
672
+ const dependencies = requireObject(manifest.dependencies, "DSH profile dependencies");
673
+ let changed = false;
674
+ for (const runtimePackage of runtimePackages) {
675
+ if (dependencies[runtimePackage.name] === void 0) {
676
+ dependencies[runtimePackage.name] = runtimePackage.version;
677
+ changed = true;
678
+ continue;
679
+ }
680
+ const installed = resolveInstalledPackage(profileDirectory, runtimePackage.name);
681
+ if (installed.version !== runtimePackage.version) throw new Error("profile dependency " + runtimePackage.name + " resolves to " + installed.version + ", but the Plus distribution requires " + runtimePackage.version);
682
+ }
683
+ const dsh = manifest.dsh === void 0 ? {} : requireObject(manifest.dsh, "DSH profile dsh");
684
+ const profile = dsh.profile === void 0 ? {} : requireObject(dsh.profile, "DSH profile dsh.profile");
685
+ if (JSON.stringify(profile.bundles) !== JSON.stringify(bundles)) changed = true;
686
+ manifest.dependencies = dependencies;
687
+ manifest.dsh = {
688
+ ...dsh,
689
+ profile: {
690
+ ...profile,
691
+ bundles: [...bundles]
692
+ }
693
+ };
694
+ if (changed) writeFileSync(path, JSON.stringify(manifest, void 0, 2) + "\n");
695
+ return changed;
696
+ }
697
+ function runPnpm(profileDirectory, args, label) {
698
+ const result = spawnSync("pnpm", args, {
699
+ cwd: profileDirectory,
700
+ stdio: "inherit",
701
+ shell: process.platform === "win32"
702
+ });
703
+ if (result.error !== void 0) throw result.error;
704
+ if (result.status !== 0) throw new Error(label + " failed with exit code " + String(result.status));
705
+ }
706
+ function pendingSourcePatchFiles(patches) {
707
+ return patches.flatMap((patch) => "alreadyApplied" in patch && !patch.alreadyApplied ? [patch.absoluteFile] : []);
708
+ }
709
+ function applySelectedPatches(profileDirectory, dshRoot, patches, profileChanged) {
710
+ const materialized = materializePatchFiles(profileDirectory, patches);
711
+ const workspacePath = resolve(profileDirectory, "pnpm-workspace.yaml");
712
+ const workspace = profilePatchConfiguration(profileDirectory, materialized.npmPatchFiles);
713
+ if (workspace.changed) writeFileSync(workspacePath, workspace.text);
714
+ if (profileChanged || workspace.changed) runPnpm(profileDirectory, ["install", "--no-frozen-lockfile"], "pnpm install in Plus profile");
715
+ const sourceFiles = pendingSourcePatchFiles(materialized.patches);
716
+ if (sourceFiles.length > 0) git(dshRoot, ["update-index", "--refresh"], true);
717
+ for (const file of sourceFiles) git(dshRoot, [
718
+ "apply",
719
+ "--3way",
720
+ file
721
+ ]);
722
+ if (materialized.patches.some((patch) => patch.target.kind === "dsh-source")) {
723
+ if (sourceFiles.length > 0) runPnpm(dshRoot, ["install", "--no-frozen-lockfile"], "pnpm install after source patches");
724
+ runPnpm(dshRoot, ["run", "build:official"], "official DSH build after source patches");
725
+ }
726
+ }
727
+ function officialPackageRoot(dshRoot) {
728
+ return resolve(dshRoot, "apps", "cli");
729
+ }
730
+ /**
731
+ * Parse pnpm's workspace roster into exact official package directories.
732
+ * @param dshRoot - exact official DSH checkout root.
733
+ * @param stdout - JSON emitted by `pnpm -r list --json --depth -1`.
734
+ * @returns sorted official package names and directories inside the checkout.
735
+ */
736
+ function parseOfficialWorkspacePackages(dshRoot, stdout) {
737
+ const parsed = JSON.parse(stdout);
738
+ if (!Array.isArray(parsed)) throw new Error("pnpm workspace package list must be an array");
739
+ const packages = /* @__PURE__ */ new Map();
740
+ for (const [index, value] of parsed.entries()) {
741
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("pnpm workspace package list[" + String(index) + "] must be an object");
742
+ const entry = value;
743
+ if (typeof entry.name !== "string" || !entry.name.startsWith("@deepseek-ai/")) continue;
744
+ const localName = entry.name.slice(13);
745
+ if (localName === "" || localName.includes("/")) throw new Error("unsupported official workspace package name: " + entry.name);
746
+ if (typeof entry.path !== "string" || entry.path === "") throw new Error("pnpm workspace package " + entry.name + " has no path");
747
+ const directory = resolve(dshRoot, entry.path);
748
+ const local = relative(dshRoot, directory);
749
+ if (isAbsolute(local) || local === ".." || local.startsWith("../")) throw new Error("official workspace package escapes DSH root: " + entry.name);
750
+ const previous = packages.get(entry.name);
751
+ if (previous !== void 0 && previous !== directory) throw new Error("duplicate official workspace package: " + entry.name);
752
+ packages.set(entry.name, directory);
753
+ }
754
+ return [...packages].sort(([left], [right]) => left.localeCompare(right)).map(([name, directory]) => ({
755
+ name,
756
+ directory
757
+ }));
758
+ }
759
+ function listOfficialWorkspacePackages(dshRoot) {
760
+ const result = spawnSync("pnpm", [
761
+ "-r",
762
+ "list",
763
+ "--json",
764
+ "--depth",
765
+ "-1"
766
+ ], {
767
+ cwd: dshRoot,
768
+ encoding: "utf8",
769
+ shell: process.platform === "win32"
770
+ });
771
+ if (result.error !== void 0) throw result.error;
772
+ if (result.status !== 0) throw new Error("pnpm list official DSH workspace packages failed with exit code " + String(result.status));
773
+ return parseOfficialWorkspacePackages(dshRoot, result.stdout);
774
+ }
775
+ /**
776
+ * Build the profile's official scope from the CLI closure plus source workspaces.
777
+ * @param profileDirectory - materialized Plus profile root.
778
+ * @param cliScope - official packages already installed under the DSH CLI.
779
+ * @param workspacePackages - additional official source workspaces required by external peers.
780
+ */
781
+ function materializeOfficialPackageScope(profileDirectory, cliScope, workspacePackages) {
782
+ if (!existsSync(cliScope)) throw new Error("official DSH dependencies are missing under " + cliScope);
783
+ const destination = resolve(profileDirectory, "node_modules", "@deepseek-ai");
784
+ rmSync(destination, {
785
+ recursive: true,
786
+ force: true
787
+ });
788
+ mkdirSync(destination, { recursive: true });
789
+ const linkType = process.platform === "win32" ? "junction" : "dir";
790
+ for (const name of readdirSync(cliScope).sort()) symlinkSync(resolve(cliScope, name), resolve(destination, name), linkType);
791
+ for (const entry of workspacePackages) {
792
+ const target = resolve(destination, entry.name.slice(13));
793
+ rmSync(target, {
794
+ recursive: true,
795
+ force: true
796
+ });
797
+ symlinkSync(entry.directory, target, linkType);
798
+ }
799
+ }
800
+ function linkOfficialPackages(profileDirectory, dshRoot) {
801
+ materializeOfficialPackageScope(profileDirectory, resolve(officialPackageRoot(dshRoot), "node_modules", "@deepseek-ai"), listOfficialWorkspacePackages(dshRoot));
802
+ }
803
+ function writeLock(profileDirectory, lock) {
804
+ const directory = resolve(profileDirectory, ".dsh-plus");
805
+ mkdirSync(directory, { recursive: true });
806
+ const path = resolve(directory, "patchset.lock.json");
807
+ writeFileSync(path, JSON.stringify(lock, void 0, 2) + "\n", { mode: 384 });
808
+ chmodSync(path, 384);
809
+ return path;
810
+ }
811
+ function parseApplyArguments(argv) {
812
+ if (argv[0] !== "apply") throw new Error("usage: dsh-plus apply --dsh-root <official-dsh-root>");
813
+ let dshRoot;
814
+ for (let index = 1; index < argv.length; index += 2) {
815
+ const key = argv[index];
816
+ const value = argv[index + 1];
817
+ if (key !== "--dsh-root" || value === void 0) throw new Error("usage: dsh-plus apply --dsh-root <official-dsh-root>");
818
+ dshRoot = resolve(value);
819
+ }
820
+ if (dshRoot === void 0) throw new Error("usage: dsh-plus apply --dsh-root <official-dsh-root>");
821
+ return {
822
+ dshRoot,
823
+ profileDirectory: process.cwd()
824
+ };
825
+ }
826
+ /**
827
+ * Apply the installed Plus distribution metadata from a DSH profile directory.
828
+ * @param argv - Explicit `apply --dsh-root <path>` command arguments.
829
+ */
830
+ function runApply(argv) {
831
+ const { dshRoot, profileDirectory } = parseApplyArguments(argv);
832
+ if (requireObject(readJsonObject(resolve(profileDirectory, "package.json"), "DSH profile manifest").dependencies, "DSH profile dependencies")["@sparkelf/dsh-plus"] === void 0) throw new Error("current directory is not a DSH profile with @sparkelf/dsh-plus installed");
833
+ const selection = prepareSelection(dirname(createRequire(resolve(profileDirectory, "package.json")).resolve("@sparkelf/dsh-plus/package.json")), profileDirectory, dshRoot);
834
+ const profileChanged = writeProfileComposition(profileDirectory, selection.bundles, selection.runtimePackages);
835
+ applySelectedPatches(profileDirectory, dshRoot, selection.patches, profileChanged);
836
+ linkOfficialPackages(profileDirectory, dshRoot);
837
+ const installedProfileDependencies = requireObject(readJsonObject(resolve(profileDirectory, "package.json"), "DSH profile manifest").dependencies, "DSH profile dependencies");
838
+ selection.lock.profile = {
839
+ bundles: selection.bundles.map((name) => {
840
+ return {
841
+ name,
842
+ version: (installedProfileDependencies[name] === void 0 ? resolveInstalledPackage(officialPackageRoot(dshRoot), name) : resolveInstalledPackage(profileDirectory, name)).version
843
+ };
844
+ }),
845
+ dependencies: selection.profileDependencies,
846
+ allowBuilds: selection.allowBuilds
847
+ };
848
+ const lock = writeLock(profileDirectory, selection.lock);
849
+ process.stdout.write("[dsh-plus] applied " + String(selection.patches.length) + " patches; lock " + lock + "\n");
850
+ }
851
+ //#endregion
852
+ export { readPatchSet as a, runApply as i, parseOfficialWorkspacePackages as n, resolvePatchPackageNames as r, materializeOfficialPackageScope as t };