@linxin666/dsh-client-ui-plugin-manager 0.4.7 → 0.4.8

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 CHANGED
@@ -5,6 +5,7 @@ import { basename, dirname, isAbsolute, join, normalize, posix, sep, win32 } fro
5
5
  import { isMap, isScalar, isSeq, parseDocument } from "yaml";
6
6
  import { homedir } from "node:os";
7
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
8
+ import semver from "semver";
8
9
  import { AsyncResource } from "node:async_hooks";
9
10
  //#region src/mount-once.ts
10
11
  /**
@@ -319,6 +320,44 @@ function claimedIdsOf(patchText) {
319
320
  return ids;
320
321
  }
321
322
  /**
323
+ * Every entry id a layer declares: its top-level `- id:` rows (bare override
324
+ * rows and config rows alike) plus the entries of its `- insert:` lists. Ids
325
+ * nested inside a row's own `config:` are composition children of that entry,
326
+ * not layer entries, and are not declared here.
327
+ *
328
+ * This answers "does this layer still declare that row?" without composing, so
329
+ * it stays true in the states where a composition probe is not: a host that
330
+ * composes mid-upgrade, or while a bundle's package is being replaced, drops
331
+ * rows whose layers still exist.
332
+ * @param patchText - a patch layer's text.
333
+ * @param filename - absolute path (diagnostics only).
334
+ * @returns the declared ids, in file order, without duplicates.
335
+ * @throws when the layer does not parse; a caller must then treat this layer's
336
+ * declarations as unknown rather than empty.
337
+ */
338
+ function declaredRowIds(patchText, filename) {
339
+ const { root } = parsePatch(patchText, filename);
340
+ const ids = [];
341
+ const push = (value) => {
342
+ if (value === void 0 || ids.includes(value)) return;
343
+ ids.push(value);
344
+ };
345
+ const idOf = (node) => {
346
+ const id = node.get("id", true);
347
+ return isScalar(id) && typeof id.value === "string" ? id.value : void 0;
348
+ };
349
+ for (const item of root.items) {
350
+ if (!isMap(item)) continue;
351
+ const insert = item.get("insert", true);
352
+ if (isSeq(insert)) {
353
+ for (const entry of insert.items) if (isMap(entry)) push(idOf(entry));
354
+ continue;
355
+ }
356
+ push(idOf(item));
357
+ }
358
+ return ids;
359
+ }
360
+ /**
322
361
  * The insert entries of an installed package's own bundle patch, with both
323
362
  * the claimed id and the entry's own name. The name matters twice: the
324
363
  * loader imports the plugin by it (an unresolvable name is a boot failure),
@@ -506,6 +545,55 @@ function pruneOrphanRowOverrides(text, filename, composedIds) {
506
545
  function appendComment(first, second) {
507
546
  return second === void 0 || second === null || second === "" ? first : `${first}\n${second}`;
508
547
  }
548
+ /**
549
+ * Point the profile's own rows at the packages that now carry those entry ids.
550
+ *
551
+ * The include patch semantics skip a row whose `name` does not match the name
552
+ * of the row a bundle inserted under that id, and the skip takes the whole row
553
+ * with it: a config row stops configuring anything and a `disabled` override
554
+ * stops disabling anything, both without a word in the browser. A package that
555
+ * changes its name — the aggregate's family rows moved from the
556
+ * `@linxin666/dsh-web-all/<family>` subpath to the real package in issue
557
+ * #1901 — therefore leaves every profile row that named it dead.
558
+ *
559
+ * The live names come from the installed bundles' own patch files, which is
560
+ * where the loader takes the row it inserts, so a repaired row names exactly
561
+ * the package the loader mounts under that id. A row whose id no bundle claims
562
+ * is left alone: its package may still be carried by a layer this manager
563
+ * cannot see, and a name it cannot prove is a name it must not write.
564
+ *
565
+ * @param text - current patch file text.
566
+ * @param filename - absolute path (diagnostics only).
567
+ * @param liveNames - the live entry names, by entry id.
568
+ * @returns the rewritten text and the repaired rows.
569
+ */
570
+ function repairStaleRowNames(text, filename, liveNames) {
571
+ const { document, root } = parsePatch(text, filename);
572
+ const repaired = [];
573
+ for (const item of root.items) {
574
+ if (!isBareRow(item)) continue;
575
+ const id = bareRowId(item);
576
+ const from = bareRowName(item);
577
+ if (id === void 0 || from === void 0) continue;
578
+ const to = liveNames.get(id);
579
+ if (to === void 0 || to === from) continue;
580
+ item.set("name", document.createNode(to));
581
+ repaired.push({
582
+ id,
583
+ from,
584
+ to
585
+ });
586
+ }
587
+ if (repaired.length === 0) return {
588
+ text,
589
+ repaired
590
+ };
591
+ const serialized = document.toString({ lineWidth: 0 });
592
+ return {
593
+ text: `${serialized.endsWith("\n") ? serialized.slice(0, -1) : serialized}${text.endsWith("\n") ? "\n" : ""}`,
594
+ repaired
595
+ };
596
+ }
509
597
  //#endregion
