@sparkelf/dsh-plus 0.2.7-alpha.50 → 0.2.9-alpha.100

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 (56) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/cordis.patch.yml +29 -7
  5. package/lib/{apply-DmICvIGh.js → apply-CvePS57c.js} +213 -43
  6. package/lib/{apply-08huHfLG.js → apply-DycMqLJO.js} +240 -53
  7. package/lib/apply-c_7SZFSh.js +1193 -0
  8. package/lib/apply.js +2 -2
  9. package/lib/bin.js +20 -319
  10. package/lib/types/apply.d.ts +14 -1
  11. package/lib/types/apply.js +275 -53
  12. package/lib/types/capabilities.js +25 -36
  13. package/lib/types/manifest.d.ts +24 -0
  14. package/lib/types/manifest.js +51 -0
  15. package/lib/types/profile.d.ts +1 -0
  16. package/lib/types/profile.js +14 -3
  17. package/package.json +529 -577
  18. package/patches/approval-allow-policy.patch +3 -3
  19. package/patches/atomic-write-zombie-lock-holder.patch +1 -1
  20. package/patches/bootstrap-exempt-names.patch +6 -6
  21. package/patches/composer-popover-boundaries.patch +41 -283
  22. package/patches/image-offload-hoist-replay.patch +34 -31
  23. package/patches/input-trigger-source-label.patch +63 -0
  24. package/patches/legacy-code-preset.patch +5 -5
  25. package/patches/llm-pi-ai-transport-truncation.patch +4 -4
  26. package/patches/mobile-journal-generation.patch +2 -2
  27. package/patches/office-preview-stable-load.patch +1 -1
  28. package/patches/officecli-deliverables.patch +2 -2
  29. package/patches/ptc-mcp-schema-types.patch +3 -3
  30. package/patches/responses-reasoning-status.patch +197 -48
  31. package/patches/session-controller-image-downgrade-and-tool-visibility.patch +16 -14
  32. package/patches/session-export-chinese.patch +11 -11
  33. package/patches/session-format-legacy-restart.patch +1 -1
  34. package/patches/sidebar-right-tab-menu.patch +119 -0
  35. package/patches/state-dot-brand-blue.patch +2 -2
  36. package/patches/ui-settings-compact-phone.patch +2 -9
  37. package/patches/ui-sidebar-right-global-panel.patch +3 -3
  38. package/patches/workspace-hide-group-rooms.patch +38 -0
  39. package/patches/workspace-storage-restore.patch +21 -5
  40. package/patches/wsl-native-open.patch +8 -8
  41. package/lib/apply-e0aMC4B4.js +0 -601
  42. package/lib/types/standalone-capabilities.d.ts +0 -139
  43. package/lib/types/standalone-capabilities.js +0 -688
  44. package/lib/types/standalone-cli.d.ts +0 -17
  45. package/lib/types/standalone-cli.js +0 -913
  46. package/lib/types/standalone-profile.d.ts +0 -258
  47. package/lib/types/standalone-profile.js +0 -747
  48. package/lib/types/standalone-server.d.ts +0 -70
  49. package/lib/types/standalone-server.js +0 -158
  50. package/patches/browser-auth-mode.patch +0 -127
  51. package/patches/diagram-preview.patch +0 -562
  52. package/patches/dsh-resource-ref-chip.patch +0 -40
  53. package/patches/session-envelope-ignorable.patch +0 -63
  54. package/patches/session-log-trajectory-toolbar.patch +0 -352
  55. package/patches/ui-schedule-plaza-tab.patch +0 -217
  56. package/patches/web-runtime-compat.patch +0 -83
