@linxin666/dsh-client-ui-plugin-manager 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1425 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { copyFile, readFile, rename, writeFile } from "node:fs/promises";
4
+ import { isAbsolute, join, win32 } from "node:path";
5
+ import { isMap, isScalar, isSeq, parseDocument } from "yaml";
6
+ import { homedir } from "node:os";
7
+ //#region src/mount-once.ts
8
+ /**
9
+ * Host single-instance guard shared by the plugin family. The family bundle
10
+ * (dsh-web-ui-all / dsh-skins) namespaces every child row id (web-ui-*), so
11
+ * the loader accepts a standalone install of the same package side by side;
12
+ * without this guard the second instance would still re-register the same
13
+ * webserver routes, tools, settings namespaces, and system-prompt sections
14
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
15
+ * lifetime of the first instance (the browser half is already deduped by
16
+ * package name in the client module host).
17
+ *
18
+ * The registry rides a global symbol so two module instances of the same
19
+ * package (npm copy vs repository link) still share one verdict. cordis
20
+ * `ctx.effect` runs its callback immediately and treats the callback's
21
+ * return value as the fiber disposer, so the unmarker is returned, not run.
22
+ */
23
+ const MOUNTED = Symbol.for("dsh-web-ui.mounted-plugins");
24
+ function mountedSet() {
25
+ const registry = globalThis;
26
+ return registry[MOUNTED] ??= /* @__PURE__ */ new Set();
27
+ }
28
+ /**
29
+ * Wrap a cordis plugin apply so the package runs at most once per process.
30
+ * The first mount registers normally and unmarks when its fiber disposes;
31
+ * any later mount of the same package name is a no-op.
32
+ * @param packageName - npm package identity shared by every install source.
33
+ * @param fn - the original plugin apply.
34
+ * @returns an apply of the same shape.
35
+ */
36
+ function mountOnce(packageName, fn) {
37
+ return ((...args) => {
38
+ const mounted = mountedSet();
39
+ if (mounted.has(packageName)) return;
40
+ mounted.add(packageName);
41
+ args[0]?.effect?.(() => () => {
42
+ mounted.delete(packageName);
43
+ });
44
+ return fn(...args);
45
+ });
46
+ }
47
+ //#endregion
48
+ //#region src/core/patch-diff.ts
49
+ /**
50
+ * Diff two layer snapshots by id. Only entries whose membership state moved
51
+ * are reported; unchanged entries are skipped.
52
+ * @param before - snapshot taken before the operation.
53
+ * @param after - snapshot taken after the operation.
54
+ * @returns one change per moved id, sorted by id.
55
+ */
56
+ function diffLayer(before, after) {
57
+ const ids = /* @__PURE__ */ new Set();
58
+ for (const id of before.rows.keys()) ids.add(id);
59
+ for (const id of after.rows.keys()) ids.add(id);
60
+ for (const bundle of before.bundles) ids.add(bundle);
61
+ for (const bundle of after.bundles) ids.add(bundle);
62
+ const stateOf = (snapshot, id) => {
63
+ const row = snapshot.rows.get(id);
64
+ if (row !== void 0) return row ? "enabled" : "disabled";
65
+ if (snapshot.bundles.includes(id)) return "enabled";
66
+ return "uninstalled";
67
+ };
68
+ const changes = [];
69
+ for (const id of ids) {
70
+ const from = stateOf(before, id);
71
+ const to = stateOf(after, id);
72
+ if (from !== to) changes.push({
73
+ id,
74
+ from,
75
+ to
76
+ });
77
+ }
78
+ return changes.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
79
+ }
80
+ /**
81
+ * Drop the normal install outcome — entries that merely appear (a new plugin
82
+ * mounting is the point of an install, not a conflict) — and keep every
83
+ * change to an entry that existed before.
84
+ * @param changes - the raw layer diff.
85
+ * @returns the conflict-worthy changes.
86
+ */
87
+ function significantChanges(changes) {
88
+ return changes.filter((change) => !(change.from === "uninstalled" && change.to === "enabled"));
89
+ }
90
+ /**
91
+ * The ids of `claimed` already held by another entry. Bundle rows with the
92
+ * same insert id double-mount at the next boot (duplicate entry id), so an
93
+ * install claiming a taken id is a boot-blocking conflict.
94
+ * @param claimed - the new plugin's claimed entry ids.
95
+ * @param taken - every id already claimed by other plugins and patch rows.
96
+ * @returns the overlapping ids, in claim order.
97
+ */
98
+ function overlappingIds(claimed, taken) {
99
+ return claimed.filter((id) => taken.has(id));
100
+ }
101
+ //#endregion
102
+ //#region src/host/rows.ts
103
+ /**
104
+ * Profile patch-row editing for the gateway host half. The npm web loader
105
+ * honors `disabled` on rows and applies the profile patch as the user layer,
106
+ * so next-start enablement is a bare `{ id, name, disabled }` override row —
107
+ * the same id-targeted, later-wins semantics the official desktop writer
108
+ * uses. Editing goes through the `yaml` document round-trip, which preserves
109
+ * comments and unrelated rows byte-for-byte in spirit; the !!js expression
110
+ * tag keeps loader expressions literal so profiles carrying them stay
111
+ * parseable.
112
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
113
+ */
114
+ /**
115
+ * Persist one patch file conservatively: a timestamped-free single backup,
116
+ * then a tmp write and an atomic-ish rename over the target.
117
+ * @param patchPath - absolute cordis.patch.yml path.
118
+ * @param text - the new file text.
119
+ */
120
+ async function writePatchAtomic(patchPath, text) {
121
+ await copyFile(patchPath, `${patchPath}.bak-plugin-manager`).catch(() => {});
122
+ await writeFile(`${patchPath}.tmp`, text, { mode: 384 });
123
+ await rename(`${patchPath}.tmp`, patchPath);
124
+ }
125
+ /** YAML `!!js` expression tag: expressions stay literal until the Loader evaluates them. */
126
+ const JS_EXPRESSION_TAG = {
127
+ tag: "tag:yaml.org,2002:js",
128
+ resolve: (value) => value
129
+ };
130
+ /**
131
+ * Parse a patch file, failing loud on invalid YAML and non-array roots.
132
+ * @param text - file content.
133
+ * @param filename - absolute cordis.patch.yml path (diagnostics only).
134
+ * @returns the parsed document and root sequence.
135
+ */
136
+ function parsePatch(text, filename) {
137
+ const document = parseDocument(text, {
138
+ customTags: [JS_EXPRESSION_TAG],
139
+ prettyErrors: true,
140
+ uniqueKeys: true
141
+ });
142
+ if (document.errors.length > 0) {
143
+ const firstError = document.errors[0];
144
+ throw new Error(`plugin-manager: cannot parse ${filename}: ${firstError?.message ?? "invalid YAML"}`);
145
+ }
146
+ const root = document.contents;
147
+ if (!isSeq(root)) throw new Error(`plugin-manager: ${filename} must contain a top-level YAML array`);
148
+ return {
149
+ document,
150
+ root
151
+ };
152
+ }
153
+ /** Whether a root item is a plain map row (not an insert-list wrapper). */
154
+ function isBareRow(item) {
155
+ return isMap(item) && !item.has("insert");
156
+ }
157
+ /** The string id of a bare row, when it carries one. */
158
+ function bareRowId(item) {
159
+ if (!isBareRow(item)) return void 0;
160
+ const id = item.get("id", true);
161
+ return isScalar(id) && typeof id.value === "string" ? id.value : void 0;
162
+ }
163
+ /** The string name of a bare row, when it carries one. */
164
+ function bareRowName(item) {
165
+ if (!isBareRow(item)) return void 0;
166
+ const name = item.get("name", true);
167
+ return isScalar(name) && typeof name.value === "string" ? name.value : void 0;
168
+ }
169
+ /**
170
+ * The next-start enablement a bare row declares: a row is enabled unless it
171
+ * carries an explicit `disabled: true` (mirrors the official reader). Non-row
172
+ * items (insert wrappers, config rows) count as enabled.
173
+ * @param item - one top-level patch item.
174
+ * @returns whether the item leaves its entry enabled.
175
+ */
176
+ function bareRowEnabled(item) {
177
+ if (!isBareRow(item)) return true;
178
+ const disabled = item.get("disabled", true);
179
+ return !(isScalar(disabled) && disabled.value === true);
180
+ }
181
+ /**
182
+ * Find the bare override row for one id.
183
+ * @param root - the top-level sequence.
184
+ * @param id - the entry id to match.
185
+ * @returns the row and its index, or undefined.
186
+ */
187
+ function findBareRow(root, id) {
188
+ const index = root.items.findIndex((item) => isBareRow(item) && bareRowId(item) === id);
189
+ if (index === -1) return void 0;
190
+ const row = root.items[index];
191
+ return isMap(row) ? {
192
+ row,
193
+ index
194
+ } : void 0;
195
+ }
196
+ /**
197
+ * The ids an installed package's own bundle patch claims, read from its
198
+ * cordis.patch.yml (each insert entry carries an id). An empty result means
199
+ * the package is a plain plugin whose row id is its package name.
200
+ * @param patchText - the package's own bundle patch text (`[]` for none).
201
+ * @returns the claimed insert ids, in order.
202
+ */
203
+ function claimedIdsOf(patchText) {
204
+ const ids = [];
205
+ for (const row of insertRowsOf(patchText)) if (row.id !== void 0) ids.push(row.id);
206
+ return ids;
207
+ }
208
+ /**
209
+ * The insert entries of an installed package's own bundle patch, with both
210
+ * the claimed id and the entry's own name. The name matters twice: the
211
+ * loader imports the plugin by it (an unresolvable name is a boot failure),
212
+ * and a bare override row whose name mismatches it is skipped by the include
213
+ * patch semantics, so enablement rows must carry this exact name.
214
+ * @param patchText - the package's own bundle patch text (`[]` for none).
215
+ * @returns the insert rows, in order.
216
+ */
217
+ function insertRowsOf(patchText) {
218
+ if (patchText.trim() === "" || patchText.trim() === "[]") return [];
219
+ try {
220
+ const { root } = parsePatch(patchText, "bundle patch");
221
+ const rows = [];
222
+ for (const item of root.items) {
223
+ if (!isMap(item)) continue;
224
+ const insert = item.get("insert", true);
225
+ if (!isSeq(insert)) continue;
226
+ for (const entry of insert.items) {
227
+ if (!isMap(entry)) continue;
228
+ const id = entry.get("id", true);
229
+ const name = entry.get("name", true);
230
+ rows.push({
231
+ id: isScalar(id) && typeof id.value === "string" ? id.value : void 0,
232
+ name: isScalar(name) && typeof name.value === "string" ? name.value : void 0
233
+ });
234
+ }
235
+ }
236
+ return rows;
237
+ } catch {
238
+ return [];
239
+ }
240
+ }
241
+ /**
242
+ * The inner entry of an insert-format item whose id matches, when one exists
243
+ * (the official desktop writer manages rows in this shape).
244
+ * @param root - the top-level sequence.
245
+ * @param id - the entry id to match.
246
+ * @returns the inner row, or undefined.
247
+ */
248
+ function findInsertRow(root, id) {
249
+ for (const item of root.items) {
250
+ if (!isMap(item)) continue;
251
+ const insert = item.get("insert", true);
252
+ if (!isSeq(insert)) continue;
253
+ for (const entry of insert.items) {
254
+ if (!isMap(entry)) continue;
255
+ const entryId = entry.get("id", true);
256
+ if (isScalar(entryId) && entryId.value === id) return entry;
257
+ }
258
+ }
259
+ }
260
+ /**
261
+ * Persist the next-start enablement of one entry. Bare override rows are this
262
+ * package's own shape: enabling removes the override, disabling creates or
263
+ * updates `{ id, name, disabled: true }`. When a newer desktop tool already
264
+ * manages the entry as an insert-format row, the inner row's `disabled` flag
265
+ * is edited instead (the official writer's shape). The returned text
266
+ * preserves every other row and comment.
267
+ * @param text - current patch file text.
268
+ * @param filename - absolute path (diagnostics only).
269
+ * @param id - the entry id to override.
270
+ * @param name - the display name recorded on the row.
271
+ * @param enabled - desired next-start enablement.
272
+ * @returns the new file text.
273
+ */
274
+ function setRowEnabled(text, filename, id, name, enabled) {
275
+ const { document, root } = parsePatch(text, filename);
276
+ const insertRow = findInsertRow(root, id);
277
+ if (insertRow !== void 0) {
278
+ insertRow.set("disabled", document.createNode(!enabled));
279
+ return document.toString({ lineWidth: 0 }) + "\n";
280
+ }
281
+ const found = findBareRow(root, id);
282
+ if (enabled) {
283
+ if (found === void 0) return text;
284
+ root.items.splice(found.index, 1);
285
+ } else if (found !== void 0) found.row.set("disabled", document.createNode(true));
286
+ else root.items.push(document.createNode({
287
+ id,
288
+ name,
289
+ disabled: true
290
+ }));
291
+ return document.toString({ lineWidth: 0 }) + "\n";
292
+ }
293
+ //#endregion
294
+ //#region src/host/bundle-guard.ts
295
+ /**
296
+ * Post-mutation duplicate-mount guard for the gateway host half. The official
297
+ * CLI's bundle reconciliation appends EVERY dependency that declares
298
+ * `dsh.bundle` to the profile manifest's `dsh.profile.bundles` — including
299
+ * packages the composition already mounts through a patch row (the family
300
+ * aggregate mounts dsh-better-sidebar as the insert row
301
+ * `{ id: 'better-sidebar', name: 'dsh-better-sidebar' }` while the package
302
+ * also sits in the profile's dependencies). The bundles layer then mounts the
303
+ * package a second time and the next boot dies on duplicate routes
304
+ * (`webserver: duplicate prefix route "/sidebar/api"`). This module decides,
305
+ * from the before-state composition, which newly added bundles entries are
306
+ * such duplicate mounts; the gateway strips exactly those entries back out.
307
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
308
+ */
309
+ /**
310
+ * The bundles entries a mutation newly added: present after, absent before.
311
+ * Entries the user already had are never the guard's business.
312
+ * @param before - bundles list before the mutation.
313
+ * @param after - bundles list after the mutation.
314
+ * @returns the newly added entries, in after-state order.
315
+ */
316
+ function newlyAddedBundles(before, after) {
317
+ return after.filter((name) => !before.includes(name));
318
+ }
319
+ /**
320
+ * Record one candidate row: an enabled row mounts its named package; a row
321
+ * the profile layer disables (bare `disabled: true` override matching the
322
+ * row id) mounts nothing, so it never justifies stripping a bundles entry.
323
+ */
324
+ function collectRow(mounted, rowEnabled, row) {
325
+ if (row.name === void 0 || row.name === "") return;
326
+ if (row.id !== void 0 && rowEnabled.get(row.id) === false) return;
327
+ mounted.add(row.name);
328
+ }
329
+ /**
330
+ * The package names the before-state composition already mounts through patch
331
+ * rows: the profile patch's own rows (bare and insert-format) plus every
332
+ * before-state dependency's own bundle patch insert entries (the aggregate's
333
+ * rows section lives there, not in the profile layer). A tolerant read: a
334
+ * broken patch file yields no names rather than failing the mutation.
335
+ * @param facts - resolved profile locations.
336
+ * @param before - the before-state capture.
337
+ * @returns the set of row-mounted package names.
338
+ */
339
+ async function rowMountedPackageNames(facts, before) {
340
+ const mounted = /* @__PURE__ */ new Set();
341
+ try {
342
+ const { root } = parsePatch(before.patchText, facts.patchPath);
343
+ for (const item of root.items) {
344
+ if (!isMap(item)) continue;
345
+ const name = bareRowName(item);
346
+ if (name !== void 0 && bareRowEnabled(item)) mounted.add(name);
347
+ }
348
+ } catch {}
349
+ for (const row of insertRowsOf(before.patchText)) collectRow(mounted, before.rowEnabled, row);
350
+ for (const dependency of before.dependencies) {
351
+ const patchPath = join(facts.profileDir, "node_modules", ...dependency.split("/"), "cordis.patch.yml");
352
+ let text;
353
+ try {
354
+ text = await readFile(patchPath, "utf8");
355
+ } catch {
356
+ continue;
357
+ }
358
+ for (const row of insertRowsOf(text)) collectRow(mounted, before.rowEnabled, row);
359
+ }
360
+ return mounted;
361
+ }
362
+ /**
363
+ * The newly added bundles entries that duplicate an existing row mount and
364
+ * must be stripped to keep the next boot alive.
365
+ * @param facts - resolved profile locations.
366
+ * @param before - the before-state capture.
367
+ * @param beforeBundles - the bundles list before the mutation.
368
+ * @param afterBundles - the bundles list after the mutation.
369
+ * @returns the entries to remove from `dsh.profile.bundles`.
370
+ */
371
+ async function duplicateMountBundles(facts, before, beforeBundles, afterBundles) {
372
+ const added = newlyAddedBundles(beforeBundles, afterBundles);
373
+ if (added.length === 0) return [];
374
+ const mounted = await rowMountedPackageNames(facts, before);
375
+ return added.filter((name) => mounted.has(name));
376
+ }
377
+ //#endregion
378
+ //#region src/host/dsh-home.ts
379
+ /**
380
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
381
+ * environment override wins, the platform home fallback follows. Mirrors
382
+ * what dsh-pet and dsh-liangshen each used to implement locally.
383
+ */
384
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
385
+ function expandHome(path, home = homedir()) {
386
+ if (path === "~") return home;
387
+ if (path.startsWith("~/") || path.startsWith("~\\")) return join(home, path.slice(2));
388
+ return path;
389
+ }
390
+ /**
391
+ * Resolve the DSH home directory.
392
+ * @param env - process environment to read DSH_HOME from.
393
+ * @param home - platform home directory fallback (test seam).
394
+ * @returns the absolute DSH home path.
395
+ */
396
+ function resolveDshHome(env = process.env, home = homedir()) {
397
+ const raw = env.DSH_HOME;
398
+ if (raw !== void 0 && raw.trim() !== "") {
399
+ const expanded = expandHome(raw.trim(), home);
400
+ return isAbsolute(expanded) ? expanded : join(process.cwd(), expanded);
401
+ }
402
+ return join(home, ".dsh");
403
+ }
404
+ //#endregion
405
+ //#region src/host/profile.ts
406
+ /**
407
+ * Profile resolution and manifest reads for the gateway host half. The npm
408
+ * web runtime has no plugin-installer service, so this package resolves the
409
+ * boot profile from the host process's own argv (the launcher fact) and reads
410
+ * the profile's package.json and cordis.patch.yml directly — reads only; every
411
+ * write goes through the official CLI or the patch-row editor.
412
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
413
+ */
414
+ /**
415
+ * Resolve the boot profile name from the host argv: an explicit `--profile`
416
+ * flag wins, then the DSH_PROFILE environment override, then the `web`
417
+ * subcommand alias. The launcher hands the app its own args verbatim, so the
418
+ * web app's argv is the reliable source on every CLI-launched host.
419
+ * @param argv - process argv (test seam).
420
+ * @param env - process environment (test seam).
421
+ * @returns the resolved profile facts.
422
+ */
423
+ function resolveProfile(argv = process.argv, env = process.env) {
424
+ const flagIndex = argv.indexOf("--profile");
425
+ let name;
426
+ if (flagIndex !== -1 && argv[flagIndex + 1] !== void 0 && argv[flagIndex + 1] !== "") name = argv[flagIndex + 1];
427
+ else if (env.DSH_PROFILE !== void 0 && env.DSH_PROFILE.trim() !== "") name = env.DSH_PROFILE.trim();
428
+ else if (argv.includes("web")) name = "web";
429
+ if (name === void 0) throw new Error("plugin-manager: cannot determine the boot profile; pass --profile <name> or set DSH_PROFILE");
430
+ if (name.includes("/") || name.includes("\\") || name.includes("..")) throw new Error(`plugin-manager: invalid profile name ${JSON.stringify(name)}`);
431
+ const profileDir = join(resolveDshHome(env), "profiles", name);
432
+ return {
433
+ profileName: name,
434
+ profileDir,
435
+ patchPath: join(profileDir, "cordis.patch.yml"),
436
+ packageJsonPath: join(profileDir, "package.json")
437
+ };
438
+ }
439
+ /**
440
+ * Read the profile manifest; a missing or malformed file fails loud.
441
+ * @param packageJsonPath - absolute path of the profile's package.json.
442
+ * @returns the parsed bundles and dependencies.
443
+ */
444
+ async function readProfileManifest(packageJsonPath) {
445
+ const text = await readFile(packageJsonPath, "utf8");
446
+ const parsed = JSON.parse(text);
447
+ const bundles = Array.isArray(parsed.dsh?.profile?.bundles) ? parsed.dsh.profile.bundles.filter((item) => typeof item === "string") : [];
448
+ const rawDeps = parsed.dependencies;
449
+ const dependencies = {};
450
+ if (typeof rawDeps === "object" && rawDeps !== null) {
451
+ for (const [name, spec] of Object.entries(rawDeps)) if (typeof spec === "string") dependencies[name] = spec;
452
+ }
453
+ return {
454
+ bundles,
455
+ dependencies
456
+ };
457
+ }
458
+ /**
459
+ * Remove selected entries from the profile manifest's `dsh.profile.bundles`,
460
+ * conservatively: a single backup copy, then a tmp write and an atomic-ish
461
+ * rename over the target — the same discipline as the patch-row editor. Every
462
+ * other key (dependencies included) round-trips untouched; entries not in
463
+ * `names` keep their order. A missing bundles array is a no-op write.
464
+ * @param packageJsonPath - absolute path of the profile's package.json.
465
+ * @param names - bundle entries to strip (package names).
466
+ */
467
+ async function stripProfileBundles(packageJsonPath, names) {
468
+ const text = await readFile(packageJsonPath, "utf8");
469
+ const parsed = JSON.parse(text);
470
+ const profile = parsed.dsh?.profile;
471
+ if (profile === void 0 || !Array.isArray(profile.bundles)) return;
472
+ profile.bundles = profile.bundles.filter((entry) => !(typeof entry === "string" && names.includes(entry)));
473
+ await copyFile(packageJsonPath, `${packageJsonPath}.bak-plugin-manager`).catch(() => {});
474
+ await writeFile(`${packageJsonPath}.tmp`, `${JSON.stringify(parsed, null, 2)}\n`, { mode: 384 });
475
+ await rename(`${packageJsonPath}.tmp`, packageJsonPath);
476
+ }
477
+ /**
478
+ * Read the profile patch text; a missing file is an empty layer.
479
+ * @param patchPath - absolute path of cordis.patch.yml.
480
+ * @returns the file text, or `[]` when absent.
481
+ */
482
+ async function readPatchText(patchPath) {
483
+ try {
484
+ return await readFile(patchPath, "utf8");
485
+ } catch (error) {
486
+ if (error?.code === "ENOENT") return "[]\n";
487
+ throw error;
488
+ }
489
+ }
490
+ /** Whether a profile directory exists (the gateway needs an initialized profile). */
491
+ function profileExists(profileDir) {
492
+ return existsSync(join(profileDir, "package.json"));
493
+ }
494
+ //#endregion
495
+ //#region src/host/state.ts
496
+ /**
497
+ * Gateway listing: the installed-plugin inventory read from the profile's
498
+ * package.json, its node_modules manifests, and the patch rows' enablement.
499
+ * The npm web runtime has no installer inventory service, so this module is
500
+ * the read side of the gateway (the write side is the official CLI).
501
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
502
+ */
503
+ /** The node_modules path of one (possibly scoped) package name. */
504
+ function modulePathOf(profileDir, name) {
505
+ return join(profileDir, "node_modules", ...name.split("/"));
506
+ }
507
+ /** Whether an install spec names a git/file/link source rather than a registry package. */
508
+ function sourceKindOf(spec) {
509
+ return /^(link:|file:|git:|github:|git\+|https?:\/\/github\.com)/.test(spec) ? "git" : "npm";
510
+ }
511
+ /**
512
+ * The entry ids one installed dependency claims: the insert ids of its own
513
+ * bundle patch, falling back to the package name. Shared by the listing read
514
+ * side and the set-enabled write side so both agree on the id space — writing
515
+ * package-name rows while reading bundle-patch ids made the switches inert.
516
+ * @param facts - resolved profile locations.
517
+ * @param name - dependency name (possibly scoped).
518
+ * @returns the claimed entry ids, never empty.
519
+ */
520
+ async function claimedEntryIdsOf(facts, name) {
521
+ const patchPath = join(modulePathOf(facts.profileDir, name), "cordis.patch.yml");
522
+ try {
523
+ const ids = claimedIdsOf(await readFile(patchPath, "utf8"));
524
+ if (ids.length > 0) return ids;
525
+ } catch {}
526
+ return [name];
527
+ }
528
+ /**
529
+ * The insert rows one installed dependency claims, id plus the entry's own
530
+ * name (falling back to the package name for plain plugins). The set-enabled
531
+ * write side needs the entry's own name: the include patch semantics skip a
532
+ * bare override row whose name mismatches the inserted entry's name.
533
+ * @param facts - resolved profile locations.
534
+ * @param name - dependency name (possibly scoped).
535
+ * @returns the claimed rows, never empty.
536
+ */
537
+ async function claimedEntryRowsOf(facts, name) {
538
+ const patchPath = join(modulePathOf(facts.profileDir, name), "cordis.patch.yml");
539
+ try {
540
+ const claimed = insertRowsOf(await readFile(patchPath, "utf8")).filter((row) => row.id !== void 0);
541
+ if (claimed.length > 0) return claimed.map((row) => ({
542
+ id: row.id,
543
+ name: row.name ?? name
544
+ }));
545
+ } catch {}
546
+ return [{
547
+ id: name,
548
+ name
549
+ }];
550
+ }
551
+ /**
552
+ * Build one installed-plugin row from the profile facts: version from the
553
+ * installed manifest, enablement from the entry ids its own bundle patch
554
+ * claims (plain plugins use the package name as the row id).
555
+ * @param facts - resolved profile locations.
556
+ * @param name - dependency name (possibly scoped).
557
+ * @param spec - the install spec recorded in the profile dependencies.
558
+ * @param rowEnabled - row enablement by id.
559
+ * @returns the wire-shaped plugin row.
560
+ */
561
+ async function buildPluginRow(facts, name, spec, rowEnabled) {
562
+ const moduleDir = modulePathOf(facts.profileDir, name);
563
+ let version = "unknown";
564
+ try {
565
+ const parsed = JSON.parse(await readFile(join(moduleDir, "package.json"), "utf8"));
566
+ if (typeof parsed.version === "string") version = parsed.version;
567
+ } catch {
568
+ version = "unknown";
569
+ }
570
+ let bundlePatch = "[]";
571
+ const bundlePatchPath = join(moduleDir, "cordis.patch.yml");
572
+ if (existsSync(bundlePatchPath)) try {
573
+ bundlePatch = await readFile(bundlePatchPath, "utf8");
574
+ } catch {
575
+ bundlePatch = "[]";
576
+ }
577
+ const claimed = claimedIdsOf(bundlePatch);
578
+ const enabled = (claimed.length > 0 ? claimed : [name]).every((id) => rowEnabled.get(id) ?? true);
579
+ return {
580
+ id: name,
581
+ name,
582
+ version,
583
+ source: {
584
+ kind: sourceKindOf(spec),
585
+ spec
586
+ },
587
+ installedAt: "",
588
+ enabled
589
+ };
590
+ }
591
+ /**
592
+ * Build the gateway listing and the layer snapshot.
593
+ * @param facts - resolved profile locations.
594
+ * @param patchText - current profile patch text.
595
+ * @returns plugin rows (wire shape of the official list) and the layer state.
596
+ */
597
+ async function snapshotGateway(facts, patchText) {
598
+ const manifest = await readProfileManifest(facts.packageJsonPath);
599
+ const parsed = parsePatch(patchText, facts.patchPath);
600
+ const rowEnabled = /* @__PURE__ */ new Map();
601
+ for (const item of parsed.root.items) {
602
+ const id = bareRowId(item);
603
+ if (id !== void 0) rowEnabled.set(id, bareRowEnabled(item));
604
+ }
605
+ const plugins = [];
606
+ for (const name of Object.keys(manifest.dependencies).sort()) plugins.push(await buildPluginRow(facts, name, manifest.dependencies[name], rowEnabled));
607
+ return {
608
+ plugins,
609
+ layer: {
610
+ rows: rowEnabled,
611
+ bundles: manifest.bundles
612
+ }
613
+ };
614
+ }
615
+ //#endregion
616
+ //#region src/host/gateway.ts
617
+ /**
618
+ * The CLI gateway: installs and removals executed by spawning the official
619
+ * `dsh plugin --profile <name> add|remove` CLI — the single writer for the
620
+ * profile — with a bounded job table the HTTP layer polls. Every run captures
621
+ * a layer snapshot before and after so the caller can render exactly what the
622
+ * CLI changed (the conflict ledger). The npm web runtime has no installer
623
+ * service, so this gateway is its write path; on runtimes with official
624
+ * channels the browser half never calls it.
625
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
626
+ */
627
+ /** Hard deadline for one CLI add (git clones can take minutes). */
628
+ const ADD_TIMEOUT_MS = 6 * 6e4;
629
+ /** Hard deadline for one CLI remove. */
630
+ const REMOVE_TIMEOUT_MS = 2 * 6e4;
631
+ /**
632
+ * Shell command-chaining metacharacters that must never reach a spawned CLI
633
+ * argument. The gateway spawns shell-free, but the official CLI forwards to
634
+ * pnpm with a cmd.exe shell on Windows, so a spec carrying these can still be
635
+ * re-parsed one layer down (a failed install reported as success, or worse).
636
+ */
637
+ const UNSAFE_SPEC_CHARS = /[&|<>"'`\n\r\0]/;
638
+ /**
639
+ * Validate an install spec or package id against shell metacharacters.
640
+ * @param spec - the user-supplied spec or id.
641
+ * @returns the rejection message, or undefined when the spec is safe.
642
+ */
643
+ function unsafeSpecReason(spec) {
644
+ return UNSAFE_SPEC_CHARS.test(spec) ? "plugin-manager: spec 含有危险的 shell 元字符(& | < > 引号 反引号或控制字符),已拒绝" : void 0;
645
+ }
646
+ /** The binary search roots for the dsh CLI. */
647
+ function findDshBinary(env = process.env, platform = process.platform, exists = existsSync) {
648
+ const candidates = [];
649
+ const separator = platform === "win32" ? ";" : ":";
650
+ for (const dir of (env.PATH ?? "").split(separator)) {
651
+ if (dir === "") continue;
652
+ if (platform === "win32") candidates.push(`${dir}\\dsh.cmd`, `${dir}\\dsh.exe`);
653
+ else candidates.push(`${dir}/dsh`);
654
+ }
655
+ if (platform === "darwin") candidates.push("/opt/homebrew/bin/dsh", "/usr/local/bin/dsh");
656
+ for (const candidate of candidates) if (exists(candidate)) return candidate;
657
+ return null;
658
+ }
659
+ /** Append bounded CLI output (stdout + stderr interleaved is not preserved; tail wins). */
660
+ function capture(chunk, buffer) {
661
+ buffer.value = (buffer.value + chunk.toString()).slice(-32e3);
662
+ }
663
+ /**
664
+ * The spawn command for the dsh CLI on this platform. Windows runs the
665
+ * npm-generated dsh.cmd wrapper by resolving its node binary and bin.js script
666
+ * and spawning them directly: going through cmd.exe splits unquoted paths with
667
+ * spaces (`'D:\Program' is not recognized`).
668
+ * @param binary - the dsh CLI path found by {@link findDshBinary}.
669
+ * @param platform - process platform (test seam).
670
+ * @param localNodeExists - existence probe (test seam).
671
+ * @returns the executable and the argument prefix to run the dsh bin script.
672
+ */
673
+ function dshSpawnCommand(binary, platform = process.platform, localNodeExists = existsSync) {
674
+ if (platform !== "win32") return {
675
+ command: binary,
676
+ argsPrefix: []
677
+ };
678
+ const dir = win32.dirname(binary);
679
+ const localNode = win32.join(dir, "node.exe");
680
+ const binJs = win32.join(dir, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js");
681
+ return {
682
+ command: localNodeExists(localNode) ? localNode : process.execPath,
683
+ argsPrefix: [binJs]
684
+ };
685
+ }
686
+ /** Spawn the dsh CLI with piped stdio and no shell parsing (see {@link dshSpawnCommand}). */
687
+ function spawnDsh(binary, args, env) {
688
+ const { command, argsPrefix } = dshSpawnCommand(binary);
689
+ return spawn(command, [...argsPrefix, ...args], {
690
+ env,
691
+ stdio: [
692
+ "ignore",
693
+ "pipe",
694
+ "pipe"
695
+ ]
696
+ });
697
+ }
698
+ /**
699
+ * Entry-id line of the official installer channels in the boot dump. A plain
700
+ * substring probe false-positives on any unrelated entry whose id, name, or
701
+ * config mentions the mark, so only a real `id:` row counts.
702
+ */
703
+ const OFFICIAL_INSTALLER_PATTERN = /^\s*-?\s*id:\s*['"]?plugin-(?:installer|control)['"]?\s*$/m;
704
+ /**
705
+ * Detect whether the official installer channels exist on this runtime by
706
+ * dumping the boot composition once: the npm-published web never contains
707
+ * `plugin-installer` entries, DSHCode and the checkout web do. The browser
708
+ * half reads the verdict from the `/mode` route so its channel probe never
709
+ * has to hit the missing official route (which 405s into the console).
710
+ * @param binary - dsh CLI path.
711
+ * @param profileName - boot profile name.
712
+ * @param env - process environment.
713
+ * @param spawnImpl - spawn seam (test seam).
714
+ * @returns true when the dump names the official installer channels.
715
+ */
716
+ async function detectOfficialChannels(binary, profileName, env = process.env, spawnImpl = spawnDsh) {
717
+ const output = { value: "" };
718
+ const child = spawnImpl(binary, [
719
+ "--profile",
720
+ profileName,
721
+ "--dump-config"
722
+ ], env);
723
+ child.stdout?.on("data", (chunk) => {
724
+ output.value = (output.value + chunk.toString()).slice(-32e3);
725
+ });
726
+ child.stderr?.on("data", (chunk) => {
727
+ output.value = (output.value + chunk.toString()).slice(-32e3);
728
+ });
729
+ if (await new Promise((resolve) => {
730
+ child.on("close", resolve);
731
+ }) !== 0) return false;
732
+ return OFFICIAL_INSTALLER_PATTERN.test(output.value);
733
+ }
734
+ /** The gateway: serializes CLI operations through one job table and one mutation queue. */
735
+ var CliGateway = class {
736
+ facts;
737
+ env;
738
+ deps;
739
+ jobs = /* @__PURE__ */ new Map();
740
+ counter = 0;
741
+ /** Mutation queue: two CLI runs must never interleave their before/after captures. */
742
+ queue = Promise.resolve();
743
+ /**
744
+ * @param facts - resolved profile locations.
745
+ * @param env - process environment.
746
+ * @param deps - spawn/binary seams (tests only; production uses the real CLI).
747
+ */
748
+ constructor(facts, env = process.env, deps = {}) {
749
+ this.facts = facts;
750
+ this.env = env;
751
+ this.deps = deps;
752
+ }
753
+ /** Chain one mutation onto the queue; a settled job never blocks the next one. */
754
+ enqueue(task) {
755
+ this.queue = this.queue.then(task).catch(() => {});
756
+ }
757
+ /** The dsh CLI path, through the test seam when present. */
758
+ binary() {
759
+ return this.deps.findBinary !== void 0 ? this.deps.findBinary(this.env) : findDshBinary(this.env);
760
+ }
761
+ /** Spawn the CLI, through the test seam when present. */
762
+ spawnCli(binary, args) {
763
+ return (this.deps.spawnImpl ?? spawnDsh)(binary, args, this.env);
764
+ }
765
+ /** Start an install; the caller polls {@link status}. */
766
+ install(spec) {
767
+ const job = {
768
+ id: `job-${++this.counter}`,
769
+ action: "install",
770
+ spec,
771
+ phase: "running"
772
+ };
773
+ this.jobs.set(job.id, job);
774
+ const unsafe = unsafeSpecReason(spec);
775
+ if (unsafe !== void 0) {
776
+ job.phase = "error";
777
+ job.error = unsafe;
778
+ return { jobId: job.id };
779
+ }
780
+ this.enqueue(() => this.run(job, [
781
+ "plugin",
782
+ "--profile",
783
+ this.facts.profileName,
784
+ "add",
785
+ spec
786
+ ], ADD_TIMEOUT_MS));
787
+ return { jobId: job.id };
788
+ }
789
+ /** Start a removal; the caller polls {@link status}. */
790
+ remove(id) {
791
+ const job = {
792
+ id: `job-${++this.counter}`,
793
+ action: "remove",
794
+ spec: id,
795
+ phase: "running"
796
+ };
797
+ this.jobs.set(job.id, job);
798
+ const unsafe = unsafeSpecReason(id);
799
+ if (unsafe !== void 0) {
800
+ job.phase = "error";
801
+ job.error = unsafe;
802
+ return { jobId: job.id };
803
+ }
804
+ this.enqueue(() => this.run(job, [
805
+ "plugin",
806
+ "--profile",
807
+ this.facts.profileName,
808
+ "remove",
809
+ id
810
+ ], REMOVE_TIMEOUT_MS));
811
+ return { jobId: job.id };
812
+ }
813
+ /** Read one job's current state (a shallow copy). */
814
+ status(jobId) {
815
+ const job = this.jobs.get(jobId);
816
+ if (job === void 0) return void 0;
817
+ return {
818
+ ...job,
819
+ conflicts: job.conflicts === void 0 ? void 0 : [...job.conflicts],
820
+ notices: job.notices === void 0 ? void 0 : [...job.notices]
821
+ };
822
+ }
823
+ /** Capture the layer snapshot and the dependency names (tolerant parse). */
824
+ async capture() {
825
+ const rows = /* @__PURE__ */ new Map();
826
+ let patchText = "[]\n";
827
+ try {
828
+ patchText = await readFile(this.facts.patchPath, "utf8");
829
+ } catch {
830
+ patchText = "[]\n";
831
+ }
832
+ try {
833
+ const { root } = parsePatch(patchText, this.facts.patchPath);
834
+ for (const item of root.items) {
835
+ const id = bareRowId(item);
836
+ if (id !== void 0) rows.set(id, bareRowEnabled(item));
837
+ }
838
+ } catch {}
839
+ let bundles = [];
840
+ let dependencies = [];
841
+ try {
842
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
843
+ bundles = manifest.bundles;
844
+ dependencies = Object.keys(manifest.dependencies);
845
+ } catch {
846
+ bundles = [];
847
+ dependencies = [];
848
+ }
849
+ return {
850
+ layer: {
851
+ rows,
852
+ bundles
853
+ },
854
+ patchText,
855
+ dependencies
856
+ };
857
+ }
858
+ /** The plugin row a finished operation produced (installed or removed). */
859
+ async rowFor(action, spec, before, after) {
860
+ let targetName;
861
+ if (action === "install") targetName = after.dependencies.find((name) => !before.dependencies.includes(name));
862
+ else targetName = before.dependencies.find((name) => !after.dependencies.includes(name)) ?? spec;
863
+ if (targetName === void 0) return void 0;
864
+ const specValue = await readProfileManifest(this.facts.packageJsonPath).then((manifest) => manifest.dependencies[targetName] ?? spec).catch(() => spec);
865
+ return buildPluginRow(this.facts, targetName, specValue, after.layer.rows);
866
+ }
867
+ /** Run one CLI operation to settlement; an unexpected failure settles the job as error. */
868
+ async run(job, args, timeoutMs) {
869
+ try {
870
+ await this.runInner(job, args, timeoutMs);
871
+ } catch (error) {
872
+ job.phase = "error";
873
+ job.error = `plugin-manager: unexpected gateway failure: ${error instanceof Error ? error.message : String(error)}`;
874
+ }
875
+ }
876
+ /** The mutation body of {@link run}. */
877
+ async runInner(job, args, timeoutMs) {
878
+ const binary = this.binary();
879
+ if (binary === null) {
880
+ job.phase = "error";
881
+ job.error = "plugin-manager: dsh CLI not found on PATH";
882
+ return;
883
+ }
884
+ const before = await this.capture();
885
+ const output = { value: "" };
886
+ const child = this.spawnCli(binary, args);
887
+ child.stdout?.on("data", (chunk) => {
888
+ capture(chunk, output);
889
+ });
890
+ child.stderr?.on("data", (chunk) => {
891
+ capture(chunk, output);
892
+ });
893
+ const timer = setTimeout(() => {
894
+ child.kill();
895
+ }, timeoutMs);
896
+ const code = await new Promise((resolve) => {
897
+ child.on("close", resolve);
898
+ });
899
+ clearTimeout(timer);
900
+ if (code !== 0) {
901
+ job.phase = "error";
902
+ const tail = output.value.trim();
903
+ job.error = tail === "" ? `plugin-manager: dsh plugin ${job.action} exited with code ${String(code)}` : tail;
904
+ return;
905
+ }
906
+ let after = await this.capture();
907
+ const stripped = await this.stripDuplicateMounts(job, before, after);
908
+ if (stripped === void 0) return;
909
+ if (stripped.length > 0) {
910
+ job.notices = stripped.map((name) => ({
911
+ id: name,
912
+ name,
913
+ from: "enabled",
914
+ to: "uninstalled"
915
+ }));
916
+ after = await this.capture();
917
+ }
918
+ const conflicts = significantChanges(diffLayer(before.layer, after.layer));
919
+ if (job.action === "install") {
920
+ const name = this.newDependency(before, after);
921
+ if (name === void 0) {
922
+ job.phase = "error";
923
+ job.error = "plugin-manager: dsh plugin add 报告成功,但 profile 未新增任何依赖(安装未生效)";
924
+ return;
925
+ }
926
+ const duplicate = await this.detectDuplicateClaims(before, after);
927
+ if (duplicate !== void 0) {
928
+ await this.rollbackInstall(job, name, `与现有插件的入口 id 冲突(${duplicate.ids.join(", ")})`, conflicts);
929
+ return;
930
+ }
931
+ const missing = await this.unresolvableInsertNames(name);
932
+ if (missing.length > 0) {
933
+ await this.rollbackInstall(job, name, `入口引用了不可解析的包(${missing.join(", ")})`, conflicts);
934
+ return;
935
+ }
936
+ await this.verifyBoot(job, before, after, conflicts);
937
+ if (job.phase === "error") return;
938
+ } else if (before.dependencies.find((candidate) => !after.dependencies.includes(candidate)) === void 0) {
939
+ job.phase = "error";
940
+ job.error = "plugin-manager: dsh plugin remove 报告成功,但依赖仍在 profile 中(卸载未生效)";
941
+ return;
942
+ }
943
+ job.conflicts = conflicts.map((change) => ({
944
+ id: change.id,
945
+ name: change.id,
946
+ from: change.from,
947
+ to: change.to
948
+ }));
949
+ job.plugin = await this.rowFor(job.action, job.spec, before, after);
950
+ job.phase = "done";
951
+ }
952
+ /**
953
+ * Post-mutation duplicate-mount safeguard (B9): remove the bundles entries
954
+ * the CLI's reconciliation newly added for packages the before-state
955
+ * composition already mounted through a patch row. The write goes through
956
+ * the manifest's safe path (backup + tmp + atomic rename); entries the
957
+ * user had before and entries with no row mount are never touched. A
958
+ * failure of the guard itself settles the job as an error — a boot-breaking
959
+ * bundles state is never left silently.
960
+ * @param job - the settling job (error target on guard failure).
961
+ * @param before - state captured before the CLI run.
962
+ * @param after - state captured after the CLI run.
963
+ * @returns the stripped entries, or undefined when the job failed.
964
+ */
965
+ async stripDuplicateMounts(job, before, after) {
966
+ try {
967
+ const strip = await duplicateMountBundles(this.facts, {
968
+ patchText: before.patchText,
969
+ dependencies: before.dependencies,
970
+ rowEnabled: before.layer.rows
971
+ }, before.layer.bundles, after.layer.bundles);
972
+ if (strip.length === 0) return [];
973
+ await stripProfileBundles(this.facts.packageJsonPath, strip);
974
+ return strip;
975
+ } catch (error) {
976
+ job.phase = "error";
977
+ job.error = `plugin-manager: 重复挂载保护写回失败:${error instanceof Error ? error.message : String(error)}(profile 的 dsh.profile.bundles 可能仍处于重复挂载状态,下次启动前请手动检查 ${this.facts.packageJsonPath})`;
978
+ return;
979
+ }
980
+ }
981
+ /**
982
+ * Roll back a freshly installed dependency through the official remove
983
+ * path (which also drops its bundle), then settle the job as an error.
984
+ * This is the owner-aware conflict resolution: the existing plugin keeps
985
+ * its entry ids and enablement untouched.
986
+ */
987
+ async rollbackInstall(job, name, reason, conflicts) {
988
+ let rolledBack = false;
989
+ let tail = "";
990
+ const binary = this.binary();
991
+ if (binary !== null) {
992
+ const output = { value: "" };
993
+ const child = this.spawnCli(binary, [
994
+ "plugin",
995
+ "--profile",
996
+ this.facts.profileName,
997
+ "remove",
998
+ name
999
+ ]);
1000
+ child.stdout?.on("data", (chunk) => {
1001
+ capture(chunk, output);
1002
+ });
1003
+ child.stderr?.on("data", (chunk) => {
1004
+ capture(chunk, output);
1005
+ });
1006
+ const timer = setTimeout(() => {
1007
+ child.kill();
1008
+ }, REMOVE_TIMEOUT_MS);
1009
+ const code = await new Promise((resolve) => {
1010
+ child.on("close", resolve);
1011
+ });
1012
+ clearTimeout(timer);
1013
+ rolledBack = code === 0;
1014
+ tail = output.value.trim();
1015
+ }
1016
+ job.phase = "error";
1017
+ job.error = rolledBack ? `plugin-manager: ${reason},已自动回滚 ${name}` : `plugin-manager: ${reason};自动回滚失败,请手动执行 dsh plugin --profile ${this.facts.profileName} remove ${name}${tail === "" ? "" : `:\n${tail}`}`;
1018
+ conflicts.push({
1019
+ id: name,
1020
+ from: "enabled",
1021
+ to: "uninstalled"
1022
+ });
1023
+ job.conflicts = conflicts.map((change) => ({
1024
+ id: change.id,
1025
+ name: change.id,
1026
+ from: change.from,
1027
+ to: change.to
1028
+ }));
1029
+ }
1030
+ /**
1031
+ * Insert-entry package names of one installed dependency that resolve
1032
+ * nowhere: not the dependency itself, not another profile dependency, not
1033
+ * an official @deepseek-ai/* package, and absent from every node_modules
1034
+ * the loader could import them from. Import-time failures beyond this
1035
+ * static check still surface only at the first real boot.
1036
+ */
1037
+ async unresolvableInsertNames(name) {
1038
+ const moduleDir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
1039
+ let text;
1040
+ try {
1041
+ text = await readFile(join(moduleDir, "cordis.patch.yml"), "utf8");
1042
+ } catch {
1043
+ return [];
1044
+ }
1045
+ const missing = [];
1046
+ for (const row of insertRowsOf(text)) {
1047
+ const target = row.name;
1048
+ if (target === void 0 || target === "") continue;
1049
+ if (target === name) continue;
1050
+ if (target.startsWith("@deepseek-ai/")) continue;
1051
+ if (existsSync(join(this.facts.profileDir, "node_modules", ...target.split("/")))) continue;
1052
+ if (existsSync(join(moduleDir, "node_modules", ...target.split("/")))) continue;
1053
+ missing.push(target);
1054
+ }
1055
+ return missing;
1056
+ }
1057
+ /** The new dependency of an install, when one exists. */
1058
+ newDependency(before, after) {
1059
+ return after.dependencies.find((name) => !before.dependencies.includes(name));
1060
+ }
1061
+ /** The claimed entry ids of one installed dependency (its own bundle patch, or its name). */
1062
+ claimedEntriesOf(name) {
1063
+ return claimedEntryIdsOf(this.facts, name);
1064
+ }
1065
+ /** Whether the new install claims an entry id another plugin already holds. */
1066
+ async detectDuplicateClaims(before, after) {
1067
+ const name = this.newDependency(before, after);
1068
+ if (name === void 0) return void 0;
1069
+ const claimed = await this.claimedEntriesOf(name);
1070
+ const taken = new Set(after.layer.rows.keys());
1071
+ for (const dep of after.dependencies) {
1072
+ if (dep === name) continue;
1073
+ for (const id of await this.claimedEntriesOf(dep)) taken.add(id);
1074
+ }
1075
+ const overlap = overlappingIds(claimed, taken);
1076
+ if (overlap.length === 0) return void 0;
1077
+ return {
1078
+ name,
1079
+ ids: overlap
1080
+ };
1081
+ }
1082
+ /**
1083
+ * Boot preflight after an install: compose the profile with the CLI's
1084
+ * `--dump-config` (resolves every entry without binding the port). A failure
1085
+ * that implicates the new plugin disables it so the next start cannot fail;
1086
+ * an unrelated failure is reported without touching anything.
1087
+ */
1088
+ async verifyBoot(job, before, after, conflicts) {
1089
+ const binary = this.binary();
1090
+ if (binary === null) return;
1091
+ const name = this.newDependency(before, after);
1092
+ const verifyOutput = { value: "" };
1093
+ const child = this.spawnCli(binary, [
1094
+ "--profile",
1095
+ this.facts.profileName,
1096
+ "--dump-config"
1097
+ ]);
1098
+ child.stdout?.on("data", (chunk) => {
1099
+ capture(chunk, verifyOutput);
1100
+ });
1101
+ child.stderr?.on("data", (chunk) => {
1102
+ capture(chunk, verifyOutput);
1103
+ });
1104
+ const timer = setTimeout(() => {
1105
+ child.kill();
1106
+ }, 9e4);
1107
+ const code = await new Promise((resolve) => {
1108
+ child.on("close", resolve);
1109
+ });
1110
+ clearTimeout(timer);
1111
+ if (code === 0) return;
1112
+ const tail = verifyOutput.value.trim();
1113
+ if (name === void 0) {
1114
+ job.phase = "error";
1115
+ job.error = tail === "" ? "plugin-manager: boot preflight failed" : tail;
1116
+ return;
1117
+ }
1118
+ const claimed = await this.claimedEntriesOf(name);
1119
+ if (tail.includes(name) || claimed.some((id) => tail.includes(id))) await this.rollbackInstall(job, name, `启动预检失败${tail === "" ? "" : `:\n${tail}`}`, conflicts);
1120
+ else {
1121
+ job.phase = "error";
1122
+ job.error = tail === "" ? "plugin-manager: 启动预检失败(与本次安装无关)" : `plugin-manager: 启动预检失败(与本次安装无关):\n${tail}`;
1123
+ }
1124
+ }
1125
+ };
1126
+ //#endregion
1127
+ //#region src/host/loopback.ts
1128
+ /** IPv4 127/8 predicate (four decimal octets, first == 127). */
1129
+ function isIPv4Loopback(v4) {
1130
+ const parts = v4.split(".");
1131
+ return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
1132
+ }
1133
+ /** Whether a socket remote address names the loopback range (127/8, ::1, IPv4-mapped). */
1134
+ function isLoopbackAddress(address) {
1135
+ if (address === void 0) return false;
1136
+ const normalized = address.toLowerCase();
1137
+ if (normalized === "::1") return true;
1138
+ if (normalized.startsWith("::ffff:")) return isIPv4Loopback(normalized.slice(7));
1139
+ return isIPv4Loopback(normalized);
1140
+ }
1141
+ /** Whether a normalized URL hostname names the loopback authority (localhost, [::1], 127/8). */
1142
+ function isLoopbackHostname(hostname) {
1143
+ if (hostname === "localhost" || hostname === "[::1]") return true;
1144
+ return isIPv4Loopback(hostname);
1145
+ }
1146
+ /**
1147
+ * Request-level trust fence: a loopback socket address AND a loopback Host
1148
+ * header, plus browser same-origin markers. The socket address is
1149
+ * authoritative; X-Forwarded-For is never trusted.
1150
+ */
1151
+ function isLoopbackRequest(request) {
1152
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
1153
+ const host = request.headers.host;
1154
+ if (typeof host !== "string") return false;
1155
+ let hostUrl;
1156
+ try {
1157
+ hostUrl = new URL("http://" + host);
1158
+ } catch {
1159
+ return false;
1160
+ }
1161
+ if (!isLoopbackHostname(hostUrl.hostname)) return false;
1162
+ if (request.headers["sec-fetch-site"] === "cross-site") return false;
1163
+ const origin = request.headers.origin;
1164
+ if (origin === void 0) return true;
1165
+ try {
1166
+ return new URL(origin).host === hostUrl.host;
1167
+ } catch {
1168
+ return false;
1169
+ }
1170
+ }
1171
+ //#endregion
1172
+ //#region src/host/routes.ts
1173
+ /** Route prefix the browser half mirrors. */
1174
+ const GATEWAY_PREFIX = "/api/plugin-manager";
1175
+ /** Cap on JSON request bodies (an install spec or a toggle is tiny). */
1176
+ const MAX_JSON_BODY_BYTES = 64 * 1024;
1177
+ /** Registry timeout for one update check. */
1178
+ const REGISTRY_TIMEOUT_MS = 3e4;
1179
+ /** Error text for a caught request or lifecycle failure. */
1180
+ function messageOf(error) {
1181
+ return error instanceof Error ? error.message : String(error);
1182
+ }
1183
+ /** Send one JSON response. */
1184
+ function sendJson(res, status, value) {
1185
+ const body = JSON.stringify(value);
1186
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
1187
+ res.end(body);
1188
+ }
1189
+ /** Read a bounded JSON request body; throws on oversized or invalid input. */
1190
+ async function readJsonBody(req) {
1191
+ const chunks = [];
1192
+ let size = 0;
1193
+ for await (const chunk of req) {
1194
+ const buffer = chunk;
1195
+ size += buffer.length;
1196
+ if (size > MAX_JSON_BODY_BYTES) throw new Error("plugin-manager: request body too large");
1197
+ chunks.push(buffer);
1198
+ }
1199
+ const text = Buffer.concat(chunks).toString("utf8");
1200
+ if (text.trim() === "") return {};
1201
+ const parsed = JSON.parse(text);
1202
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("plugin-manager: request body must be a JSON object");
1203
+ return parsed;
1204
+ }
1205
+ /** Default registry latest-version probe for npm packages. */
1206
+ async function fetchLatestFromRegistry(name) {
1207
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : name;
1208
+ const response = await fetch(`https://registry.npmjs.org/${encoded}/latest`, { signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS) });
1209
+ if (!response.ok) return void 0;
1210
+ const body = await response.json();
1211
+ return typeof body.version === "string" ? body.version : void 0;
1212
+ }
1213
+ /**
1214
+ * Build the gateway routes.
1215
+ * @param deps - profile facts, the CLI gateway, and seams.
1216
+ * @returns the web-server routes to register.
1217
+ */
1218
+ function makeGatewayRoutes(deps) {
1219
+ const { facts, gateway } = deps;
1220
+ const fetchLatest = deps.fetchLatest ?? fetchLatestFromRegistry;
1221
+ /** Wrap a handler with the loopback fence and JSON error reporting. */
1222
+ const guard = (handler) => async (req, res) => {
1223
+ if (!isLoopbackRequest(req)) {
1224
+ res.writeHead(403);
1225
+ res.end("forbidden");
1226
+ return;
1227
+ }
1228
+ try {
1229
+ await handler(req, res);
1230
+ } catch (error) {
1231
+ sendJson(res, 500, { error: messageOf(error) });
1232
+ }
1233
+ };
1234
+ const listHandler = async (req, res) => {
1235
+ const patchText = await readPatchText(facts.patchPath);
1236
+ sendJson(res, 200, { plugins: (await snapshotGateway(facts, patchText)).plugins });
1237
+ };
1238
+ const installHandler = async (req, res) => {
1239
+ const spec = (await readJsonBody(req))["spec"];
1240
+ if (typeof spec !== "string" || spec.trim() === "") {
1241
+ sendJson(res, 400, { error: "plugin-manager: install needs a spec" });
1242
+ return;
1243
+ }
1244
+ const unsafeSpec = unsafeSpecReason(spec.trim());
1245
+ if (unsafeSpec !== void 0) {
1246
+ sendJson(res, 400, { error: unsafeSpec });
1247
+ return;
1248
+ }
1249
+ if (!deps.cliAvailable()) {
1250
+ sendJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
1251
+ return;
1252
+ }
1253
+ sendJson(res, 200, gateway.install(spec.trim()));
1254
+ };
1255
+ const removeHandler = async (req, res) => {
1256
+ const id = (await readJsonBody(req))["id"];
1257
+ if (typeof id !== "string" || id.trim() === "") {
1258
+ sendJson(res, 400, { error: "plugin-manager: remove needs an id" });
1259
+ return;
1260
+ }
1261
+ const unsafeId = unsafeSpecReason(id.trim());
1262
+ if (unsafeId !== void 0) {
1263
+ sendJson(res, 400, { error: unsafeId });
1264
+ return;
1265
+ }
1266
+ if (!deps.cliAvailable()) {
1267
+ sendJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
1268
+ return;
1269
+ }
1270
+ sendJson(res, 200, gateway.remove(id.trim()));
1271
+ };
1272
+ const statusHandler = async (req, res) => {
1273
+ const jobId = new URL(req.url ?? "/", "http://localhost").searchParams.get("job");
1274
+ if (jobId === null) {
1275
+ sendJson(res, 400, { error: "plugin-manager: status needs a job id" });
1276
+ return;
1277
+ }
1278
+ const job = gateway.status(jobId);
1279
+ if (job === void 0) {
1280
+ sendJson(res, 404, { error: "plugin-manager: unknown job" });
1281
+ return;
1282
+ }
1283
+ sendJson(res, 200, { job });
1284
+ };
1285
+ const setEnabledHandler = async (req, res) => {
1286
+ const body = await readJsonBody(req);
1287
+ const id = body["id"];
1288
+ const enabled = body["enabled"];
1289
+ if (typeof id !== "string" || id.trim() === "" || typeof enabled !== "boolean") {
1290
+ sendJson(res, 400, { error: "plugin-manager: set-enabled needs an id and a boolean enabled" });
1291
+ return;
1292
+ }
1293
+ const target = id.trim();
1294
+ const unsafeTarget = unsafeSpecReason(target);
1295
+ if (unsafeTarget !== void 0) {
1296
+ sendJson(res, 400, { error: unsafeTarget });
1297
+ return;
1298
+ }
1299
+ const patchText = await readPatchText(facts.patchPath);
1300
+ const entries = (await readProfileManifest(facts.packageJsonPath)).dependencies[target] !== void 0 ? await claimedEntryRowsOf(facts, target) : [{
1301
+ id: target,
1302
+ name: target
1303
+ }];
1304
+ let next = patchText;
1305
+ for (const entry of entries) next = setRowEnabled(next, facts.patchPath, entry.id, entry.name, enabled);
1306
+ if (next !== patchText) await writePatchAtomic(facts.patchPath, next);
1307
+ sendJson(res, 200, { plugin: (await snapshotGateway(facts, next)).plugins.find((item) => item.id === target) ?? {
1308
+ id: target,
1309
+ name: target,
1310
+ version: "unknown",
1311
+ source: {
1312
+ kind: "npm",
1313
+ spec: target
1314
+ },
1315
+ installedAt: "",
1316
+ enabled
1317
+ } });
1318
+ };
1319
+ const failuresHandler = async (req, res) => {
1320
+ sendJson(res, 200, {
1321
+ items: [],
1322
+ pluginRoot: facts.profileDir,
1323
+ safeMode: false
1324
+ });
1325
+ };
1326
+ let modePromise;
1327
+ const probeOfficialChannels = () => {
1328
+ const binary = findDshBinary();
1329
+ if (binary === null) return Promise.resolve(false);
1330
+ return detectOfficialChannels(binary, facts.profileName);
1331
+ };
1332
+ const modeHandler = async (req, res) => {
1333
+ if (modePromise === void 0) modePromise = (deps.officialChannels ?? probeOfficialChannels)().then((official) => ({ official })).catch(() => ({ official: false }));
1334
+ sendJson(res, 200, await modePromise);
1335
+ };
1336
+ const checkUpdatesHandler = async (req, res) => {
1337
+ const patchText = await readPatchText(facts.patchPath);
1338
+ const snapshot = await snapshotGateway(facts, patchText);
1339
+ const updates = [];
1340
+ for (const plugin of snapshot.plugins) {
1341
+ if (plugin.source.kind !== "npm") continue;
1342
+ const latest = await fetchLatest(plugin.id).catch(() => void 0);
1343
+ if (latest !== void 0 && latest !== plugin.version) updates.push({
1344
+ id: plugin.id,
1345
+ current: plugin.version,
1346
+ latest
1347
+ });
1348
+ }
1349
+ sendJson(res, 200, { updates });
1350
+ };
1351
+ return [
1352
+ {
1353
+ kind: "exact",
1354
+ path: `${GATEWAY_PREFIX}/list`,
1355
+ handler: guard(listHandler)
1356
+ },
1357
+ {
1358
+ kind: "exact",
1359
+ path: `${GATEWAY_PREFIX}/install`,
1360
+ handler: guard(installHandler)
1361
+ },
1362
+ {
1363
+ kind: "exact",
1364
+ path: `${GATEWAY_PREFIX}/remove`,
1365
+ handler: guard(removeHandler)
1366
+ },
1367
+ {
1368
+ kind: "exact",
1369
+ path: `${GATEWAY_PREFIX}/status`,
1370
+ handler: guard(statusHandler)
1371
+ },
1372
+ {
1373
+ kind: "exact",
1374
+ path: `${GATEWAY_PREFIX}/set-enabled`,
1375
+ handler: guard(setEnabledHandler)
1376
+ },
1377
+ {
1378
+ kind: "exact",
1379
+ path: `${GATEWAY_PREFIX}/failures`,
1380
+ handler: guard(failuresHandler)
1381
+ },
1382
+ {
1383
+ kind: "exact",
1384
+ path: `${GATEWAY_PREFIX}/mode`,
1385
+ handler: guard(modeHandler)
1386
+ },
1387
+ {
1388
+ kind: "exact",
1389
+ path: `${GATEWAY_PREFIX}/check-updates`,
1390
+ handler: guard(checkUpdatesHandler)
1391
+ }
1392
+ ];
1393
+ }
1394
+ //#endregion
1395
+ //#region src/index.ts
1396
+ /** Stable cordis plugin name (matches cordis.patch.yml insert id). */
1397
+ const name = "ui-plugin-manager";
1398
+ /** Services the gateway needs — the web server seam. */
1399
+ const inject = ["webServer"];
1400
+ /** Apply the host half (once per process). */
1401
+ const apply = mountOnce("@linxin666/dsh-client-ui-plugin-manager", applyImpl);
1402
+ function applyImpl(ctx) {
1403
+ let facts;
1404
+ try {
1405
+ facts = resolveProfile();
1406
+ } catch (error) {
1407
+ console.error("[plugin-manager]", error instanceof Error ? error.message : String(error));
1408
+ return;
1409
+ }
1410
+ if (!profileExists(facts.profileDir)) return;
1411
+ const gateway = new CliGateway(facts);
1412
+ const cliAvailable = () => findDshBinary() !== null;
1413
+ ctx.effect(() => {
1414
+ const disposers = makeGatewayRoutes({
1415
+ facts,
1416
+ gateway,
1417
+ cliAvailable
1418
+ }).map((route) => ctx.webServer.register(route));
1419
+ return () => {
1420
+ for (const dispose of disposers) dispose();
1421
+ };
1422
+ }, "plugin-manager: gateway routes");
1423
+ }
1424
+ //#endregion
1425
+ export { apply, inject, name };