510
598
  //#region src/host/bundle-guard.ts
511
599
  /**
@@ -916,19 +1004,22 @@ function profileExists(profileDir) {
916
1004
  */
917
1005
  /**
918
1006
  * Entry rows that must never carry a disabled override: the manager tab
919
- * itself (the UI performing the write), the family settings surface the tab
920
- * injects into, and the aggregate compat face (disabling it unmounts the
921
- * whole folded client bundle while host rows keep running — a half-dead
922
- * page). Covers both the standalone and the aggregate row ids. The standalone
923
- * id is this package's own `cordis.patch.yml` insert id, never the official
924
- * `ui-plugin-manager` row the DSH web-app bundle already claims.
1007
+ * itself (the UI performing the write) and the family settings surface the
1008
+ * tab injects into. Covers both the standalone and the aggregate row ids. The
1009
+ * standalone id is this package's own `cordis.patch.yml` insert id, never the
1010
+ * official `ui-plugin-manager` row the DSH web-app bundle already claims.
1011
+ *
1012
+ * `web-ui-compat` is deliberately NOT locked (issue #1901). It used to be:
1013
+ * the compat row carried the inlined browser half of every family, so
1014
+ * disabling it blanked the whole page while the host rows kept running. Family
1015
+ * rows mount their own packages now, and the compat row is the optional
1016
+ * compatibility patch layer the issue asks users to be able to turn off.
925
1017
  */
926
1018
  const LOCKED_ENTRY_IDS = /* @__PURE__ */ new Set([
927
1019
  "ui-plugin-manager-update-check",
928
1020
  "web-ui-plugin-manager",
929
1021
  "ui-web-ui-settings",
930
- "web-ui-settings",
931
- "web-ui-compat"
1022
+ "web-ui-settings"
932
1023
  ]);
933
1024
  /** The node_modules path of one (possibly scoped) package name. */