@@ -0,0 +1,1193 @@
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, join, 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/manifest.js
128
+ /**
129
+ * Derive the profile's override table from the distribution's own facts.
130
+ *
131
+ * The distribution records one truth per fact: the patch set names the official packages it
132
+ * patches, the runtime names the version its republished builds carry, and an edition names the
133
+ * capabilities a deployment omits. The override table npm and pnpm read is a projection of those
134
+ * three, never a fourth list: an entry that cannot be derived fails the build instead of being
135
+ * carried forward, which is what kept a stale `@deepseek-ai/dsh-client-ui-slots` pin alive long
136
+ * after the patch behind it had gone.
137
+ *
138
+ * @module manifest
139
+ */
140
+ /** npm scope every patched official package is republished under. */
141
+ const OFFICIAL_PREFIX = "@deepseek-ai/";
142
+ /** npm scope the distribution publishes its republished builds under. */
143
+ const REPUBLISHED_PREFIX = "@sparkelf/";
144
+ /** Independent profile metadata the app-boot preflight reads before importing plugins. */
145
+ const PROFILE_COMPATIBILITY_FILENAME = "compatibility.json";
146
+ function record(value, label) {
147
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be an object");
148
+ return value;
149
+ }
150
+ /** A declared value as text, or the fallback when the manifest holds something else. */
151
+ function text(value, fallback = "") {
152
+ return typeof value === "string" ? value : fallback;
153
+ }
154
+ function stringArray(value, label) {
155
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry === "")) throw new Error(label + " must be a non-empty string array");
156
+ return value;
157
+ }
158
+ function stringMap(value, label) {
159
+ const result = {};
160
+ for (const [name, spec] of Object.entries(record(value, label))) {
161
+ if (typeof spec !== "string" || spec === "") throw new Error(label + "." + name + " must be a non-empty string");
162
+ result[name] = spec;
163
+ }
164
+ return result;
165
+ }
166
+ /**
167
+ * The republished scope name for one official package.
168
+ *
169
+ * @param official - an `@deepseek-ai/dsh-*` name.
170
+ * @returns the `@sparkelf/dsh-*` name the distribution publishes it as.
171
+ */
172
+ function republishedName(official) {
173
+ if (!official.startsWith(OFFICIAL_PREFIX)) throw new Error(official + " is not an official package name");
174
+ return REPUBLISHED_PREFIX + official.slice(13);
175
+ }
176
+ /**
177
+ * Derive the redirect table from the patch set.
178
+ *
179
+ * Every `dsh-source` entry republishes the packages its payload modifies, because a registry
180
+ * installation has no source tree to patch. An entry that changes only types sets
181
+ * `target.republish: false` and must say why; anything else would look like a redirect that
182
+ * silently never happens.
183
+ *
184
+ * @param entries - the distribution's patch entries.
185
+ * @param runtimeVersion - exact version the republished builds carry.
186
+ * @returns official name to `npm:` alias spec.
187
+ */
188
+ function deriveRedirects(entries, runtimeVersion) {
189
+ const redirects = {};
190
+ const ids = {};
191
+ for (const entry of entries) {
192
+ if (entry.target.kind !== "dsh-source") continue;
193
+ const packages = entry.target.packages ?? [];
194
+ if (packages.length === 0) throw new Error("patch entry " + entry.id + " declares no target packages");
195
+ if (!(entry.target.republish !== false)) {
196
+ if (entry.target.reason === void 0 || entry.target.reason.trim() === "") throw new Error("patch entry " + entry.id + " sets republish:false without a reason");
197
+ continue;
198
+ }
199
+ for (const official of packages) {
200
+ const spec = "npm:" + republishedName(official) + "@" + runtimeVersion;
201
+ if (redirects[official] !== void 0 && redirects[official] !== spec) throw new Error("patch entries " + (ids[official] ?? "?") + " and " + entry.id + " redirect " + official + " to different targets");
202
+ redirects[official] = spec;
203
+ ids[official] = entry.id;
204
+ }
205
+ }
206
+ if (Object.keys(redirects).length === 0) throw new Error("the patch set declares no republishable target");
207
+ return {
208
+ redirects,
209
+ ids
210
+ };
211
+ }
212
+ /** Read and validate the facts one installed distribution declares. */
213
+ function readDistributionFacts(directory) {
214
+ const manifest = record(JSON.parse(readFileSync(join(directory, "package.json"), "utf8")), "distribution manifest");
215
+ const plus = record(manifest.dshPlus, "dshPlus");
216
+ const profile = record(plus.profile, "dshPlus.profile");
217
+ if (profile.overrides !== void 0) throw new Error("dshPlus.profile.overrides is retired; overrides are derived from dshPlus.patchSet");
218
+ const runtimeVersion = text(record(plus.runtime, "dshPlus.runtime").version);
219
+ if (valid(runtimeVersion) === null) throw new Error("dshPlus.runtime.version must be an exact version, got: " + runtimeVersion);
220
+ const omission = record(plus.omission, "dshPlus.omission");
221
+ const omissionPackage = text(omission.package);
222
+ const omissionVersion = text(omission.version);
223
+ if (!omissionPackage.startsWith("@sparkelf/") || valid(omissionVersion) === null) throw new Error("dshPlus.omission must name an @sparkelf package and an exact version");
224
+ if (validRange(text(record(plus.compatibility, "dshPlus.compatibility").dsh)) === null) throw new Error("dshPlus.compatibility.dsh must be a semver range");
225
+ const rawEntries = record(plus.patchSet, "dshPlus.patchSet").entries;
226
+ if (!Array.isArray(rawEntries) || rawEntries.length === 0) throw new Error("dshPlus.patchSet.entries must be a non-empty array");
227
+ const { redirects, ids } = deriveRedirects(rawEntries.map((value, index) => {
228
+ const entry = record(value, "patchSet.entries[" + String(index) + "]");
229
+ const target = record(entry.target, "patchSet.entries[" + String(index) + "].target");
230
+ const targetFacts = { kind: text(target.kind) };
231
+ if (target.packages !== void 0) Object.assign(targetFacts, { packages: stringArray(target.packages, "target.packages") });
232
+ if (target.republish === false) Object.assign(targetFacts, { republish: false });
233
+ if (typeof target.reason === "string") Object.assign(targetFacts, { reason: target.reason });
234
+ return {
235
+ id: text(entry.id),
236
+ target: targetFacts
237
+ };
238
+ }), runtimeVersion);
239
+ const dependencies = stringMap(profile.dependencies, "dshPlus.profile.dependencies");
240
+ const compatibilityExemptions = profile.compatibility === void 0 ? [] : stringArray(profile.compatibility, "dshPlus.profile.compatibility");
241
+ for (const entry of compatibilityExemptions) {
242
+ const separator = entry.lastIndexOf("@");
243
+ const name = entry.slice(0, separator);
244
+ const version = entry.slice(separator + 1);
245
+ if (separator <= 0 || valid(version) === null) throw new Error("dshPlus.profile.compatibility entry must be an exact package@version, got: " + entry);
246
+ if (dependencies[name] !== version) throw new Error("dshPlus.profile.compatibility names " + entry + ", which dshPlus.profile.dependencies does not pin");
247
+ }
248
+ const allowBuilds = {};
249
+ for (const [name, allowed] of Object.entries(record(profile.allowBuilds, "dshPlus.profile.allowBuilds"))) {
250
+ if (typeof allowed !== "boolean") throw new Error("dshPlus.profile.allowBuilds." + name + " must be a boolean");
251
+ allowBuilds[name] = allowed;
252
+ }
253
+ const editions = {};
254
+ const rawEditions = plus.editions === void 0 ? {} : record(plus.editions, "dshPlus.editions");
255
+ for (const [id, value] of Object.entries(rawEditions)) {
256
+ const edition = record(value, "dshPlus.editions." + id);
257
+ const rawPackages = edition.packages;
258
+ if (rawPackages === void 0) throw new Error("dshPlus.editions." + id + ".packages is required");
259
+ const names = Array.isArray(rawPackages) ? stringArray(rawPackages, "dshPlus.editions." + id + ".packages") : Object.keys(record(rawPackages, "dshPlus.editions." + id + ".packages"));
260
+ for (const name of names) if (dependencyKey(dependencies, name) === void 0) throw new Error("edition \"" + id + "\" installs " + name + ", which dshPlus.profile.dependencies does not pin");
261
+ const omit = stringArray(edition.omit ?? [], "dshPlus.editions." + id + ".omit");
262
+ for (const name of omit) if (dependencies[name] === void 0 && manifest.dependencies?.[name] === void 0) throw new Error("edition \"" + id + "\" omits " + name + ", which the distribution does not declare");
263
+ const excludePackages = stringArray(edition.excludePackages ?? [], "dshPlus.editions." + id + ".excludePackages");
264
+ for (const name of excludePackages) {
265
+ if (dependencies[name] === void 0 && !stringArray(edition.bundles ?? [], "x").includes(name)) throw new Error("edition \"" + id + "\" excludes " + name + ", which it does not install or mount");
266
+ if (omit.includes(name)) throw new Error("edition \"" + id + "\" both excludes and omits " + name);
267
+ for (const [other, spec] of Object.entries(dependencies)) if (/^npm:/u.test(spec) && spec.includes(name + "@")) throw new Error("edition \"" + id + "\" excludes " + name + " but " + other + " aliases it");
268
+ }
269
+ const bundles = stringArray(edition.bundles ?? [], "dshPlus.editions." + id + ".bundles");
270
+ for (const name of bundles) if (omit.includes(name)) throw new Error("edition \"" + id + "\" mounts " + name + " but also omits it");
271
+ editions[id] = {
272
+ label: text(edition.label, id),
273
+ profile: text(edition.profile, "plus"),
274
+ bundles,
275
+ packages: names,
276
+ omit,
277
+ excludePackages
278
+ };
279
+ }
280
+ return {
281
+ name: String(manifest.name),
282
+ version: String(manifest.version),
283
+ runtimeVersion,
284
+ omissionSpec: "npm:" + omissionPackage + "@" + omissionVersion,
285
+ bundles: stringArray(profile.bundles, "dshPlus.profile.bundles"),
286
+ dependencies,
287
+ compatibilityExemptions,
288
+ allowBuilds,
289
+ redirects,
290
+ redirectIds: ids,
291
+ editions
292
+ };
293
+ }
294
+ /**
295
+ * The dependency-table key that installs one package.
296
+ *
297
+ * A bundle published under a scope we own is installed through an alias: the official name a
298
+ * consumer imports (`dsh-better-sidebar`) is the key, and the spec names our build
299
+ * (`npm:@sparkelf/dsh-better-sidebar@…`). Editions name the real package, so the
300
+ * lookup has to follow the alias or it reports a reviewed package as unpinned.
301
+ *
302
+ * @param dependencies - the distribution's dependency table.
303
+ * @param name - package name an edition names.
304
+ * @returns the key that installs it, or undefined when the distribution does not carry it.
305
+ */
306
+ function dependencyKey(dependencies, name) {
307
+ if (dependencies[name] !== void 0) return name;
308
+ for (const [key, spec] of Object.entries(dependencies)) if (/^npm:(@[^/]+\/[^@]+)@/u.exec(spec)?.[1] === name) return key;
309
+ }
310
+ /**
311
+ * Project an edition into the profile npm and pnpm install.
312
+ *
313
+ * The distribution's reviewed order is the base; the edition names the bundle order and package
314
+ * set it installs and the capabilities it must not run. Versions always come from
315
+ * `profile.dependencies`, so an edition cannot pin a version the distribution did not review.
316
+ * No edition means the full distribution, which is what a launcher start without a selection
317
+ * materializes.
318
+ *
319
+ * @param facts - validated distribution facts.
320
+ * @param editionId - edition to project, or undefined for the full distribution.
321
+ * @returns the profile's dependencies, bundles, and override table.
322
+ */
323
+ function projectEdition(facts, editionId, extraExcludes = []) {
324
+ const edition = editionId === void 0 ? void 0 : facts.editions[editionId];
325
+ if (editionId !== void 0 && edition === void 0) throw new Error("unknown edition \"" + editionId + "\"; declared: " + (Object.keys(facts.editions).join(", ") || "(none)"));
326
+ const excludedNames = new Set([...edition?.excludePackages ?? [], ...extraExcludes]);
327
+ for (const name of excludedNames) if (!(facts.dependencies[name] !== void 0 || facts.bundles.includes(name))) throw new Error("exclude names " + name + ", which the distribution does not install or mount");
328
+ const omittedNames = new Set(edition?.omit ?? []);
329
+ const omitted = {};
330
+ for (const name of omittedNames) omitted[name] = facts.omissionSpec;
331
+ const dependencies = {};
332
+ const sharedOfficials = Object.keys(facts.dependencies).filter((name) => name.startsWith("@deepseek-ai/dsh"));
333
+ const packageNames = edition === void 0 ? [...new Set([...Object.keys(facts.dependencies), ...sharedOfficials])] : [...new Set([...edition.packages, ...sharedOfficials])];
334
+ for (const name of packageNames) {
335
+ if (omittedNames.has(name) || excludedNames.has(name)) continue;
336
+ const key = dependencyKey(facts.dependencies, name) ?? name;
337
+ const spec = facts.dependencies[key];
338
+ if (spec === void 0) throw new Error(name + " is not a reviewed package");
339
+ dependencies[key] = spec;
340
+ }
341
+ for (const [name, spec] of Object.entries(facts.redirects)) {
342
+ if (omittedNames.has(name) || excludedNames.has(name)) continue;
343
+ dependencies[name] = spec;
344
+ }
345
+ const bundles = (edition === void 0 ? [...facts.bundles] : [...new Set(edition.bundles)]).filter((name) => !excludedNames.has(name));
346
+ for (const name of bundles) if (!facts.bundles.includes(name) && !(edition?.bundles ?? []).includes(name)) throw new Error("edition \"" + String(editionId) + "\" mounts bundle " + name + ", which the distribution does not declare");
347
+ const overrides = {};
348
+ for (const [name, spec] of Object.entries(facts.redirects)) {
349
+ if (omittedNames.has(name) || excludedNames.has(name)) continue;
350
+ overrides[name] = spec;
351
+ }
352
+ overrides["@deepseek-ai/dsh"] = facts.runtimeVersion;
353
+ Object.assign(overrides, omitted);
354
+ return {
355
+ profileName: edition?.profile ?? "plus",
356
+ dependencies,
357
+ bundles,
358
+ overrides,
359
+ allowBuilds: facts.allowBuilds,
360
+ omittedPackages: omitted
361
+ };
362
+ }
363
+ /**
364
+ * Assert every redirect target is served by a registry.
365
+ *
366
+ * A redirect names a published build; one that names a version the registry does not serve
367
+ * installs nothing at all, and the failure surfaces as a resolver error that reads like a
368
+ * packaging defect rather than a release that never happened.
369
+ *
370
+ * @param redirects - official name to `npm:` alias spec.
371
+ * @param registry - npm registry base URL.
372
+ * @returns nothing; throws on the first unavailable target.
373
+ */
374
+ async function assertRedirectsPublished(redirects, registry = "https://registry.npmjs.org") {
375
+ for (const spec of Object.values(redirects)) {
376
+ const match = /^npm:(@[^/]+\/[^@]+)@(.+)$/u.exec(spec);
377
+ if (match === null) throw new Error("redirect " + spec + " is not an npm alias");
378
+ const [, name, version] = match;
379
+ if (name === void 0 || version === void 0) throw new Error("redirect " + spec + " is not an npm alias");
380
+ if (!(await fetch(registry.replace(/\/$/u, "") + "/" + name.replace("/", "%2f") + "/" + version)).ok) throw new Error("redirect target " + name + "@" + version + " is not served by " + registry);
381
+ }
382
+ }
383
+ /**
384
+ * Record the distribution's exact-version grants in the profile's compatibility file.
385
+ *
386
+ * The file is the app-boot preflight's own grant mechanism: a missing or unreadable file
387
+ * authorizes nothing, and every other key belongs to the deployment. Writing merges the
388
+ * distribution's grants into the existing object rather than replacing it, so a grant a
389
+ * user or image added for another plugin survives a `dsh-plus install`/`start`.
390
+ *
391
+ * @param directory - profile directory that receives the file.
392
+ * @param exemptions - exact `package@version` grants the distribution admits.
393
+ * @param runtimeVersion - exact runtime each grant names.
394
+ */
395
+ function writeProfileCompatibility(directory, exemptions, runtimeVersion) {
396
+ mkdirSync(directory, { recursive: true });
397
+ const path = join(directory, PROFILE_COMPATIBILITY_FILENAME);
398
+ let current = {};
399
+ try {
400
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
401
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) current = parsed;
402
+ } catch {}
403
+ for (const entry of exemptions) {
404
+ const versions = Array.isArray(current[entry]) ? current[entry].filter((version) => typeof version === "string") : [];
405
+ current[entry] = [...new Set([...versions, runtimeVersion])];
406
+ }
407
+ writeFileSync(path, JSON.stringify(current, null, 2) + "\n");
408
+ }
409
+ /**
410
+ * Write the profile manifest and the pnpm workspace the install reads.
411
+ *
412
+ * npm reads `overrides` from the root manifest and pnpm reads them from the workspace file, so
413
+ * both are written from the same projection. Resolver settings a container needs (store location,
414
+ * supported architectures, release-age window) belong to the caller and are appended to the
415
+ * workspace file afterwards.
416
+ *
417
+ * @param directory - profile directory to write into.
418
+ * @param facts - validated distribution facts.
419
+ * @param editionId - edition to project.
420
+ * @param extraExcludes - packages the caller drops on top of the edition's own exclusions.
421
+ * @returns the projection that was written.
422
+ */
423
+ function writeProfileProjection(directory, facts, editionId, extraExcludes = []) {
424
+ const projection = projectEdition(facts, editionId, extraExcludes);
425
+ mkdirSync(directory, { recursive: true });
426
+ const dependencies = {
427
+ "@sparkelf/dsh-plus": facts.version,
428
+ "@deepseek-ai/dsh": facts.runtimeVersion,
429
+ ...projection.dependencies
430
+ };
431
+ writeFileSync(join(directory, "package.json"), JSON.stringify({
432
+ name: "dsh-profile-" + projection.profileName,
433
+ private: true,
434
+ type: "module",
435
+ dependencies,
436
+ dsh: { profile: {
437
+ bundles: projection.bundles,
438
+ patchReload: "live"
439
+ } }
440
+ }, null, 2) + "\n");
441
+ const workspace = [
442
+ "packages:",
443
+ " - .",
444
+ "nodeLinker: hoisted",
445
+ "autoInstallPeers: false",
446
+ "",
447
+ "overrides:",
448
+ ...Object.keys(projection.overrides).sort().map((name) => " " + JSON.stringify(name) + ": " + (projection.overrides[name] ?? "")),
449
+ "",
450
+ "allowBuilds:",
451
+ ...Object.keys(projection.allowBuilds).sort().map((name) => " " + JSON.stringify(name) + ": " + String(projection.allowBuilds[name])),
452
+ ""
453
+ ];
454
+ writeFileSync(join(directory, "pnpm-workspace.yaml"), workspace.join("\n"));
455
+ writeProfileCompatibility(directory, facts.compatibilityExemptions, facts.runtimeVersion);
456
+ return projection;
457
+ }
458
+ //#endregion
459
+ //#region lib/types/apply.js
460
+ /** Materialize the Plus distribution's independent patch packages without Desktop. */
461
+ const FORMAT_VERSION = 1;
462
+ function isSelectedNpmPatch(patch) {
463
+ return patch.target.kind === "npm";
464
+ }
465
+ function readJsonObject(path, label) {
466
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
467
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(label + " must be a JSON object");
468
+ return parsed;
469
+ }
470
+ function requireObject(value, label) {
471
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be an object");
472
+ return value;
473
+ }
474
+ function requireString(value, label) {
475
+ if (typeof value !== "string" || value === "") throw new Error(label + " must be a non-empty string");
476
+ return value;
477
+ }
478
+ function requireRange(value, label) {
479
+ const range = requireString(value, label);
480
+ if (validRange(range) === null) throw new Error(label + " is not a semantic-version range: " + range);
481
+ return range;
482
+ }
483
+ function requireVersion(value, label) {
484
+ const version = requireString(value, label);
485
+ if (valid(version) === null) throw new Error(label + " is not a semantic version: " + version);
486
+ return version;
487
+ }
488
+ function requireStringArray(value, label) {
489
+ if (!Array.isArray(value) || value.length === 0) throw new Error(label + " must be a non-empty array");
490
+ const strings = value.map((entry, index) => requireString(entry, label + "[" + String(index) + "]"));
491
+ if (new Set(strings).size !== strings.length) throw new Error(label + " must not contain duplicates");
492
+ return strings;
493
+ }
494
+ /**
495
+ * Resolve one installed package's manifest directory.
496
+ *
497
+ * `require.resolve(name + '/package.json')` respects the package's `exports`
498
+ * map, so a dependency that publishes only `"."` — `@sparkelf/dsh-quant`
499
+ * 0.91.0-sparkelf.13 among the `personal` edition's packages — fails to
500
+ * resolve even though the package is installed. Reading a manifest is not a
501
+ * public-export lookup, so resolve the package entry and walk up to the
502
+ * manifest that names it.
503
+ * @param distributionDirectory - directory whose resolution anchors the lookup.
504
+ * @param packageName - dependency name to locate.
505
+ * @returns path of the `package.json` that declares `packageName`.
506
+ */
507
+ function resolvePackageManifest(distributionDirectory, packageName) {
508
+ const requireFromDistribution = createRequire(resolve(distributionDirectory, "package.json"));
509
+ try {
510
+ return requireFromDistribution.resolve(packageName + "/package.json");
511
+ } catch {}
512
+ let directory = dirname(requireFromDistribution.resolve(packageName));
513
+ for (;;) {
514
+ const candidate = resolve(directory, "package.json");
515
+ if (existsSync(candidate)) {
516
+ if (JSON.parse(readFileSync(candidate, "utf8")).name === packageName) return candidate;
517
+ }
518
+ const parent = dirname(directory);
519
+ if (parent === directory) throw new Error(packageName + " is installed but no package.json naming it was found");
520
+ directory = parent;
521
+ }
522
+ }
523
+ function resolveInstalledPackage(distributionDirectory, packageName) {
524
+ const manifestPath = resolvePackageManifest(distributionDirectory, packageName);
525
+ const manifest = readJsonObject(manifestPath, packageName + " manifest");
526
+ return {
527
+ name: packageName,
528
+ version: requireVersion(manifest.version, packageName + " version"),
529
+ directory: dirname(manifestPath),
530
+ manifest
531
+ };
532
+ }
533
+ function resolvePatchFile(packageDirectory, declared) {
534
+ const absoluteFile = resolve(packageDirectory, declared);
535
+ const local = relative(packageDirectory, absoluteFile);
536
+ if (isAbsolute(local) || local === ".." || local.startsWith("../")) throw new Error("patch file must stay inside its patch package: " + declared);
537
+ if (!existsSync(absoluteFile)) throw new Error("patch file does not exist: " + absoluteFile);
538
+ return {
539
+ relativeFile: local.replaceAll("\\", "/"),
540
+ absoluteFile
541
+ };
542
+ }
543
+ function parseVariant(value, index, patchPackage) {
544
+ const label = patchPackage.name + " dshPatch.variants[" + String(index) + "]";
545
+ const variant = requireObject(value, label);
546
+ const target = requireObject(variant.target, label + ".target");
547
+ const kind = requireString(target.kind, label + ".target.kind");
548
+ const common = {
549
+ id: requireString(variant.id, label + ".id"),
550
+ dsh: requireRange(variant.dsh, label + ".dsh"),
551
+ file: requireString(variant.file, label + ".file"),
552
+ patchPackage
553
+ };
554
+ if (kind === "npm") return {
555
+ ...common,
556
+ target: {
557
+ kind,
558
+ name: requireString(target.name, label + ".target.name"),
559
+ range: requireRange(target.range, label + ".target.range")
560
+ }
561
+ };
562
+ if (kind === "dsh-source") return {
563
+ ...common,
564
+ target: {
565
+ kind,
566
+ baseRevision: requireString(target.baseRevision, label + ".target.baseRevision")
567
+ }
568
+ };
569
+ throw new Error("unsupported patch target kind: " + kind);
570
+ }
571
+ function git(root, args, acceptFailure = false) {
572
+ const result = spawnSync("git", args, {
573
+ cwd: root,
574
+ encoding: "utf8"
575
+ });
576
+ if (result.status === 0) return result.stdout.trim();
577
+ if (acceptFailure) return void 0;
578
+ const detail = result.stderr.trim();
579
+ throw new Error("git " + args.join(" ") + " failed" + (detail === "" ? "" : ": " + detail));
580
+ }
581
+ function sourcePatchState(root, file) {
582
+ if (git(root, [
583
+ "apply",
584
+ "--check",
585
+ file
586
+ ], true) !== void 0) return "pending";
587
+ if (git(root, [
588
+ "apply",
589
+ "--reverse",
590
+ "--check",
591
+ file
592
+ ], true) !== void 0) return "applied";
593
+ git(root, [
594
+ "apply",
595
+ "--check",
596
+ file
597
+ ]);
598
+ throw new Error("unreachable");
599
+ }
600
+ /** 在隔离index中按真实顺序预演source patches,避免失败后污染official worktree。 */
601
+ function preflightSourcePatches(root, files) {
602
+ if (files.length === 0) return;
603
+ const directory = mkdtempSync(resolve(tmpdir(), "dsh-plus-source-patches-"));
604
+ const index = resolve(directory, "index");
605
+ const env = {
606
+ ...process.env,
607
+ GIT_INDEX_FILE: index
608
+ };
609
+ const run = (args) => {
610
+ const result = spawnSync("git", args, {
611
+ cwd: root,
612
+ encoding: "utf8",
613
+ env
614
+ });
615
+ if (result.status === 0) return;
616
+ const detail = result.stderr.trim();
617
+ throw new Error("git " + args.join(" ") + " failed" + (detail === "" ? "" : ": " + detail));
618
+ };
619
+ try {
620
+ run(["read-tree", "HEAD"]);
621
+ for (const file of files) run([
622
+ "apply",
623
+ "--cached",
624
+ "--3way",
625
+ file
626
+ ]);
627
+ } finally {
628
+ rmSync(directory, {
629
+ recursive: true,
630
+ force: true
631
+ });
632
+ }
633
+ }
634
+ function requireSourceBase(root, baseRevision) {
635
+ const checkoutRevision = requireString(git(root, ["rev-parse", "HEAD"]), "DSH checkout revision");
636
+ if (checkoutRevision !== baseRevision) throw new Error("DSH checkout must be exact official base " + baseRevision + ", found " + checkoutRevision);
637
+ return checkoutRevision;
638
+ }
639
+ /**
640
+ * Names of distribution dependencies that carry `dshPatch` variants.
641
+ *
642
+ * `patchPackageVariants()` resolves these names from the Plus install tree, so they must be
643
+ * packages this distribution actually depends on. The current manifest declares `dshPlus.patchSet`
644
+ * instead of a flat list: only entries whose target is an npm package name a `dshPatch` carrier
645
+ * (`dsh-source` entries name the source packages being patched, which are never Plus dependencies).
646
+ * An older tarball may still carry the flat `dshPlus.patchPackages` list, which wins when present.
647
+ *
648
+ * @param plus - Parsed `dshPlus` block of the distribution manifest.
649
+ * @returns Patch-carrier package names; empty when the distribution ships only source patches.
650
+ */
651
+ function resolvePatchPackageNames(plus) {
652
+ const declared = plus.patchPackages;
653
+ if (declared !== void 0) {
654
+ const names = requireStringArray(declared, "dshPlus.patchPackages");
655
+ if (names.length > 0) return names;
656
+ }
657
+ const entries = requireObject(plus.patchSet, "dshPlus.patchSet").entries;
658
+ if (!Array.isArray(entries)) throw new Error("dshPlus.patchSet.entries must be an array");
659
+ const names = /* @__PURE__ */ new Set();
660
+ for (const [index, value] of entries.entries()) {
661
+ const target = requireObject(requireObject(value, "dshPlus.patchSet.entries[" + String(index) + "]").target, "dshPlus.patchSet.entries[" + String(index) + "].target");
662
+ if (target.kind !== "npm") continue;
663
+ names.add(requireString(target.name, "dshPlus.patchSet.entries[" + String(index) + "].target.name"));
664
+ }
665
+ return [...names].sort();
666
+ }
667
+ function patchPackageVariants(distributionDirectory, names) {
668
+ const variants = [];
669
+ for (const name of names) {
670
+ const patchPackage = resolveInstalledPackage(distributionDirectory, name);
671
+ const declaration = requireObject(patchPackage.manifest.dshPatch, name + " dshPatch");
672
+ if (declaration.formatVersion !== FORMAT_VERSION) throw new Error("unsupported dshPatch formatVersion in " + name + ": " + String(declaration.formatVersion));
673
+ if (!Array.isArray(declaration.variants) || declaration.variants.length === 0) throw new Error(name + " dshPatch.variants must be a non-empty array");
674
+ for (const [index, value] of declaration.variants.entries()) variants.push(parseVariant(value, index, patchPackage));
675
+ }
676
+ return variants;
677
+ }
678
+ /**
679
+ * Build patch variants from the distribution's `dshPlus.patchSet`.
680
+ *
681
+ * The patch files live inside the Plus package (`./patches/*.patch`), so every variant points at
682
+ * the distribution itself as its patch package: `resolvePatchFile()` then resolves the declared
683
+ * path inside the tarball, and `materializePatchFiles()` copies it into the profile's stable
684
+ * patch directory. Unlike the retired `dshPatch` carrier packages, the source packages named in
685
+ * `target.packages` are never resolved from the Plus tree -- they are the packages being patched.
686
+ *
687
+ * @param distribution - Installed Plus distribution package.
688
+ */
689
+ function patchSetVariants(distribution) {
690
+ const patchSet = readPatchSet(distribution.directory, distribution.manifest);
691
+ return [...patchSet.entries, ...patchSet.thirdPartyPatches].map((entry) => ({
692
+ id: entry.id,
693
+ dsh: entry.dsh,
694
+ file: entry.file,
695
+ patchPackage: distribution,
696
+ target: entry.target.kind === "npm" ? {
697
+ kind: "npm",
698
+ name: entry.target.name,
699
+ range: entry.target.range
700
+ } : {
701
+ kind: "dsh-source",
702
+ baseRevision: entry.target.baseRevision
703
+ }
704
+ }));
705
+ }
706
+ function prepareSelection(distributionDirectory, profileDirectory, dshRoot) {
707
+ const distributionManifest = readJsonObject(resolve(distributionDirectory, "package.json"), "Plus distribution manifest");
708
+ const distributionName = requireString(distributionManifest.name, "Plus distribution name");
709
+ const distributionVersion = requireVersion(distributionManifest.version, "Plus distribution version");
710
+ const plus = requireObject(distributionManifest.dshPlus, "Plus distribution dshPlus");
711
+ if (plus.formatVersion !== FORMAT_VERSION) throw new Error("unsupported dshPlus formatVersion: " + String(plus.formatVersion));
712
+ const dshRange = requireRange(requireObject(plus.compatibility, "dshPlus.compatibility").dsh, "dshPlus.compatibility.dsh");
713
+ const baseRevision = requireString(requireObject(plus.sourceBase, "dshPlus.sourceBase").revision, "dshPlus.sourceBase.revision");
714
+ const profile = requireObject(plus.profile, "dshPlus.profile");
715
+ const bundles = requireStringArray(profile.bundles, "dshPlus.profile.bundles");
716
+ const rawProfileDependencySpecs = requireObject(profile.dependencies, "dshPlus.profile.dependencies");
717
+ const profileDependencySpecs = {};
718
+ for (const [name, spec] of Object.entries(rawProfileDependencySpecs)) profileDependencySpecs[name] = requireString(spec, "dshPlus.profile.dependencies." + name);
719
+ const rawAllowBuilds = requireObject(profile.allowBuilds, "dshPlus.profile.allowBuilds");
720
+ const allowBuilds = {};
721
+ for (const [name, allowed] of Object.entries(rawAllowBuilds)) {
722
+ if (typeof allowed !== "boolean") throw new Error("dshPlus.profile.allowBuilds." + name + " must be a boolean");
723
+ allowBuilds[name] = allowed;
724
+ }
725
+ const compatibilityExemptions = profile.compatibility === void 0 ? [] : requireStringArray(profile.compatibility, "dshPlus.profile.compatibility");
726
+ for (const entry of compatibilityExemptions) {
727
+ const separator = entry.lastIndexOf("@");
728
+ const name = entry.slice(0, separator);
729
+ const version = entry.slice(separator + 1);
730
+ if (separator <= 0 || valid(version) === null) throw new Error("dshPlus.profile.compatibility entry must be an exact package@version, got: " + entry);
731
+ if (profileDependencySpecs[name] !== version) throw new Error("dshPlus.profile.compatibility names " + entry + ", which dshPlus.profile.dependencies does not pin");
732
+ }
733
+ const patchPackageNames = resolvePatchPackageNames(plus);
734
+ const dependencies = requireObject(distributionManifest.dependencies, "Plus distribution dependencies");
735
+ const dshVersion = requireVersion(readJsonObject(resolve(dshRoot, "package.json"), "DSH source manifest").version, "DSH source version");
736
+ if (!satisfies(dshVersion, dshRange, { includePrerelease: true })) throw new Error(distributionName + "@" + distributionVersion + " requires DSH " + dshRange + ", found " + dshVersion);
737
+ const checkoutRevision = requireSourceBase(dshRoot, baseRevision);
738
+ const variants = plus.patchPackages === void 0 ? patchSetVariants({
739
+ name: distributionName,
740
+ version: distributionVersion,
741
+ directory: distributionDirectory,
742
+ manifest: distributionManifest
743
+ }) : patchPackageVariants(distributionDirectory, patchPackageNames);
744
+ const groups = /* @__PURE__ */ new Map();
745
+ for (const variant of variants) {
746
+ const entries = groups.get(variant.id) ?? [];
747
+ entries.push(variant);
748
+ groups.set(variant.id, entries);
749
+ }
750
+ const sourceStates = /* @__PURE__ */ new Map();
751
+ const orderedGroups = [...groups].sort(([left], [right]) => left.localeCompare(right));
752
+ for (const [, variants] of orderedGroups) for (const variant of variants) {
753
+ if (variant.target.kind !== "dsh-source" || variant.target.baseRevision !== baseRevision || !satisfies(dshVersion, variant.dsh, { includePrerelease: true })) continue;
754
+ const file = resolvePatchFile(variant.patchPackage.directory, variant.file);
755
+ sourceStates.set(file.absoluteFile, sourcePatchState(dshRoot, file.absoluteFile));
756
+ }
757
+ preflightSourcePatches(dshRoot, [...sourceStates].flatMap(([file, state]) => state === "pending" ? [file] : []));
758
+ writeProfileRequirements(profileDirectory, profileDependencySpecs, allowBuilds);
759
+ writeProfileCompatibility(profileDirectory, compatibilityExemptions, dshVersion);
760
+ runPnpm(profileDirectory, ["install", "--no-frozen-lockfile"], "pnpm install Plus profile dependencies");
761
+ const profileDependencies = Object.keys(profileDependencySpecs).sort().map((name) => {
762
+ return {
763
+ name,
764
+ version: resolveInstalledPackage(profileDirectory, name).version
765
+ };
766
+ });
767
+ const runtimePackages = [...Object.keys(dependencies).filter((name) => !patchPackageNames.includes(name)).sort().map((name) => {
768
+ return {
769
+ name,
770
+ version: resolveInstalledPackage(distributionDirectory, name).version
771
+ };
772
+ }), ...profileDependencies].sort((left, right) => left.name.localeCompare(right.name));
773
+ const selected = [];
774
+ for (const [id, variants] of orderedGroups) {
775
+ const candidates = variants.flatMap((variant) => {
776
+ if (!satisfies(dshVersion, variant.dsh, { includePrerelease: true })) return [];
777
+ const file = resolvePatchFile(variant.patchPackage.directory, variant.file);
778
+ if (variant.target.kind === "dsh-source") {
779
+ if (variant.target.baseRevision !== baseRevision) return [];
780
+ return [{
781
+ id,
782
+ patchPackage: {
783
+ name: variant.patchPackage.name,
784
+ version: variant.patchPackage.version
785
+ },
786
+ file: file.relativeFile,
787
+ absoluteFile: file.absoluteFile,
788
+ target: {
789
+ kind: "dsh-source",
790
+ baseRevision
791
+ },
792
+ alreadyApplied: sourceStates.get(file.absoluteFile) === "applied"
793
+ }];
794
+ }
795
+ const targetVersion = resolveInstalledPackage(variant.target.name in profileDependencySpecs ? profileDirectory : distributionDirectory, variant.target.name).version;
796
+ if (!satisfies(targetVersion, variant.target.range, { includePrerelease: true })) return [];
797
+ return [{
798
+ id,
799
+ patchPackage: {
800
+ name: variant.patchPackage.name,
801
+ version: variant.patchPackage.version
802
+ },
803
+ file: file.relativeFile,
804
+ absoluteFile: file.absoluteFile,
805
+ target: {
806
+ kind: "npm",
807
+ name: variant.target.name,
808
+ version: targetVersion
809
+ }
810
+ }];
811
+ });
812
+ const [candidate] = candidates;
813
+ if (candidate === void 0) throw new Error("no compatible patch variant for " + id + " on DSH " + dshVersion);
814
+ if (candidates.length > 1) throw new Error("multiple compatible patch variants for " + id + " on DSH " + dshVersion);
815
+ selected.push(candidate);
816
+ }
817
+ const lockPatches = selected.map((patch) => {
818
+ if ("alreadyApplied" in patch) {
819
+ const { absoluteFile: _absoluteFile, alreadyApplied: _alreadyApplied, ...locked } = patch;
820
+ return locked;
821
+ }
822
+ const { absoluteFile: _absoluteFile, ...locked } = patch;
823
+ return locked;
824
+ });
825
+ return {
826
+ patches: selected,
827
+ bundles,
828
+ runtimePackages,
829
+ profileDependencies,
830
+ allowBuilds,
831
+ lock: {
832
+ formatVersion: FORMAT_VERSION,
833
+ distribution: {
834
+ name: distributionName,
835
+ version: distributionVersion
836
+ },
837
+ dsh: {
838
+ version: dshVersion,
839
+ baseRevision,
840
+ checkoutRevision
841
+ },
842
+ runtimePackages,
843
+ patches: lockPatches
844
+ }
845
+ };
846
+ }
847
+ /** 保留每个独立payload,并为同一npm目标生成pnpm可消费的唯一组合patch。 */
848
+ function materializePatchFiles(profileDirectory, patches) {
849
+ const root = resolve(profileDirectory, ".dsh-plus", "patches");
850
+ rmSync(root, {
851
+ recursive: true,
852
+ force: true
853
+ });
854
+ const stablePatches = patches.map((patch) => {
855
+ const destination = resolve(root, patch.patchPackage.name, patch.patchPackage.version, patch.file);
856
+ mkdirSync(dirname(destination), { recursive: true });
857
+ copyFileSync(patch.absoluteFile, destination);
858
+ return {
859
+ ...patch,
860
+ absoluteFile: destination
861
+ };
862
+ });
863
+ const npmGroups = /* @__PURE__ */ new Map();
864
+ for (const patch of stablePatches) {
865
+ if (!isSelectedNpmPatch(patch)) continue;
866
+ const key = patch.target.name + "@" + patch.target.version;
867
+ const group = npmGroups.get(key);
868
+ if (group === void 0) npmGroups.set(key, [patch]);
869
+ else group.push(patch);
870
+ }
871
+ const npmPatchFiles = /* @__PURE__ */ new Map();
872
+ for (const [key, group] of npmGroups) {
873
+ const first = group[0];
874
+ if (group.length === 1) {
875
+ npmPatchFiles.set(key, first.absoluteFile);
876
+ continue;
877
+ }
878
+ const members = group.map((patch) => encodeURIComponent(patch.id + "@" + patch.patchPackage.version)).join("+");
879
+ const destination = resolve(root, "combined", encodeURIComponent(key), members + ".patch");
880
+ mkdirSync(dirname(destination), { recursive: true });
881
+ writeFileSync(destination, group.map((patch) => {
882
+ const content = readFileSync(patch.absoluteFile, "utf8");
883
+ return content.endsWith("\n") ? content : content + "\n";
884
+ }).join(""));
885
+ npmPatchFiles.set(key, destination);
886
+ }
887
+ return {
888
+ patches: stablePatches,
889
+ npmPatchFiles
890
+ };
891
+ }
892
+ function profilePatchConfiguration(profileDirectory, npmPatchFiles) {
893
+ const document = parseDocument(readFileSync(resolve(profileDirectory, "pnpm-workspace.yaml"), "utf8"));
894
+ const [documentError] = document.errors;
895
+ if (documentError !== void 0) throw new Error("Plus profile workspace is not valid YAML", { cause: documentError });
896
+ let changed = false;
897
+ const desiredKeys = new Set(npmPatchFiles.keys());
898
+ const workspace = requireObject(document.toJS(), "Plus profile workspace");
899
+ const configured = workspace.patchedDependencies === void 0 ? {} : requireObject(workspace.patchedDependencies, "Plus profile patchedDependencies");
900
+ for (const [key, value] of Object.entries(configured)) if (typeof value === "string" && value.startsWith(".dsh-plus/patches/") && !desiredKeys.has(key)) {
901
+ document.deleteIn(["patchedDependencies", key]);
902
+ changed = true;
903
+ }
904
+ for (const [key, file] of npmPatchFiles) {
905
+ const value = relative(profileDirectory, file).replaceAll("\\", "/");
906
+ const current = document.getIn(["patchedDependencies", key]);
907
+ 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");
908
+ if (current === value) continue;
909
+ document.setIn(["patchedDependencies", key], value);
910
+ changed = true;
911
+ }
912
+ return {
913
+ text: String(document),
914
+ changed
915
+ };
916
+ }
917
+ /**
918
+ * Profile-local pnpm hook that keeps the CDN-only xlsx dependency installable.
919
+ *
920
+ * `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` declares `xlsx` as
921
+ * `https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz`. SheetJS stopped publishing to npm
922
+ * after 0.18.5, so no registry mirror carries 0.20.3, and the build network cannot reach that
923
+ * CDN (measured 2026-11-06: every request times out). The image vendors the tarball at
924
+ * /opt/dsh-vendor; this hook rewrites the spec wherever it appears so a cold profile install
925
+ * never requests the CDN.
926
+ *
927
+ * Written into the profile root rather than a template: the Plus bundle has no profile
928
+ * template directory, the profile manifest and pnpm-workspace.yaml are generated here.
929
+ */
930
+ const PROFILE_PNPMFILE = `// Generated by @sparkelf/dsh-plus -- do not edit; rewritten on every apply.
931
+ const VENDORED_XLSX = '/opt/dsh-vendor/xlsx-0.20.3.tgz'
932
+ const CDN_XLSX = /^https?:\\/\\/cdn\\.sheetjs\\.com\\//
933
+ const FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']
934
+
935
+ module.exports = {
936
+ hooks: {
937
+ readPackage(pkg) {
938
+ for (const field of FIELDS) {
939
+ const deps = pkg && pkg[field]
940
+ if (deps && typeof deps.xlsx === 'string' && CDN_XLSX.test(deps.xlsx)) {
941
+ deps.xlsx = 'file:' + VENDORED_XLSX
942
+ }
943
+ }
944
+ return pkg
945
+ },
946
+ },
947
+ }
948
+ `;
949
+ /** Write the profile pnpmfile when its content changed; returns whether it wrote. */
950
+ function writeProfilePnpmfile(profileDirectory) {
951
+ const path = resolve(profileDirectory, ".pnpmfile.cjs");
952
+ if ((existsSync(path) ? readFileSync(path, "utf8") : void 0) === PROFILE_PNPMFILE) return false;
953
+ writeFileSync(path, PROFILE_PNPMFILE);
954
+ console.log("profile pnpmfile: xlsx -> /opt/dsh-vendor/xlsx-0.20.3.tgz");
955
+ return true;
956
+ }
957
+ function writeProfileRequirements(profileDirectory, dependencySpecs, allowBuilds) {
958
+ const manifestPath = resolve(profileDirectory, "package.json");
959
+ const manifest = readJsonObject(manifestPath, "DSH profile manifest");
960
+ const dependencies = requireObject(manifest.dependencies, "DSH profile dependencies");
961
+ let manifestChanged = false;
962
+ for (const [name, spec] of Object.entries(dependencySpecs)) {
963
+ const current = dependencies[name];
964
+ if (current !== void 0 && current !== spec) throw new Error("profile dependency " + name + " is configured as " + JSON.stringify(current) + ", expected " + spec);
965
+ if (current === void 0) {
966
+ dependencies[name] = spec;
967
+ manifestChanged = true;
968
+ }
969
+ }
970
+ const workspacePath = resolve(profileDirectory, "pnpm-workspace.yaml");
971
+ const document = parseDocument(readFileSync(workspacePath, "utf8"));
972
+ const [documentError] = document.errors;
973
+ if (documentError !== void 0) throw new Error("Plus profile workspace is not valid YAML", { cause: documentError });
974
+ let workspaceChanged = false;
975
+ const autoInstallPeers = document.get("autoInstallPeers");
976
+ if (autoInstallPeers !== void 0 && autoInstallPeers !== false) throw new Error("profile autoInstallPeers must be false because official peers come from the selected DSH source");
977
+ if (autoInstallPeers === void 0) {
978
+ document.set("autoInstallPeers", false);
979
+ workspaceChanged = true;
980
+ }
981
+ const managedFileAsset = (value) => value.startsWith("file:") && (/[\\/]\.dsh[\\/]releases[\\/]plus[\\/].*[\\/]packages[\\/]/u.test(value) || /[\\/]\.dsh-plus[\\/]packages[\\/]/u.test(value));
982
+ const retiredOverrides = new Set([
983
+ "@huanlin/dsh-plugin-better-sidebar-plugin-office",
984
+ "@sparkelf/dsh-office-viewer-fonts",
985
+ "dsh-better-sidebar",
986
+ "dsh-video-preview"
987
+ ]);
988
+ const workspace = requireObject(document.toJS(), "Plus profile workspace");
989
+ const configuredOverrides = workspace.overrides === void 0 ? {} : requireObject(workspace.overrides, "Plus profile overrides");
990
+ for (const [name, value] of Object.entries(configuredOverrides)) if (retiredOverrides.has(name) || typeof value === "string" && managedFileAsset(value)) {
991
+ document.deleteIn(["overrides", name]);
992
+ workspaceChanged = true;
993
+ }
994
+ for (const [name, allowed] of Object.entries(allowBuilds)) {
995
+ const current = document.getIn(["allowBuilds", name]);
996
+ if (current !== void 0 && current !== allowed) throw new Error("profile allowBuilds." + name + " is configured as " + JSON.stringify(current) + ", expected " + String(allowed));
997
+ if (current === void 0) {
998
+ document.setIn(["allowBuilds", name], allowed);
999
+ workspaceChanged = true;
1000
+ }
1001
+ }
1002
+ if (manifestChanged) {
1003
+ manifest.dependencies = dependencies;
1004
+ writeFileSync(manifestPath, JSON.stringify(manifest, void 0, 2) + "\n");
1005
+ }
1006
+ if (workspaceChanged) writeFileSync(workspacePath, String(document));
1007
+ const pnpmfileChanged = writeProfilePnpmfile(profileDirectory);
1008
+ return manifestChanged || workspaceChanged || pnpmfileChanged;
1009
+ }
1010
+ function writeProfileComposition(profileDirectory, bundles, runtimePackages) {
1011
+ const path = resolve(profileDirectory, "package.json");
1012
+ const manifest = readJsonObject(path, "DSH profile manifest");
1013
+ const dependencies = requireObject(manifest.dependencies, "DSH profile dependencies");
1014
+ let changed = false;
1015
+ for (const runtimePackage of runtimePackages) {
1016
+ if (dependencies[runtimePackage.name] === void 0) {
1017
+ dependencies[runtimePackage.name] = runtimePackage.version;
1018
+ changed = true;
1019
+ continue;
1020
+ }
1021
+ const installed = resolveInstalledPackage(profileDirectory, runtimePackage.name);
1022
+ if (installed.version !== runtimePackage.version) throw new Error("profile dependency " + runtimePackage.name + " resolves to " + installed.version + ", but the Plus distribution requires " + runtimePackage.version);
1023
+ }
1024
+ const dsh = manifest.dsh === void 0 ? {} : requireObject(manifest.dsh, "DSH profile dsh");
1025
+ const profile = dsh.profile === void 0 ? {} : requireObject(dsh.profile, "DSH profile dsh.profile");
1026
+ if (JSON.stringify(profile.bundles) !== JSON.stringify(bundles)) changed = true;
1027
+ manifest.dependencies = dependencies;
1028
+ manifest.dsh = {
1029
+ ...dsh,
1030
+ profile: {
1031
+ ...profile,
1032
+ bundles: [...bundles]
1033
+ }
1034
+ };
1035
+ if (changed) writeFileSync(path, JSON.stringify(manifest, void 0, 2) + "\n");
1036
+ return changed;
1037
+ }
1038
+ function runPnpm(profileDirectory, args, label) {
1039
+ const result = spawnSync("pnpm", args, {
1040
+ cwd: profileDirectory,
1041
+ stdio: "inherit",
1042
+ shell: process.platform === "win32"
1043
+ });
1044
+ if (result.error !== void 0) throw result.error;
1045
+ if (result.status !== 0) throw new Error(label + " failed with exit code " + String(result.status));
1046
+ }
1047
+ function pendingSourcePatchFiles(patches) {
1048
+ return patches.flatMap((patch) => "alreadyApplied" in patch && !patch.alreadyApplied ? [patch.absoluteFile] : []);
1049
+ }
1050
+ function applySelectedPatches(profileDirectory, dshRoot, patches, profileChanged) {
1051
+ const materialized = materializePatchFiles(profileDirectory, patches);
1052
+ const workspacePath = resolve(profileDirectory, "pnpm-workspace.yaml");
1053
+ const workspace = profilePatchConfiguration(profileDirectory, materialized.npmPatchFiles);
1054
+ if (workspace.changed) writeFileSync(workspacePath, workspace.text);
1055
+ if (profileChanged || workspace.changed) runPnpm(profileDirectory, ["install", "--no-frozen-lockfile"], "pnpm install in Plus profile");
1056
+ const sourceFiles = pendingSourcePatchFiles(materialized.patches);
1057
+ if (sourceFiles.length > 0) git(dshRoot, ["update-index", "--refresh"], true);
1058
+ for (const file of sourceFiles) git(dshRoot, [
1059
+ "apply",
1060
+ "--3way",
1061
+ file
1062
+ ]);
1063
+ if (materialized.patches.some((patch) => patch.target.kind === "dsh-source")) {
1064
+ if (sourceFiles.length > 0) runPnpm(dshRoot, ["install", "--no-frozen-lockfile"], "pnpm install after source patches");
1065
+ runPnpm(dshRoot, ["run", "build:official"], "official DSH build after source patches");
1066
+ }
1067
+ }
1068
+ function officialPackageRoot(dshRoot) {
1069
+ return resolve(dshRoot, "apps", "cli");
1070
+ }
1071
+ /**
1072
+ * Parse pnpm's workspace roster into exact official package directories.
1073
+ * @param dshRoot - exact official DSH checkout root.
1074
+ * @param stdout - JSON emitted by `pnpm -r list --json --depth -1`.
1075
+ * @returns sorted official package names and directories inside the checkout.
1076
+ */
1077
+ function parseOfficialWorkspacePackages(dshRoot, stdout) {
1078
+ const parsed = JSON.parse(stdout);
1079
+ if (!Array.isArray(parsed)) throw new Error("pnpm workspace package list must be an array");
1080
+ const packages = /* @__PURE__ */ new Map();
1081
+ for (const [index, value] of parsed.entries()) {
1082
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("pnpm workspace package list[" + String(index) + "] must be an object");
1083
+ const entry = value;
1084
+ if (typeof entry.name !== "string" || !entry.name.startsWith("@deepseek-ai/")) continue;
1085
+ const localName = entry.name.slice(13);
1086
+ if (localName === "" || localName.includes("/")) throw new Error("unsupported official workspace package name: " + entry.name);
1087
+ if (typeof entry.path !== "string" || entry.path === "") throw new Error("pnpm workspace package " + entry.name + " has no path");
1088
+ const directory = resolve(dshRoot, entry.path);
1089
+ const local = relative(dshRoot, directory);
1090
+ if (isAbsolute(local) || local === ".." || local.startsWith("../")) throw new Error("official workspace package escapes DSH root: " + entry.name);
1091
+ const previous = packages.get(entry.name);
1092
+ if (previous !== void 0 && previous !== directory) throw new Error("duplicate official workspace package: " + entry.name);
1093
+ packages.set(entry.name, directory);
1094
+ }
1095
+ return [...packages].sort(([left], [right]) => left.localeCompare(right)).map(([name, directory]) => ({
1096
+ name,
1097
+ directory
1098
+ }));
1099
+ }
1100
+ function listOfficialWorkspacePackages(dshRoot) {
1101
+ const result = spawnSync("pnpm", [
1102
+ "-r",
1103
+ "list",
1104
+ "--json",
1105
+ "--depth",
1106
+ "-1"
1107
+ ], {
1108
+ cwd: dshRoot,
1109
+ encoding: "utf8",
1110
+ shell: process.platform === "win32"
1111
+ });
1112
+ if (result.error !== void 0) throw result.error;
1113
+ if (result.status !== 0) throw new Error("pnpm list official DSH workspace packages failed with exit code " + String(result.status));
1114
+ return parseOfficialWorkspacePackages(dshRoot, result.stdout);
1115
+ }
1116
+ /**
1117
+ * Build the profile's official scope from the CLI closure plus source workspaces.
1118
+ * @param profileDirectory - materialized Plus profile root.
1119
+ * @param cliScope - official packages already installed under the DSH CLI.
1120
+ * @param workspacePackages - additional official source workspaces required by external peers.
1121
+ */
1122
+ function materializeOfficialPackageScope(profileDirectory, cliScope, workspacePackages) {
1123
+ if (!existsSync(cliScope)) throw new Error("official DSH dependencies are missing under " + cliScope);
1124
+ const destination = resolve(profileDirectory, "node_modules", "@deepseek-ai");
1125
+ rmSync(destination, {
1126
+ recursive: true,
1127
+ force: true
1128
+ });
1129
+ mkdirSync(destination, { recursive: true });
1130
+ const linkType = process.platform === "win32" ? "junction" : "dir";
1131
+ for (const name of readdirSync(cliScope).sort()) symlinkSync(resolve(cliScope, name), resolve(destination, name), linkType);
1132
+ for (const entry of workspacePackages) {
1133
+ const target = resolve(destination, entry.name.slice(13));
1134
+ rmSync(target, {
1135
+ recursive: true,
1136
+ force: true
1137
+ });
1138
+ symlinkSync(entry.directory, target, linkType);
1139
+ }
1140
+ }
1141
+ function linkOfficialPackages(profileDirectory, dshRoot) {
1142
+ materializeOfficialPackageScope(profileDirectory, resolve(officialPackageRoot(dshRoot), "node_modules", "@deepseek-ai"), listOfficialWorkspacePackages(dshRoot));
1143
+ }
1144
+ function writeLock(profileDirectory, lock) {
1145
+ const directory = resolve(profileDirectory, ".dsh-plus");
1146
+ mkdirSync(directory, { recursive: true });
1147
+ const path = resolve(directory, "patchset.lock.json");
1148
+ writeFileSync(path, JSON.stringify(lock, void 0, 2) + "\n", { mode: 384 });
1149
+ chmodSync(path, 384);
1150
+ return path;
1151
+ }
1152
+ function parseApplyArguments(argv) {
1153
+ if (argv[0] !== "apply") throw new Error("usage: dsh-plus apply --dsh-root <official-dsh-root>");
1154
+ let dshRoot;
1155
+ for (let index = 1; index < argv.length; index += 2) {
1156
+ const key = argv[index];
1157
+ const value = argv[index + 1];
1158
+ if (key !== "--dsh-root" || value === void 0) throw new Error("usage: dsh-plus apply --dsh-root <official-dsh-root>");
1159
+ dshRoot = resolve(value);
1160
+ }
1161
+ if (dshRoot === void 0) throw new Error("usage: dsh-plus apply --dsh-root <official-dsh-root>");
1162
+ return {
1163
+ dshRoot,
1164
+ profileDirectory: process.cwd()
1165
+ };
1166
+ }
1167
+ /**
1168
+ * Apply the installed Plus distribution metadata from a DSH profile directory.
1169
+ * @param argv - Explicit `apply --dsh-root <path>` command arguments.
1170
+ */
1171
+ function runApply(argv) {
1172
+ const { dshRoot, profileDirectory } = parseApplyArguments(argv);
1173
+ 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");
1174
+ const selection = prepareSelection(dirname(createRequire(resolve(profileDirectory, "package.json")).resolve("@sparkelf/dsh-plus/package.json")), profileDirectory, dshRoot);
1175
+ const profileChanged = writeProfileComposition(profileDirectory, selection.bundles, selection.runtimePackages);
1176
+ applySelectedPatches(profileDirectory, dshRoot, selection.patches, profileChanged);
1177
+ linkOfficialPackages(profileDirectory, dshRoot);
1178
+ const installedProfileDependencies = requireObject(readJsonObject(resolve(profileDirectory, "package.json"), "DSH profile manifest").dependencies, "DSH profile dependencies");
1179
+ selection.lock.profile = {
1180
+ bundles: selection.bundles.map((name) => {
1181
+ return {
1182
+ name,
1183
+ version: (installedProfileDependencies[name] === void 0 ? resolveInstalledPackage(officialPackageRoot(dshRoot), name) : resolveInstalledPackage(profileDirectory, name)).version
1184
+ };
1185
+ }),
1186
+ dependencies: selection.profileDependencies,
1187
+ allowBuilds: selection.allowBuilds
1188
+ };
1189
+ const lock = writeLock(profileDirectory, selection.lock);
1190
+ process.stdout.write("[dsh-plus] applied " + String(selection.patches.length) + " patches; lock " + lock + "\n");
1191
+ }
1192
+ //#endregion
1193
+ export { assertRedirectsPublished as a, writeProfileCompatibility as c, runApply as i, writeProfileProjection as l, parseOfficialWorkspacePackages as n, projectEdition as o, resolvePatchPackageNames as r, readDistributionFacts as s, materializeOfficialPackageScope as t, readPatchSet as u };