934
1025
  function modulePathOf(profileDir, name) {
@@ -2129,6 +2220,21 @@ var CliGateway = class {
2129
2220
  * A failed second phase reinstalls the spec the profile carried before the run,
2130
2221
  * so an update that cannot land leaves a working plugin behind instead of an
2131
2222
  * empty slot; the report says which of the two happened.
2223
+ *
2224
+ * Two facts make the replacement safe to repeat in one session:
2225
+ *
2226
+ * - **The bundle keeps its layer index.** A removal drops the name from
2227
+ * `dsh.profile.bundles` and the reinstall appends it, so a plain
2228
+ * remove-then-install moves the bundle behind every bundle that followed it
2229
+ * and its patch layer starts overriding rows it never overrode
2230
+ * ({@link restoreBundleIndex} puts it back).
2231
+ * - **A `bundle-in-use` refusal is answered once, not repeated.** The
2232
+ * official guard deselects the bundle and reloads before it checks whether
2233
+ * the bundle's rows still run, so a refusal means the session still holds
2234
+ * them: the update is retried exactly once against that settled state, and a
2235
+ * second refusal restores the selection and names the restart the person has
2236
+ * to do ({@link removeForReplacement}).
2237
+ *
2132
2238
  * @param job - the update job whose spec is installed.
2133
2239
  * @param native - the official manager.
2134
2240
  * @param targetId - the installed bundle being replaced.
@@ -2137,20 +2243,124 @@ var CliGateway = class {
2137
2243
  */
2138
2244
  async replaceInstalled(job, native, targetId, previousSpec) {
2139
2245
  if (previousSpec === void 0) return `${targetId} 不在 profile 依赖中,无法替换已安装版本`;
2140
- const removalFailure = nativeManagerFailure(await native.removeBundle(targetId));
2141
- if (removalFailure !== void 0) return `已安装版本无法移除(${removalFailure}),本次更新未做改动`;
2246
+ const index = await this.bundleIndexOf(targetId);
2247
+ const removal = await this.removeForReplacement(native, targetId);
2248
+ if (removal.failure !== void 0) {
2249
+ if (removal.deselected) await this.restoreBundleSelection(native, targetId);
2250
+ return `已安装版本无法移除(${removal.failure}),本次更新未做改动${removal.remedy}`;
2251
+ }
2142
2252
  const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
2143
2253
  enabled: true,
2144
2254
  requestId: job.id
2145
2255
  }));
2146
- if (refusal === void 0) return void 0;
2256
+ if (refusal === void 0) {
2257
+ await this.restoreBundleIndex(targetId, previousSpec, index);
2258
+ return;
2259
+ }
2147
2260
  const restoreSpec = `${targetId}@${previousSpec}`;
2148
2261
  const restoreFailure = nativeManagerFailure(await native.installBundle(restoreSpec, {
2149
2262
  enabled: true,
2150
2263
  requestId: job.id
2151
2264
  }));
2152
- if (restoreFailure === void 0) return `${refusal};已装回 ${restoreSpec}`;
2153
- return `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`;
2265
+ if (restoreFailure !== void 0) return `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`;
2266
+ await this.restoreBundleIndex(targetId, previousSpec, index);
2267
+ return `${refusal};已装回 ${restoreSpec}`;
2268
+ }
2269
+ /**
2270
+ * Where a bundle sits in the layer order, read before the removal drops it.
2271
+ * @param name - the installed bundle name.
2272
+ * @returns the index in `dsh.profile.bundles`, or undefined when the profile
2273
+ * does not list it (nothing to restore in that case).
2274
+ */
2275
+ async bundleIndexOf(name) {
2276
+ try {
2277
+ const index = (await readProfileManifest(this.facts.packageJsonPath)).bundles.indexOf(name);
2278
+ return index < 0 ? void 0 : index;
2279
+ } catch {
2280
+ return;
2281
+ }
2282
+ }
2283
+ /**
2284
+ * Put a replaced bundle back at the layer index it had before the removal.
2285
+ *
2286
+ * The loader applies one patch layer per entry of `dsh.profile.bundles`, in
2287
+ * that order, so the index is behavior: a bundle that is removed and
2288
+ * reinstalled without this lands behind every bundle that followed it, and
2289
+ * whole rows start inheriting from a layer that used to come first. The write
2290
+ * is the manifest's own backup + tmp + rename path, and nothing is written
2291
+ * when the profile already lists the bundle where it belongs.
2292
+ * @param name - the reinstalled bundle.
2293
+ * @param spec - the dependency spec the reinstall recorded (unused when the bundle is absent).
2294
+ * @param index - the position captured before the removal.
2295
+ */
2296
+ async restoreBundleIndex(name, spec, index) {
2297
+ if (index === void 0) return;
2298
+ try {
2299
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
2300
+ if (!Object.hasOwn(manifest.dependencies, name)) return;
2301
+ if (manifest.bundles.indexOf(name) === index) return;
2302
+ await reorderProfileBundle(this.facts.packageJsonPath, name, index);
2303
+ } catch (error) {
2304
+ console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 顺序(${spec}):${error instanceof Error ? error.message : String(error)}`);
2305
+ }
2306
+ }
2307
+ /**
2308
+ * Remove a bundle for the two-phase replacement, answering the official
2309
+ * manager's in-use refusal instead of repeating it.
2310
+ *
2311
+ * Read the official `removeBundle` guard in order: it deselects the bundle,
2312
+ * reloads the profile, and only then checks whether the bundle's own rows
2313
+ * still hold a running fiber, which it reports as `bundle-in-use`. The
2314
+ * deselection is therefore already on disk when the refusal arrives — the
2315
+ * guard re-reads the selection on entry, so asking once more after that
2316
+ * settled state is idempotent and is the only way an update can continue
2317
+ * without a restart. A second refusal means the rows really are still
2318
+ * loaded, and the report then names the restart instead of a bare code.
2319
+ * @param native - the official manager.
2320
+ * @param name - the bundle to remove.
2321
+ * @returns the refusal to report, whether the profile lost the selection on the
2322
+ * way, and the remedy text for that refusal.
2323
+ */
2324
+ async removeForReplacement(native, name) {
2325
+ const first = await native.removeBundle(name);
2326
+ const failure = nativeManagerFailure(first);
2327
+ if (failure === void 0) return {
2328
+ deselected: false,
2329
+ remedy: ""
2330
+ };
2331
+ if (nativeManagerRefusalCode(first) !== "bundle-in-use") return {
2332
+ failure,
2333
+ deselected: await this.bundleSelectionLost(name),
2334
+ remedy: ""
2335
+ };
2336
+ const retryFailure = nativeManagerFailure(await native.removeBundle(name));
2337
+ if (retryFailure === void 0) return {
2338
+ deselected: false,
2339
+ remedy: ""
2340
+ };
2341
+ return {
2342
+ failure: retryFailure,
2343
+ deselected: await this.bundleSelectionLost(name),
2344
+ remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可"
2345
+ };
2346
+ }
2347
+ /** Whether a bundle is still an installed dependency but no longer selected. */
2348
+ async bundleSelectionLost(name) {
2349
+ try {
2350
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
2351
+ return Object.hasOwn(manifest.dependencies, name) && !manifest.bundles.includes(name);
2352
+ } catch {
2353
+ return false;
2354
+ }
2355
+ }
2356
+ /** Put a selection back after a refused removal, so the profile is as it was found. */
2357
+ async restoreBundleSelection(native, name) {
2358
+ if (native.setBundleEnabled === void 0) return;
2359
+ try {
2360
+ await native.setBundleEnabled(name, true);
2361
+ } catch (error) {
2362
+ console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 启用状态:${error instanceof Error ? error.message : String(error)}`);
2363
+ }
2154
2364
  }
2155
2365
  /** Start a deterministic legacy aggregate migration. */
2156
2366
  migrate(sourceId, targetId, targetVersion, targetSpec) {
@@ -2483,14 +2693,133 @@ var CliGateway = class {
2483
2693
  }
2484
2694
  }
2485
2695
  /**
2696
+ * The entry ids a user-layer override may still point at: the composed ids
2697
+ * plus every id the profile's own bundle layers still declare.
2698
+ *
2699
+ * The composition alone does not prove a row is retired. A host that
2700
+ * composes while a bundle is being replaced — the remove-then-install half of
2701
+ * an application-owned update, or an upgrade whose packages are half
2702
+ * installed — composes *without* the rows of the bundle that is momentarily
2703
+ * gone, and pruning on that probe deletes the user's override for a row that
2704
+ * still exists (0.4.7 lost `web-ui-remote-web-ui` and `ui-schedule` this
2705
+ * way). Declarations live in the bundle layers, so they survive that window.
2706
+ * @param composed - the entry ids of the composition probe.
2707
+ * @returns the ids to keep, or undefined when a declared layer cannot be
2708
+ * read, which proves nothing either way and must leave the file alone.
2709
+ */
2710
+ async liveOverrideIds(composed) {
2711
+ const live = new Set(composed);
2712
+ let manifest;
2713
+ try {
2714
+ manifest = await readProfileManifest(this.facts.packageJsonPath);
2715
+ } catch {
2716
+ return;
2717
+ }
2718
+ for (const name of manifest.bundles) {
2719
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2720
+ try {
2721
+ await readFile(join(dir, "package.json"), "utf8");
2722
+ } catch {
2723
+ return;
2724
+ }
2725
+ let text;
2726
+ try {
2727
+ text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
2728
+ } catch (error) {
2729
+ if (error.code === "ENOENT") continue;
2730
+ return;
2731
+ }
2732
+ try {
2733
+ for (const id of declaredRowIds(text, join(dir, "cordis.patch.yml"))) live.add(id);
2734
+ } catch {
2735
+ return;
2736
+ }
2737
+ }
2738
+ return live;
2739
+ }
2740
+ /**
2741
+ * The entry names the installed bundles' own rows carry, by entry id.
2742
+ *
2743
+ * The loader inserts one row per id and takes that row's name from the
2744
+ * bundle's own patch file, so this map is the very fact the loader composes:
2745
+ * a profile row naming something else is a row the loader skips.
2746
+ *
2747
+ * @returns the live names, or undefined when a bundle's patch cannot be read
2748
+ * (which proves nothing either way and must leave the profile alone).
2749
+ */
2750
+ async liveEntryNames() {
2751
+ const names = /* @__PURE__ */ new Map();
2752
+ let manifest;
2753
+ try {
2754
+ manifest = await readProfileManifest(this.facts.packageJsonPath);
2755
+ } catch {
2756
+ return;
2757
+ }
2758
+ for (const name of manifest.bundles) {
2759
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2760
+ let text;
2761
+ try {
2762
+ text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
2763
+ } catch (error) {
2764
+ if (error.code === "ENOENT") continue;
2765
+ return;
2766
+ }
2767
+ for (const row of insertRowsOf(text)) {
2768
+ if (row.id === void 0 || row.name === void 0) continue;
2769
+ names.set(row.id, row.name);
2770
+ }
2771
+ }
2772
+ return names;
2773
+ }
2774
+ /**
2775
+ * Point the profile's own rows at the packages that now carry those entry ids.
2776
+ *
2777
+ * A bundle that renames a row's package leaves every profile row that named
2778
+ * the old one dead: the include patch semantics skip a row whose name does
2779
+ * not match the inserted row, and the skip takes the whole row with it — a
2780
+ * config row stops configuring and a `disabled` override stops disabling,
2781
+ * both without a word in the browser. Issue #1901 moved the aggregate's
2782
+ * family rows from the `@linxin666/dsh-web-all/<family>` subpath to the
2783
+ * real package, so every profile row written before that upgrade went dead
2784
+ * with it.
2785
+ *
2786
+ * The repair is idempotent and writes only when a row actually changed, so a
2787
+ * healthy profile is never rewritten.
2788
+ *
2789
+ * @returns the repaired rows, in file order.
2790
+ */
2791
+ async repairProfileRowNames() {
2792
+ const names = await this.liveEntryNames();
2793
+ if (names === void 0 || names.size === 0) return [];
2794
+ let text;
2795
+ try {
2796
+ text = await readFile(this.facts.patchPath, "utf8");
2797
+ } catch {
2798
+ return [];
2799
+ }
2800
+ let repaired;
2801
+ try {
2802
+ repaired = repairStaleRowNames(text, this.facts.patchPath, names);
2803
+ } catch {
2804
+ return [];
2805
+ }
2806
+ if (repaired.repaired.length === 0) return [];
2807
+ await writePatchAtomic(this.facts.patchPath, repaired.text);
2808
+ return repaired.repaired;
2809
+ }
2810
+ /**
2486
2811
  * Post-update orphan guard: drop this package's own enablement overrides
2487
- * whose entry id the composed *target* profile no longer carries. The
2488
- * authority is the loader's own composition after the update
2489
- * ({@link composedEntryIdsOf}), not the profile patch and not the source
2490
- * profile: an override is only orphaned once the target composition stops
2491
- * declaring that id, and ids the official base or another bundle still
2492
- * mounts stay valid. A retired row would otherwise leave a stale override
2493
- * that the loader reports on every boot as `patch: entry "<id>" not found`.
2812
+ * whose entry id neither the composed *target* profile nor any bundle layer
2813
+ * still declares. The composition is the loader's own after the update
2814
+ * ({@link composedEntryIdsOf}), widened by the bundle layers' declarations
2815
+ * ({@link liveOverrideIds}) because a composition taken mid-upgrade omits
2816
+ * rows that still exist. A retired row would otherwise leave a stale
2817
+ * override that the loader reports on every boot as
2818
+ * `patch: entry "<id>" not found`.
2819
+ *
2820
+ * The stale-row-name repair ({@link repairProfileRowNames}) runs first and
2821
+ * on its own authority, so a profile whose bundle declarations cannot be
2822
+ * resolved is repaired even though the prune then writes nothing.
2494
2823
  *
2495
2824
  * Nothing is written when nothing is orphaned — a second run over a pruned
2496
2825
  * profile returns the input text untouched, so no write and no second backup
@@ -2503,10 +2832,18 @@ var CliGateway = class {
2503
2832
  * @returns the pruned entry ids, or undefined when the job failed.
2504
2833
  */
2505
2834
  async pruneOrphanOverrides(job, dumpText) {
2835
+ try {
2836
+ const repaired = await this.repairProfileRowNames();
2837
+ if (repaired.length > 0) console.warn("[plugin-manager] 已修复 profile 中失效的行名:" + repaired.map((row) => `${row.id}(${row.from} → ${row.to})`).join("、"));
2838
+ } catch (error) {
2839
+ console.warn("[plugin-manager] profile 行名修复失败:" + (error instanceof Error ? error.message : String(error)));
2840
+ }
2506
2841
  const dump = dumpText ?? await this.compositionOf();
2507
2842
  if (dump === void 0) return [];
2508
2843
  const composed = composedEntryIdsOf(dump);
2509
2844
  if (composed === void 0) return [];
2845
+ const live = await this.liveOverrideIds(composed);
2846
+ if (live === void 0) return [];
2510
2847
  let text;
2511
2848
  try {
2512
2849
  text = await readFile(this.facts.patchPath, "utf8");
@@ -2515,7 +2852,7 @@ var CliGateway = class {
2515
2852
  }
2516
2853
  let pruned;
2517
2854
  try {
2518
- pruned = pruneOrphanRowOverrides(text, this.facts.patchPath, composed);
2855
+ pruned = pruneOrphanRowOverrides(text, this.facts.patchPath, live);
2519
2856
  } catch {
2520
2857
  return [];
2521
2858
  }
@@ -2767,12 +3104,26 @@ function isLoopbackHostname(hostname) {
2767
3104
  return isIPv4Loopback(hostname);
2768
3105
  }
2769
3106
  /**
3107
+ * Whether a reverse proxy stood between the client and this host: the request
3108
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
3109
+ * hop that forwards traffic, so the request did not originate on this machine.
3110
+ * @param request - node HTTP request.
3111
+ * @returns true when a forwarding header is present.
3112
+ */
3113
+ function isProxiedRequest(request) {
3114
+ return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
3115
+ }
3116
+ /**
2770
3117
  * Request-level trust fence: a loopback socket address AND a loopback Host
2771
3118
  * header, plus browser same-origin markers. The socket address is
2772
- * authoritative; X-Forwarded-For is never trusted.
3119
+ * authoritative for a direct connection; a request that carries a forwarding
3120
+ * header is refused outright, because a proxy in front of the host makes both
3121
+ * the socket address and the Host header describe the proxy rather than the
3122
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
2773
3123
  */
2774
3124
  function isLoopbackRequest(request) {
2775
3125
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
3126
+ if (isProxiedRequest(request)) return false;
2776
3127
  const host = request.headers.host;
2777
3128
  if (typeof host !== "string") return false;
2778
3129
  let hostUrl;
@@ -2812,62 +3163,6 @@ function parseDshVersion(value) {
2812
3163
  };
2813
3164
  }
2814
3165
  /**
2815
- * Compare two version strings by semver order (a release is newer than any
2816
- * prerelease of the same tuple).
2817
- * @returns -1 / 0 / 1, or undefined when either side is malformed.
2818
- */
2819
- function compareVersions(left, right) {
2820
- const a = parseDshVersion(left);
2821
- const b = parseDshVersion(right);
2822
- if (a === void 0 || b === void 0) return void 0;
2823
- for (const key of [
2824
- "major",
2825
- "minor",
2826
- "patch"
2827
- ]) if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1;
2828
- return comparePrerelease(a.prerelease, b.prerelease);
2829
- }
2830
- /**
2831
- * Semver prerelease ordering: numeric identifiers compare numerically,
2832
- * numeric identifiers rank below alphanumeric ones, alphanumeric identifiers
2833
- * compare lexically, and a longer list wins when the shared prefix is equal.
2834
- */
2835
- function comparePrerelease(left, right) {
2836
- if (left.length === 0 && right.length === 0) return 0;
2837
- if (left.length === 0) return 1;
2838
- if (right.length === 0) return -1;
2839
- const length = Math.max(left.length, right.length);
2840
- for (let index = 0; index < length; index += 1) {
2841
- const a = left[index];
2842
- const b = right[index];
2843
- if (a === void 0) return -1;
2844
- if (b === void 0) return 1;
2845
- if (typeof a === "number" && typeof b === "number") {
2846
- if (a !== b) return a < b ? -1 : 1;
2847
- } else if (typeof a === "number") return -1;
2848
- else if (typeof b === "number") return 1;
2849
- else if (a !== b) return a < b ? -1 : 1;
2850
- }
2851
- return 0;
2852
- }
2853
- const MINIMUM_RANGE_PATTERN = /^>=\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/;
2854
- /**
2855
- * Whether a host version satisfies a declared `>=X.Y.Z[-prerelease]` minimum.
2856
- * @param host - the running DSH host version.
2857
- * @param minimum - the declared minimum; any form other than `>=<semver>`
2858
- * (plain semver, `^`, `~`, multi-comparator ranges, empty) returns undefined.
2859
- * @returns true / false, or undefined when the host version is malformed or
2860
- * the minimum uses an unsupported form — callers treat undefined as
2861
- * "cannot verify" and fail closed for declared requirements.
2862
- */
2863
- function meetsMinimumDsh(host, minimum) {
2864
- const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim());
2865
- if (match === null) return void 0;
2866
- const compared = compareVersions(host, match[1]);
2867
- if (compared === void 0) return void 0;
2868
- return compared >= 0;
2869
- }
2870
- /**
2871
3166
  * Read the declared DSH minimum from a published registry manifest:
2872
3167
  * `dsh.engines.dsh` first, top-level `engines.dsh` next, and
2873
3168
  * `peerDependencies["@deepseek-ai/dsh"]` last, which is where a package that
@@ -2885,6 +3180,40 @@ function dshRequirementOf(manifest) {
2885
3180
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
2886
3181
  }
2887
3182
  //#endregion
3183
+ //#region src/host/dsh-compat.ts
3184
+ /**
3185
+ * The DSH runtime compatibility verdict for one declared plugin requirement,
3186
+ * evaluated the way the official boot gate evaluates it
3187
+ * (`evaluatePluginCompatibility` in app-boot's `plugin-compatibility.ts`):
3188
+ * the requirement is a node-semver range and the host satisfies it when
3189
+ * `semver.satisfies(host, range, { includePrerelease: true })` holds. Every
3190
+ * legal range form therefore decides: `||` alternatives, `^` and `~`,
3191
+ * whitespace-separated comparators, x-ranges, and prerelease tags compared as
3192
+ * ordinary versions.
3193
+ *
3194
+ * The requirement itself comes from `dshRequirementOf` in
3195
+ * `../core/version.ts`, which owns the field priority (this module only
3196
+ * decides the verdict). Host-only on purpose: `semver` is a node package and
3197
+ * must never be reachable from the browser half, which renders the same
3198
+ * declaration through the regex-only `displayMinimumVersion`.
3199
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
3200
+ */
3201
+ /**
3202
+ * Decide whether the running DSH host satisfies a declared requirement range.
3203
+ * @param host - the running DSH host version.
3204
+ * @param range - the declared requirement, in any node-semver range form.
3205
+ * @returns `satisfied` when the host satisfies the declaration,
3206
+ * `host-too-low` when it was compared and does not, and `unverifiable` when
3207
+ * no comparison could be made. Callers fail closed on the last two (issue
3208
+ * #754) but must not describe them with the same words.
3209
+ */
3210
+ function evaluateDshCompatibility(host, range) {
3211
+ if (range.trim() === "") return { verdict: "unverifiable" };
3212
+ if (semver.validRange(range) === null) return { verdict: "unverifiable" };
3213
+ if (semver.valid(host) === null) return { verdict: "unverifiable" };
3214
+ return semver.satisfies(host, range, { includePrerelease: true }) ? { verdict: "satisfied" } : { verdict: "host-too-low" };
3215
+ }
3216
+ //#endregion
2888
3217
  //#region src/host/legacy-migration.ts
2889
3218
  /**
2890
3219
  * Deterministic mapping for the dsh-web aggregate package rename.
@@ -2985,6 +3314,25 @@ const DETACHED = new AsyncResource("dsh-web:detached-work", { triggerAsyncId: 0
2985
3314
  function runDetached(work) {
2986
3315
  return DETACHED.runInAsyncScope(work);
2987
3316
  }
3317
+ /**
3318
+ * Environment marker a Desktop shell sets when it guarantees that a host which
3319
+ * exits is replaced by a fresh host (rather than reported as stopped).
3320
+ *
3321
+ * The packaged Desktop shell owns the process tree but has no obligation to
3322
+ * respawn it: the shipped shell in this repository's compat matrix answers a
3323
+ * host exit with `desktop host stopped` and an error page. Stopping ourselves
3324
+ * under such a shell turns the restart button into "kill the app", so the mode
3325
+ * requires proof of the opposite behaviour.
3326
+ */
3327
+ const SHELL_RESTART_CAPABILITY_ENV = "DSH_SHELL_RESTARTS_HOST";
3328
+ /**
3329
+ * Whether the launching shell promises to bring the host back after it exits.
3330
+ * @param env - the environment the host was launched with.
3331
+ * @returns true only for an opt-in marker value of `1`.
3332
+ */
3333
+ function shellRestartIsSupported(env) {
3334
+ return env[SHELL_RESTART_CAPABILITY_ENV] === "1";
3335
+ }
2988
3336
  /** How long the helper waits for this process to disappear before giving up on the wait. */
2989
3337
  const RESTART_WAIT_MS = 3e4;
2990
3338
  /** Exit/interpreter arguments a relaunch must not repeat (they re-bind fixed ports). */
@@ -2997,7 +3345,7 @@ function isReusableExecArg(argument) {
2997
3345
  * @returns the planned mode, with the relaunch command when one is used.
2998
3346
  */
2999
3347
  function planRestart(facts) {
3000
- if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return { mode: "shell" };
3348
+ if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return shellRestartIsSupported(facts.env) ? { mode: "shell" } : { mode: "manual" };
3001
3349
  if (!facts.interactive) return { mode: "manual" };
3002
3350
  const script = facts.argv[0];
3003
3351
  if (script === void 0 || script === "") return { mode: "manual" };
@@ -3284,17 +3632,27 @@ function makeGatewayRoutes(deps) {
3284
3632
  return dshVersionPending;
3285
3633
  };
3286
3634
  /**
3287
- * Compat verdict for one declared requirement. Unverified (unknown host,
3288
- * malformed host output, unsupported range) is incompatible so an update
3289
- * can never run against a runtime we cannot prove compatible (issue #754);
3290
- * only absent metadata keeps the update fail-open.
3635
+ * Compat verdict for one declared requirement, plus the running version the
3636
+ * verdict was made from. Unverified (unknown host, malformed host output, a
3637
+ * range node-semver rejects) is incompatible so an update can never run
3638
+ * against a runtime we cannot prove compatible (issue #754); only absent
3639
+ * metadata keeps the update fail-open.
3640
+ *
3641
+ * `hostVersion` is reported only for a verdict that really compared the
3642
+ * running version and lost it. Its absence is the wire's way of saying "this
3643
+ * declaration could not be checked", which is what the browser reads to tell
3644
+ * "your DSH is too old" from "we could not verify" (issues #1819 and #1899):
3645
+ * a blocked row with no version must never be described as below the
3646
+ * minimum, because nothing was compared.
3291
3647
  */
3292
3648
  const compatibleVerdict = async (requiresDsh) => {
3293
3649
  const hostVersion = await resolveDshVersion();
3294
3650
  if (hostVersion === void 0) return { compatible: false };
3651
+ const compatibility = evaluateDshCompatibility(hostVersion, requiresDsh);
3652
+ if (compatibility.verdict === "unverifiable") return { compatible: false };
3295
3653
  return {
3296
3654
  hostVersion,
3297
- compatible: meetsMinimumDsh(hostVersion, requiresDsh) === true
3655
+ compatible: compatibility.verdict === "satisfied"
3298
3656
  };
3299
3657
  };
3300
3658
  /** Wrap a handler with the loopback fence and JSON error reporting. */
@@ -3398,7 +3756,7 @@ function makeGatewayRoutes(deps) {
3398
3756
  const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
3399
3757
  if (!compatible) return {
3400
3758
  status: 412,
3401
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to}; check the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
3759
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
3402
3760
  };
3403
3761
  }
3404
3762
  return {
@@ -3434,7 +3792,7 @@ function makeGatewayRoutes(deps) {
3434
3792
  const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
3435
3793
  if (!compatible) return {
3436
3794
  status: 412,
3437
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target}; check the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
3795
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
3438
3796
  };
3439
3797
  }
3440
3798
  return {
@@ -3747,6 +4105,19 @@ function applyImpl(ctx) {
3747
4105
  for (const dispose of disposers) dispose();
3748
4106
  };
3749
4107
  }, "plugin-manager: gateway routes");
4108
+ ctx.effect(() => {
4109
+ const timer = setTimeout(() => {
4110
+ gateway.repairProfileRowNames().then((repaired) => {
4111
+ if (repaired.length === 0) return;
4112
+ console.warn("[plugin-manager] 已修复 profile 中失效的行名:" + repaired.map((row) => `${row.id}(${row.from} → ${row.to})`).join("、"));
4113
+ }).catch((error) => {
4114
+ console.error("[plugin-manager] profile 行名修复失败:" + (error instanceof Error ? error.message : String(error)));
4115
+ });
4116
+ }, 1500);
4117
+ return () => {
4118
+ clearTimeout(timer);
4119
+ };
4120
+ }, "plugin-manager: stale row name repair");
3750
4121
  }
3751
4122
  //#endregion
3752
4123
  export { apply, inject, name };