@deepseek-ai/dsh-plugin-manager 0.2.1-rc.5 → 0.2.2-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.i18n.yaml +13 -10
  2. package/README.md +43 -8
  3. package/README.zh.md +43 -8
  4. package/lib/index.js +974 -139
  5. package/lib/typert.host.js +513 -55
  6. package/lib/typert.remote-client.d.ts +11 -1
  7. package/lib/typert.remote-client.js +411 -48
  8. package/lib/types/build-approval.d.ts +5 -5
  9. package/lib/types/build-approval.js +23 -10
  10. package/lib/types/bundle-detail.d.ts +40 -0
  11. package/lib/types/bundle-detail.js +85 -0
  12. package/lib/types/diagnostic.d.ts +17 -0
  13. package/lib/types/diagnostic.js +72 -0
  14. package/lib/types/git-transport.d.ts +27 -0
  15. package/lib/types/git-transport.js +65 -0
  16. package/lib/types/github-connection.d.ts +15 -3
  17. package/lib/types/github-connection.js +13 -3
  18. package/lib/types/index.d.ts +91 -2
  19. package/lib/types/index.js +530 -101
  20. package/lib/types/install-failure.js +1 -1
  21. package/lib/types/install-spec.d.ts +2 -0
  22. package/lib/types/install-spec.js +1 -1
  23. package/lib/types/operations.d.ts +5 -1
  24. package/lib/types/operations.js +31 -6
  25. package/lib/types/tools.js +5 -1
  26. package/lib/types/types.d.ts +169 -7
  27. package/lib/types/versions.d.ts +40 -0
  28. package/lib/types/versions.js +61 -0
  29. package/locale/de.json +6 -0
  30. package/locale/es.json +6 -0
  31. package/locale/fr.json +6 -0
  32. package/locale/ja.json +6 -0
  33. package/locale/pt.json +6 -0
  34. package/locale/ru.json +6 -0
  35. package/locale/tools/de.json +5 -0
  36. package/locale/tools/es.json +5 -0
  37. package/locale/tools/fr.json +5 -0
  38. package/locale/tools/ja.json +5 -0
  39. package/locale/tools/pt.json +5 -0
  40. package/locale/tools/ru.json +5 -0
  41. package/package.json +48 -34
package/lib/index.js CHANGED
@@ -5,14 +5,102 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
7
7
  import z from "@deepseek-ai/schemastery";
8
- import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
8
+ import semver from "semver";
9
+ import { Remote, RemoteError, TypertRemoteService, remoteErrorOf } from "@deepseek-ai/dsh-typert-protocol";
10
+ import { DetailFailure, NPM_FILE_SOURCES, detailImage, detailImageResponse, languageChain, localFiles, npmFileSourceOrder, npmFiles, readPackageDocument } from "@deepseek-ai/dsh-plugin-detail";
11
+ import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
12
+ import { PROFILE_COMPATIBILITY_FILENAME, ResolutionRestartRequired, UnsupportedBundlePlatformError, assertBundlePlatform, bundlePatchPaths, composeEntries, evaluatePluginCompatibility, getDshRuntimeVersion, loadOptionalPatches, loadOverlayPatches, pluginCompatibilityWarning, readBundlePatches, readPluginMeta, readProfileCompatibility, readProfileManifest, readProfilePatches, readProfileVersionExemptions, resolveBundleDir, resolveProfileDir, setProfileVersionExemption, validatePluginVersionExemption } from "@deepseek-ai/dsh-app-boot";
9
13
  import { pluginEntryId, readPluginInventory } from "@deepseek-ai/dsh-host-plugin-inventory";
10
- import { OFFICIAL_ON_DEMAND_CATALOG, OPTIONAL_BUNDLES, PROFILE_COMPATIBILITY_FILENAME, ResolutionRestartRequired, bundlePatchPaths, composeEntries, evaluatePluginCompatibility, getDshRuntimeVersion, loadOptionalPatches, loadOverlayPatches, pluginCompatibilityWarning, readBundlePatches, readPluginMeta, readProfileCompatibility, readProfileManifest, readProfilePatches, readProfileVersionExemptions, resolveBundleDir, resolveProfileDir, setProfileVersionExemption } from "@deepseek-ai/dsh-app-boot";
14
+ import { OFFICIAL_ON_DEMAND_CATALOG, OPTIONAL_BUNDLES, PROTECTED_PLUGINS } from "@deepseek-ai/dsh-official-bundles";
11
15
  import { once } from "node:events";
12
16
  import { execa } from "execa";
13
17
  import { scrubbedParentEnv } from "@deepseek-ai/dsh-subprocess";
14
18
  import { homedir } from "node:os";
15
19
  import { isAlias, isMap, isNode, isScalar, isSeq, parseDocument, visit } from "yaml";
20
+ import hostedGitInfo from "hosted-git-info";
21
+ //#region lib/types/bundle-detail.js
22
+ /**
23
+ * Detail documents of profile bundles: an installed bundle's `meta.detail` file or README from its directory, and an
24
+ * official bundle the installation offers, before it is installed, from the npm file CDNs at its offered version. Reads
25
+ * keep no state; an image request resolves its bundle and document again.
26
+ */
27
+ /**
28
+ * The files of a listed bundle: its directory when its files can be read, otherwise its offered npm version.
29
+ * @param bundle - the bundle as `listBundles()` reports it.
30
+ * @param preferred - npm file CDNs to ask first for an offered version; see `npmFileSourceOrder`.
31
+ * @param options - profile, sources, and limits.
32
+ * @returns the files, or undefined for a bundle offered at no published version.
33
+ * @throws {RemoteError} `plugin-manager/unknown-bundle` when the bundle's directory cannot be resolved.
34
+ */
35
+ function filesOf(bundle, preferred, options) {
36
+ if (bundle.availability !== "missing") {
37
+ let dir;
38
+ try {
39
+ dir = resolveBundleDir("dsh", bundle.name, options.profile.installAnchor, options.profile.dir);
40
+ } catch (error) {
41
+ throw new RemoteError("plugin-manager/unknown-bundle", error.message, { name: bundle.name }, { cause: error });
42
+ }
43
+ return localFiles(dir, String(bundle.version));
44
+ }
45
+ const version = bundle.installTarget?.version;
46
+ if (version === void 0 || semver.valid(version) !== version) return void 0;
47
+ const sources = npmFileSourceOrder(options.npmFileSources, preferred);
48
+ return npmFiles(bundle.name, version, sources, {
49
+ timeoutMs: options.timeoutMs,
50
+ lifetime: options.lifetime
51
+ });
52
+ }
53
+ /** Rethrow a detail failure as the Remote error clients read. */
54
+ function remoteFailure(error) {
55
+ if (error instanceof DetailFailure) throw new RemoteError("plugin-manager/detail-unavailable", error.message, { reason: error.reason }, { cause: error });
56
+ throw error;
57
+ }
58
+ /**
59
+ * Read a bundle's detail document in a display language.
60
+ * @param bundle - the bundle as `listBundles()` reports it.
61
+ * @param language - a BCP 47 language id.
62
+ * @param preferred - npm file CDNs to ask first for an offered version; see `npmFileSourceOrder`.
63
+ * @param options - profile, sources, and limits.
64
+ * @returns the document, or `none` when the bundle has neither a `meta.detail` file nor a README.
65
+ * @throws {RemoteError} `plugin-manager/invalid-language`, `plugin-manager/unknown-bundle`, or
66
+ * `plugin-manager/detail-unavailable`.
67
+ */
68
+ async function readBundleDocument(bundle, language, preferred, options) {
69
+ let languages;
70
+ try {
71
+ languages = languageChain(language);
72
+ } catch (error) {
73
+ throw new RemoteError("plugin-manager/invalid-language", error.message, { language }, { cause: error });
74
+ }
75
+ const files = filesOf(bundle, preferred, options);
76
+ if (files === void 0) return { status: "none" };
77
+ const document = await readPackageDocument(files, "", languages, options.maxDocumentBytes, options.lifetime).catch(remoteFailure);
78
+ return document === void 0 ? { status: "none" } : {
79
+ status: "found",
80
+ ...document
81
+ };
82
+ }
83
+ /**
84
+ * Read an image beside a bundle's detail document.
85
+ * @param bundle - the bundle as `listBundles()` reports it.
86
+ * @param document - the document's path inside the bundle, as {@link readBundleDocument} returned it.
87
+ * @param destination - the image destination as the document writes it.
88
+ * @param preferred - npm file CDNs to ask first for an offered version; see `npmFileSourceOrder`.
89
+ * @param options - profile, sources, and limits.
90
+ * @returns the bytes and media type, or undefined for a path outside the bundle, an unsupported type, or a missing file.
91
+ * @throws {RemoteError} `plugin-manager/unknown-bundle` or `plugin-manager/detail-unavailable`.
92
+ */
93
+ async function readBundleImage(bundle, document, destination, preferred, options) {
94
+ const image = detailImage(document, destination);
95
+ const files = image === void 0 ? void 0 : filesOf(bundle, preferred, options);
96
+ if (image === void 0 || files === void 0) return void 0;
97
+ const bytes = await files.read(image.path, options.maxImageBytes, options.lifetime).catch(remoteFailure);
98
+ return bytes === void 0 ? void 0 : {
99
+ bytes,
100
+ mediaType: image.mediaType
101
+ };
102
+ }
103
+ //#endregion
16
104
  //#region lib/types/install-spec.js
17
105
  /**
18
106
  * Reading an install spec before pnpm sees it: which of pnpm's spec forms it
@@ -319,12 +407,13 @@ function bundleManifest(name, dir, anchor) {
319
407
  async function saveManifest(dir, manifest) {
320
408
  await writeFileAtomic(join(dir, "package.json"), JSON.stringify(manifest, void 0, 2) + "\n", { mode: 384 });
321
409
  }
322
- /** Reconcile package removals and newly installed bundles without re-enabling retained dependencies. */
410
+ /** Reconcile bundle selection, returning platform denials without saving any selection changes. */
323
411
  async function reconcile(before, dir, anchor, options) {
324
412
  const after = readProfileManifest("dsh", dir);
325
413
  const dependencies = Object.keys(after.dependencies ?? {});
326
414
  const beforeDeps = new Set(Object.keys(before.dependencies ?? {}));
327
415
  const previous = after.dsh?.profile?.bundles ?? [];
416
+ const unsupported = [];
328
417
  const bundles = previous.filter((name) => {
329
418
  if (!beforeDeps.has(name) && !dependencies.includes(name)) return true;
330
419
  return dependencies.includes(name) && bundleManifest(name, dir, anchor) !== void 0;
@@ -336,10 +425,18 @@ async function reconcile(before, dir, anchor, options) {
336
425
  options.onOutput?.(`dsh: warning: ${name} declares no dsh.bundle — installed as a plain dependency, not a profile layer\n`, "stderr");
337
426
  continue;
338
427
  }
428
+ try {
429
+ assertBundlePlatform(metadata.dsh.bundle.platforms, process.platform);
430
+ } catch (error) {
431
+ if (!(error instanceof UnsupportedBundlePlatformError)) throw error;
432
+ unsupported.push(`${name}: ${error.message}`);
433
+ continue;
434
+ }
339
435
  for (const file of bundlePatchPaths(resolveBundleDir("dsh", name, anchor, dir), metadata.dsh.bundle)) loadOverlayPatches("dsh", file);
340
436
  if (!bundles.includes(name)) bundles.push(name);
341
437
  }
342
- if (JSON.stringify(previous) === JSON.stringify(bundles)) return;
438
+ if (unsupported.length > 0) return unsupported;
439
+ if (JSON.stringify(previous) === JSON.stringify(bundles)) return [];
343
440
  after.dsh = {
344
441
  ...after.dsh,
345
442
  profile: {
@@ -348,6 +445,7 @@ async function reconcile(before, dir, anchor, options) {
348
445
  }
349
446
  };
350
447
  await saveManifest(dir, after);
448
+ return [];
351
449
  }
352
450
  /**
353
451
  * How long the pipes keep draining after their process exited, as a fixed part of
@@ -520,6 +618,8 @@ function bundleComponentManifests(manifest, dir, anchor) {
520
618
  * @param options Output, activation and cancellation policy.
521
619
  * @returns Exit status, whether the silence bound stopped the run, and the diagnostic path.
522
620
  * A compatibility denial returns exit code 1. Service output is bounded; CLI output uses inherited descriptors.
621
+ * Unsupported Host activation returns exit code 1 with named diagnostics; installed dependencies remain,
622
+ * and no bundle selection changes are saved. Other reconciliation or filesystem errors reject.
523
623
  * The diagnostic file is closed on return or rejection, including preparation and spawn failures.
524
624
  */
525
625
  async function runProfilePnpm(context, args, options) {
@@ -702,6 +802,7 @@ async function runProfilePnpm(context, args, options) {
702
802
  if (result.failed && output.length === 0) {
703
803
  const diagnostic = result.shortMessage ?? "pnpm failed";
704
804
  await log.write(diagnostic);
805
+ options.onOutput?.(diagnostic, "stderr");
705
806
  truncated = Buffer.byteLength(diagnostic) > options.outputBytes;
706
807
  output = Buffer.from(diagnostic).subarray(0, options.outputBytes);
707
808
  }
@@ -759,7 +860,16 @@ async function runProfilePnpm(context, args, options) {
759
860
  await log.write(diagnostic);
760
861
  options.onOutput?.(diagnostic, "stderr");
761
862
  append(Buffer.from(diagnostic));
762
- } else if (options.activateNewBundles !== false) await reconcile(before, dir, context.installAnchor, options);
863
+ } else if (options.activateNewBundles !== false) {
864
+ const unsupported = await reconcile(before, dir, context.installAnchor, options);
865
+ if (unsupported.length > 0) {
866
+ exitCode = 1;
867
+ const diagnostic = `\ndsh: bundle activation rejected: ${unsupported.join("\n")}\ndsh: installed dependencies remain; bundle selection is unchanged. Use a supported Host or remove the unwanted dependencies with 'dsh plugin remove <package>'.\n`;
868
+ await log.write(diagnostic);
869
+ options.onOutput?.(diagnostic, "stderr");
870
+ append(Buffer.from(diagnostic));
871
+ }
872
+ }
763
873
  }
764
874
  } finally {
765
875
  control.settled = true;
@@ -826,7 +936,7 @@ function registryArguments(registry) {
826
936
  * configured after it are the retry.
827
937
  * @param dir Profile directory.
828
938
  * @param spec One registry spec: a package name with an optional range.
829
- * @param options The registry, cancellation, and the time bound.
939
+ * @param options The fields printed, the registry, cancellation, and the time bound.
830
940
  * @returns pnpm's exit, output, and how the lookup ended.
831
941
  */
832
942
  async function viewProfilePackage(dir, spec, options) {
@@ -834,10 +944,7 @@ async function viewProfilePackage(dir, spec, options) {
834
944
  ...options.args ?? [],
835
945
  "view",
836
946
  spec,
837
- "name",
838
- "version",
839
- "description",
840
- "dsh",
947
+ ...options.fields,
841
948
  "--json",
842
949
  ...registryArguments(options.registry ?? null),
843
950
  "--config.fetch-retries=0"
@@ -872,7 +979,7 @@ async function viewProfilePackage(dir, spec, options) {
872
979
  */
873
980
  /** Patterns in the order they decide: a specific code before the generic network family. */
874
981
  const LOG_KINDS = [
875
- ["build-blocked", /ERR_PNPM_IGNORED_BUILDS|Ignored build scripts/],
982
+ ["build-blocked", /ERR_PNPM_IGNORED_BUILDS|Ignored build scripts|ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED/],
876
983
  ["not-found", /ERR_PNPM_FETCH_404|\bE404\b|404 Not Found|Not Found - GET/],
877
984
  ["no-matching-version", /ERR_PNPM_NO_MATCHING_VERSION|\bETARGET\b|No matching version/],
878
985
  ["disk-full", /\bENOSPC\b|no space left on device/i],
@@ -1085,6 +1192,18 @@ async function writePluginEnabled(profile, id, name, enabled) {
1085
1192
  const UNDECIDED_BUILD = "set this to true or false";
1086
1193
  /** Where a non-interactive run names the build scripts it skipped. */
1087
1194
  const IGNORED_BUILDS = /\bIgnored build scripts: (.+)/;
1195
+ /** The `allowBuilds` key pnpm suggests when it refuses to prepare a git-hosted package; a subdirectory key can contain spaces. */
1196
+ const GIT_DEP_PREPARE = /ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED[\s\S]*?^allowBuilds:\r?\n[ \t]+(.+?): true$/m;
1197
+ /**
1198
+ * Whether an `allowBuilds` key names a git URL that carries a credential: a password, or any user name over HTTP(S).
1199
+ * Such a key is not recorded, so the credential stays out of the profile settings and the pending list.
1200
+ */
1201
+ function carriesCredential(key) {
1202
+ const at = key.indexOf("@git+");
1203
+ if (at === -1) return false;
1204
+ const url = URL.parse(key.slice(at + 5).replace(/#.*$/s, ""));
1205
+ return url !== null && (url.password !== "" || url.username !== "" && /^https?:$/.test(url.protocol));
1206
+ }
1088
1207
  async function readPolicy(dir) {
1089
1208
  let text;
1090
1209
  try {
@@ -1109,33 +1228,33 @@ async function readPolicy(dir) {
1109
1228
  };
1110
1229
  }
1111
1230
  /**
1112
- * Record the build scripts a failed run reported as ignored, then list every name awaiting a decision.
1231
+ * Record the build scripts a failed run reported as blocked, then list every `allowBuilds` key awaiting a decision.
1113
1232
  *
1114
1233
  * pnpm writes those policy entries itself only when it can prompt, and the
1115
1234
  * manager always runs it non-interactively, so the run's own report is the
1116
1235
  * record that survives.
1117
1236
  * @param dir Current profile directory.
1118
1237
  * @param output Captured output of the failed run.
1119
- * @returns Exact package names awaiting a build decision; wildcard rules are excluded.
1238
+ * @returns Exact `allowBuilds` keys awaiting a build decision; wildcard rules are excluded.
1120
1239
  */
1121
1240
  async function recordPendingBuilds(dir, output) {
1122
1241
  const { document, pending, keys } = await readPolicy(dir);
1123
1242
  const known = new Set(keys);
1124
- const added = ignoredBuildNames(output).filter((name) => !known.has(name));
1243
+ const added = blockedBuildNames(output).filter((name) => !known.has(name));
1125
1244
  if (added.length === 0) return pending;
1126
1245
  for (const name of added) document.setIn(["allowBuilds", name], UNDECIDED_BUILD);
1127
1246
  await writeFileAtomic(join(dir, "pnpm-workspace.yaml"), String(document), { mode: 384 });
1128
1247
  return [...pending, ...added];
1129
1248
  }
1130
1249
  /**
1131
- * Read the package names a pnpm run reported as ignored build scripts.
1250
+ * Read the `allowBuilds` keys a pnpm run reported as ignored build scripts or as a git-hosted package it refused to prepare.
1132
1251
  * @param output Captured output of the run.
1133
- * @returns Exact names in report order; wildcard patterns are excluded.
1252
+ * @returns Exact keys in report order; wildcard patterns and git keys carrying a credential are excluded.
1134
1253
  */
1135
- function ignoredBuildNames(output) {
1136
- const reported = IGNORED_BUILDS.exec(output)?.[1];
1137
- if (reported === void 0) return [];
1138
- return reported.split(",").map((name) => name.trim()).filter((name) => name !== "" && !/[*?]/.test(name));
1254
+ function blockedBuildNames(output) {
1255
+ const ignored = IGNORED_BUILDS.exec(output)?.[1]?.split(",") ?? [];
1256
+ const git = GIT_DEP_PREPARE.exec(output)?.[1];
1257
+ return [...ignored, ...git === void 0 ? [] : [git]].map((name) => name.trim()).filter((name) => name !== "" && !/[*?]/.test(name) && !carriesCredential(name));
1139
1258
  }
1140
1259
  /** Persist approval without running scripts; the caller holds the profile manifest lock.
1141
1260
  * @param dir Current profile directory.
@@ -1159,7 +1278,8 @@ async function approveBuilds(dir, names) {
1159
1278
  * @param spec The parsed installation address; npm packages, local paths and other hosts are not checked.
1160
1279
  * @param dir The profile directory where installation runs.
1161
1280
  * @param options The connection deadline, output bound and operation cancellation.
1162
- * @returns A failed check with bounded output and a complete log at logPath, or undefined for a reachable repository or an unhandled spec.
1281
+ * @returns A failed check carrying the command line it ran (without URL user information) and its bounded output, with a
1282
+ * complete log at logPath, or undefined for a reachable repository or an unhandled spec.
1163
1283
  */
1164
1284
  async function checkGithubConnection(spec, dir, options) {
1165
1285
  if (spec.kind !== "git") return void 0;
@@ -1173,15 +1293,19 @@ async function checkGithubConnection(spec, dir, options) {
1173
1293
  });
1174
1294
  const logPath = join(await mkdtemp(join(logRoot, "github-connection-")), "git.log");
1175
1295
  const log = await open(logPath, "ax+", 384);
1296
+ const argv = [
1297
+ "git",
1298
+ "-c",
1299
+ "credential.helper=",
1300
+ "ls-remote",
1301
+ "--",
1302
+ repository,
1303
+ "HEAD"
1304
+ ];
1305
+ const recordedArgv = argv.map((argument) => argument.replace(HTTP_USER_INFO, "$1"));
1306
+ const [command, ...args] = argv;
1176
1307
  try {
1177
- const result = await execa("git", [
1178
- "-c",
1179
- "credential.helper=",
1180
- "ls-remote",
1181
- "--",
1182
- repository,
1183
- "HEAD"
1184
- ], {
1308
+ const result = await execa(command, args, {
1185
1309
  cwd: dir,
1186
1310
  env: {
1187
1311
  ...scrubbedParentEnv(),
@@ -1214,6 +1338,7 @@ async function checkGithubConnection(spec, dir, options) {
1214
1338
  await log.read(bytes, 0, bytes.length, size - bytes.length);
1215
1339
  const output = bytes.toString("utf8");
1216
1340
  return {
1341
+ argv: recordedArgv,
1217
1342
  exitCode: result.exitCode ?? (result.code === "ENOENT" ? 127 : 1),
1218
1343
  output,
1219
1344
  truncated: size > options.outputBytes,
@@ -1221,13 +1346,158 @@ async function checkGithubConnection(spec, dir, options) {
1221
1346
  kind: classifyInstallFailure({
1222
1347
  log: output,
1223
1348
  timedOut: result.timedOut
1224
- })
1349
+ }),
1350
+ ...result.timedOut ? { timedOut: true } : {}
1225
1351
  };
1226
1352
  } finally {
1227
1353
  await log.close();
1228
1354
  }
1229
1355
  }
1230
1356
  //#endregion
1357
+ //#region lib/types/git-transport.js
1358
+ /** The Git transport an installation of a self-hosted repository uses, chosen by probing access before pnpm starts. */
1359
+ /** An HTTP(S) Git URL with an optional `git+` prefix, which pnpm clones over that transport as written. */
1360
+ const HTTP_GIT_URL = /^(?:git\+)?https?:\/\//i;
1361
+ /**
1362
+ * The SSH form of an HTTP(S) Git spec on a host pnpm has no transport fallback for. pnpm tries HTTPS and SSH itself
1363
+ * for the hosts `hosted-git-info` knows, such as GitHub and GitLab.com, and clones any other URL over the transport
1364
+ * it names.
1365
+ * @param spec The parsed installation address.
1366
+ * @returns `git+ssh://git@<host>/<path>` on SSH's default port with the spec's fragment, or `undefined` for a spec that
1367
+ * is not an HTTP(S) Git URL on such a host, or whose URL carries credentials or a query.
1368
+ */
1369
+ function sshGitSpec(spec) {
1370
+ if (spec.kind !== "git" || !HTTP_GIT_URL.test(spec.spec) || hostedGitInfo.fromUrl(spec.spec) !== void 0) return void 0;
1371
+ const url = new URL(spec.spec.replace(/^git\+/i, ""));
1372
+ if (url.username !== "" || url.password !== "" || url.search !== "") return void 0;
1373
+ const hash = /#.*$/s.exec(spec.spec)?.[0] ?? "";
1374
+ return `git+ssh://git@${url.hostname}${url.pathname}${hash}`;
1375
+ }
1376
+ /**
1377
+ * Probe whether Git can read a repository with the installer's Git configuration and credential helpers. Git's
1378
+ * terminal and askpass prompts are disabled, `core.askPass` included because Windows drops the empty `GIT_ASKPASS`,
1379
+ * and on POSIX the probe has no controlling terminal, so SSH cannot ask about host keys or passphrases either.
1380
+ * @param repository The repository URL Git reads.
1381
+ * @param dir The profile directory where installation runs.
1382
+ * @param options The probe deadline, cancellation and environment.
1383
+ * @returns Whether `git ls-remote` listed the repository's HEAD.
1384
+ */
1385
+ async function readable(repository, dir, options) {
1386
+ return !(await execa("git", [
1387
+ "-c",
1388
+ "core.askPass=",
1389
+ "ls-remote",
1390
+ "--exit-code",
1391
+ "--",
1392
+ repository,
1393
+ "HEAD"
1394
+ ], {
1395
+ cwd: dir,
1396
+ env: {
1397
+ ...scrubbedParentEnv(),
1398
+ ...options.env,
1399
+ LC_ALL: "C",
1400
+ GIT_TERMINAL_PROMPT: "0",
1401
+ GCM_INTERACTIVE: "never",
1402
+ GIT_ASKPASS: "",
1403
+ SSH_ASKPASS: "",
1404
+ SSH_ASKPASS_REQUIRE: "never"
1405
+ },
1406
+ extendEnv: false,
1407
+ stdin: "ignore",
1408
+ stdout: "ignore",
1409
+ stderr: "ignore",
1410
+ reject: false,
1411
+ timeout: options.timeoutMs,
1412
+ cancelSignal: options.signal,
1413
+ killDescendants: true,
1414
+ killSignal: "SIGKILL"
1415
+ })).failed;
1416
+ }
1417
+ /**
1418
+ * Choose how pnpm clones an HTTP(S) Git repository that {@link sshGitSpec} has an SSH form for: probe the spec's URL,
1419
+ * and when HTTP(S) cannot read it, probe the SSH form.
1420
+ * @param spec The parsed installation address.
1421
+ * @param dir The profile directory where installation runs.
1422
+ * @param options The deadline of each probe, cancellation and the installer's environment.
1423
+ * @returns The SSH form when only SSH can read the repository; otherwise the spec unchanged.
1424
+ */
1425
+ async function chooseGitTransport(spec, dir, options) {
1426
+ const ssh = sshGitSpec(spec);
1427
+ if (ssh === void 0) return spec.spec;
1428
+ const strip = (value) => value.replace(/^git\+/i, "").replace(/#.*$/s, "");
1429
+ if (await readable(strip(spec.spec), dir, options)) return spec.spec;
1430
+ if (options.signal.aborted || !await readable(strip(ssh), dir, options)) return spec.spec;
1431
+ return ssh;
1432
+ }
1433
+ //#endregion
1434
+ //#region lib/types/versions.js
1435
+ /** Read `pnpm view` answers about a package's published versions. */
1436
+ /** The fields a version listing prints for the package: every version, its publication times, and its dist-tags. */
1437
+ const VERSION_LIST_FIELDS = [
1438
+ "versions",
1439
+ "time",
1440
+ "dist-tags"
1441
+ ];
1442
+ /** The fields read for one version: what decides whether it can replace an installed bundle. */
1443
+ const VERSION_FIELDS = [
1444
+ "name",
1445
+ "version",
1446
+ "engines",
1447
+ "peerDependencies",
1448
+ "deprecated",
1449
+ "dsh"
1450
+ ];
1451
+ /** A JSON object, or undefined for anything else. */
1452
+ function recordOf(value) {
1453
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1454
+ }
1455
+ /**
1456
+ * The published versions newer than the installed one, newest first.
1457
+ * @param answer - parsed `pnpm view <name> versions time dist-tags --json` output.
1458
+ * @param installed - the installed version.
1459
+ * @returns the newer versions with their publication times and dist-tags.
1460
+ * @throws when the answer names no versions.
1461
+ */
1462
+ function newerVersions(answer, installed) {
1463
+ const fields = recordOf(answer);
1464
+ const listed = typeof fields?.versions === "string" ? [fields.versions] : fields?.versions;
1465
+ if (!Array.isArray(listed)) throw new Error("pnpm view answered no versions");
1466
+ const time = recordOf(fields?.time) ?? {};
1467
+ const tags = Object.entries(recordOf(fields?.["dist-tags"]) ?? {});
1468
+ return listed.filter((version) => typeof version === "string" && semver.valid(version) !== null && semver.gt(version, installed)).sort(semver.rcompare).map((version) => {
1469
+ const published = time[version];
1470
+ return {
1471
+ version,
1472
+ ...typeof published === "string" ? { publishedAt: published } : {},
1473
+ tags: tags.filter(([, tagged]) => tagged === version).map(([tag]) => tag),
1474
+ prerelease: semver.prerelease(version) !== null
1475
+ };
1476
+ });
1477
+ }
1478
+ /**
1479
+ * What one exact version's manifest says, from `pnpm view <name>@<version> name version engines peerDependencies deprecated dsh --json`.
1480
+ * @param answer - the parsed output.
1481
+ * @param name - the package name, used when the answer omits it.
1482
+ * @param version - the version asked for, used when the answer omits it.
1483
+ * @returns the manifest fields compatibility reads, whether the version declares a bundle, and its deprecation message.
1484
+ */
1485
+ function versionFacts(answer, name, version) {
1486
+ const fields = recordOf(answer) ?? {};
1487
+ const dsh = recordOf(fields.dsh);
1488
+ const deprecated = fields.deprecated;
1489
+ return {
1490
+ manifest: {
1491
+ name: typeof fields.name === "string" ? fields.name : name,
1492
+ version: typeof fields.version === "string" ? fields.version : version,
1493
+ ...Object.hasOwn(fields, "engines") ? { engines: fields.engines } : {},
1494
+ ...Object.hasOwn(fields, "peerDependencies") ? { peerDependencies: fields.peerDependencies } : {}
1495
+ },
1496
+ bundle: recordOf(dsh?.bundle) !== void 0,
1497
+ ...typeof deprecated === "string" && deprecated !== "" ? { deprecated } : {}
1498
+ };
1499
+ }
1500
+ //#endregion
1231
1501
  //#region lib/types/index.js
1232
1502
  /** Current-profile plugin and bundle management over shared dsh plugin operations. */
1233
1503
  var __runInitializers = function(thisArg, initializers, value) {
@@ -1268,29 +1538,19 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
1268
1538
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
1269
1539
  done = true;
1270
1540
  };
1541
+ /** The Fetch route serving images beside bundle detail documents. */
1542
+ const DETAIL_FILE_PATH = "/api/plugin-manager/detail-file";
1271
1543
  /** An http(s) URL, as pnpm's `--registry` takes it. */
1272
1544
  const REGISTRY_URL = /^https?:\/\/\S+$/;
1273
- const protectedModules = new Set([
1274
- "@deepseek-ai/dsh-plugin-manager",
1275
- "@deepseek-ai/cordis-plugin-loader",
1276
- "@deepseek-ai/cordis-plugin-include",
1277
- "@deepseek-ai/dsh-api-gateway",
1278
- "@deepseek-ai/dsh-host-webserver",
1279
- "@deepseek-ai/dsh-client-modules",
1280
- "@deepseek-ai/dsh-client-ui-settings-plugin-inventory",
1281
- "@deepseek-ai/dsh-client-ui-plugin-manager",
1282
- "@deepseek-ai/dsh-host-plugin-inventory",
1283
- "@deepseek-ai/dsh-typert-registry",
1284
- "@deepseek-ai/dsh-api-remotes",
1285
- "@deepseek-ai/dsh-api-remote-access",
1286
- "@deepseek-ai/cordis-plugin-timer",
1287
- "@deepseek-ai/dsh-client-connection",
1288
- "@deepseek-ai/dsh-host-frontend-static",
1289
- "@deepseek-ai/dsh-tools",
1290
- "@deepseek-ai/dsh-hmr"
1291
- ]);
1292
1545
  /** The profile files an installation writes and a failed or cancelled one restores. */
1293
1546
  const RESTORED_FILES = ["package.json", "pnpm-lock.yaml"];
1547
+ /** The manifest fields an inspection reads for a registry spec. */
1548
+ const INSPECT_FIELDS = [
1549
+ "name",
1550
+ "version",
1551
+ "description",
1552
+ "dsh"
1553
+ ];
1294
1554
  /** pnpm's colour escapes, which a JSON answer may be wrapped in. */
1295
1555
  const ANSI_SEQUENCE = /\x1b\[[0-9;]*m/g;
1296
1556
  /** Preserve the exact observed diagnostic, including non-Error failures. */
@@ -1299,6 +1559,7 @@ function messageOf(error) {
1299
1559
  }
1300
1560
  /** An expected refusal keeps its code; anything else becomes an operation error carrying its exact diagnostic. */
1301
1561
  function managementError(error) {
1562
+ if (error instanceof UnsupportedBundlePlatformError) return { code: "unsupported-platform" };
1302
1563
  if (!(error instanceof ManagementFailure)) return {
1303
1564
  code: "operation-error",
1304
1565
  diagnostic: messageOf(error)
@@ -1345,6 +1606,47 @@ function refused(problem, reason) {
1345
1606
  reason
1346
1607
  };
1347
1608
  }
1609
+ /**
1610
+ * Why an update cannot replace a listed bundle, or what it replaces.
1611
+ * @param bundle The listed bundle, or undefined for a name the inventory does not list.
1612
+ * @param name The package name, for the refusal.
1613
+ * @returns The bundle, its installed version, and its registry spec; or the refusal's diagnostic.
1614
+ */
1615
+ function updateRefusal(bundle, name) {
1616
+ if (bundle === void 0 || !bundle.installed || bundle.availability !== "profile" || bundle.official || bundle.source === void 0) return `${name} is not a third-party package installed in this profile`;
1617
+ if (bundle.readOnlyReason !== void 0) return `${bundle.name} carries plugin management and cannot be removed`;
1618
+ const installed = bundle.version;
1619
+ if (installed === void 0 || semver.valid(installed) === null) return `${bundle.name} declares no semver version`;
1620
+ const parsed = parsedForRegistry(bundle.source);
1621
+ if (parsed.kind !== "registry" || parsed.name !== bundle.name || parsed.range?.includes(":") === true) return `${bundle.name} is not installed from a registry under its own name`;
1622
+ return {
1623
+ bundle,
1624
+ installed,
1625
+ parsed
1626
+ };
1627
+ }
1628
+ /**
1629
+ * Map items with at most `limit` calls in flight, stopping new calls once one answers `stop`.
1630
+ * @param items - the items, in order.
1631
+ * @param limit - the most calls in flight.
1632
+ * @param map - the call for one item.
1633
+ * @param stop - whether an answer ends the remaining calls.
1634
+ * @returns the answers of the calls that ran, in item order; items after a stop stay absent.
1635
+ */
1636
+ async function mapConcurrent(items, limit, map, stop) {
1637
+ const answers = items.map(() => void 0);
1638
+ let next = 0;
1639
+ let stopped = false;
1640
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
1641
+ while (!stopped && next < items.length) {
1642
+ const index = next++;
1643
+ const answer = await map(items[index]);
1644
+ answers[index] = answer;
1645
+ if (stop(answer)) stopped = true;
1646
+ }
1647
+ }));
1648
+ return answers;
1649
+ }
1348
1650
  /** The refusal `pnpm view --json` prints on stdout, `{ error: { code, message } }`, as one log line; empty for anything else. */
1349
1651
  function printedError(printed) {
1350
1652
  let parsed;
@@ -1364,7 +1666,7 @@ function bundleSelection(manifest) {
1364
1666
  }
1365
1667
  /**
1366
1668
  * The package an installation spec names before pnpm runs: a registry name, a local directory's manifest name, or the
1367
- * dependency saved with this git or tarball spec, compared as the plugin list shows saved specs.
1669
+ * dependency saved with this git or tarball spec or the SSH form of its Git URL, compared as the plugin list shows saved specs.
1368
1670
  * @param spec The installation spec.
1369
1671
  * @param dependencies The profile's saved dependencies.
1370
1672
  * @param profileDir The profile directory saved local paths are relative to.
@@ -1374,7 +1676,8 @@ function specPackageName(spec, dependencies, profileDir) {
1374
1676
  const parsed = parsedForRegistry(spec);
1375
1677
  if (parsed.kind === "registry") return parsed.name;
1376
1678
  if (parsed.kind === "path") return packageName(parsed.path);
1377
- const specs = parsed.kind === "tarball" && parsed.path !== void 0 ? [spec, `file:${parsed.path}`] : [spec];
1679
+ const alternative = parsed.kind === "tarball" && parsed.path !== void 0 ? `file:${parsed.path}` : sshGitSpec(parsed);
1680
+ const specs = alternative === void 0 ? [spec] : [spec, alternative];
1378
1681
  return Object.entries(dependencies).find(([dependency, saved]) => specs.includes(dependencySpec(dependency, saved, profileDir)))?.[0];
1379
1682
  }
1380
1683
  /** The package name a local directory declares, or `undefined` without a readable manifest. */
@@ -1399,16 +1702,46 @@ function parsedForRegistry(spec) {
1399
1702
  };
1400
1703
  }
1401
1704
  }
1705
+ /** Only registry package names are retained before installation resolves its target. */
1706
+ function installOperationTarget(spec) {
1707
+ let parsed;
1708
+ try {
1709
+ parsed = parseInstallSpec(spec);
1710
+ } catch (_error) {
1711
+ return null;
1712
+ }
1713
+ return parsed.kind === "registry" ? parsed.name : null;
1714
+ }
1715
+ /** Exemption facts use canonical package identity, never the raw request or installed version. */
1716
+ function exemptionOperationIdentity(packageVersion, runtimeVersion) {
1717
+ try {
1718
+ validatePluginVersionExemption(packageVersion, runtimeVersion);
1719
+ } catch (_error) {
1720
+ return { target: null };
1721
+ }
1722
+ const separator = packageVersion.lastIndexOf("@");
1723
+ return {
1724
+ target: installOperationTarget(packageVersion.slice(0, separator)),
1725
+ version: diagnosticVersion(packageVersion.slice(separator + 1))
1726
+ };
1727
+ }
1728
+ /** Unusable file metadata must not discard the rest of an operation record. */
1729
+ function diagnosticVersion(value) {
1730
+ return typeof value === "string" && value.length <= 128 ? value : void 0;
1731
+ }
1402
1732
  /** Manage profile files and apply their declared reload lifecycle. */
1403
1733
  let PluginManager = (() => {
1404
1734
  let _classSuper = TypertRemoteService;
1405
1735
  let _instanceExtraInitializers = [];
1736
+ let _readBundleDetail_decorators;
1406
1737
  let _listVersionExemptions_decorators;
1407
1738
  let _setVersionExemption_decorators;
1408
1739
  let _listPlugins_decorators;
1409
1740
  let _listBundles_decorators;
1410
1741
  let _registries_decorators;
1411
1742
  let _inspect_decorators;
1743
+ let _listVersions_decorators;
1744
+ let _updateBundle_decorators;
1412
1745
  let _setPluginEnabled_decorators;
1413
1746
  let _setBundleEnabled_decorators;
1414
1747
  let _installBundle_decorators;
@@ -1418,18 +1751,32 @@ let PluginManager = (() => {
1418
1751
  return class PluginManager extends _classSuper {
1419
1752
  static {
1420
1753
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
1754
+ _readBundleDetail_decorators = [Remote];
1421
1755
  _listVersionExemptions_decorators = [Remote];
1422
1756
  _setVersionExemption_decorators = [Remote];
1423
1757
  _listPlugins_decorators = [Remote];
1424
1758
  _listBundles_decorators = [Remote];
1425
1759
  _registries_decorators = [Remote];
1426
1760
  _inspect_decorators = [Remote];
1761
+ _listVersions_decorators = [Remote];
1762
+ _updateBundle_decorators = [Remote];
1427
1763
  _setPluginEnabled_decorators = [Remote];
1428
1764
  _setBundleEnabled_decorators = [Remote];
1429
1765
  _installBundle_decorators = [Remote];
1430
1766
  _waitForInstall_decorators = [Remote];
1431
1767
  _cancelInstall_decorators = [Remote];
1432
1768
  _removeBundle_decorators = [Remote];
1769
+ __esDecorate(this, null, _readBundleDetail_decorators, {
1770
+ kind: "method",
1771
+ name: "readBundleDetail",
1772
+ static: false,
1773
+ private: false,
1774
+ access: {
1775
+ has: (obj) => "readBundleDetail" in obj,
1776
+ get: (obj) => obj.readBundleDetail
1777
+ },
1778
+ metadata: _metadata
1779
+ }, null, _instanceExtraInitializers);
1433
1780
  __esDecorate(this, null, _listVersionExemptions_decorators, {
1434
1781
  kind: "method",
1435
1782
  name: "listVersionExemptions",
@@ -1496,6 +1843,28 @@ let PluginManager = (() => {
1496
1843
  },
1497
1844
  metadata: _metadata
1498
1845
  }, null, _instanceExtraInitializers);
1846
+ __esDecorate(this, null, _listVersions_decorators, {
1847
+ kind: "method",
1848
+ name: "listVersions",
1849
+ static: false,
1850
+ private: false,
1851
+ access: {
1852
+ has: (obj) => "listVersions" in obj,
1853
+ get: (obj) => obj.listVersions
1854
+ },
1855
+ metadata: _metadata
1856
+ }, null, _instanceExtraInitializers);
1857
+ __esDecorate(this, null, _updateBundle_decorators, {
1858
+ kind: "method",
1859
+ name: "updateBundle",
1860
+ static: false,
1861
+ private: false,
1862
+ access: {
1863
+ has: (obj) => "updateBundle" in obj,
1864
+ get: (obj) => obj.updateBundle
1865
+ },
1866
+ metadata: _metadata
1867
+ }, null, _instanceExtraInitializers);
1499
1868
  __esDecorate(this, null, _setPluginEnabled_decorators, {
1500
1869
  kind: "method",
1501
1870
  name: "setPluginEnabled",
@@ -1576,9 +1945,16 @@ let PluginManager = (() => {
1576
1945
  lockWaitMs: z.number().step(1).min(0).default(12e4),
1577
1946
  inspectTimeoutMs: z.number().step(1).min(1e3).default(2e4),
1578
1947
  githubConnectionTimeoutMs: z.number().step(1).min(1e3).default(5e3),
1948
+ gitTransportTimeoutMs: z.number().step(1).min(1e3).default(5e3),
1579
1949
  idleTimeoutMs: z.number().step(1).min(1e3).default(6e5),
1580
1950
  registry: z.string().pattern(REGISTRY_URL),
1581
- fallbackRegistries: z.array(z.string().pattern(REGISTRY_URL)).default([NPMMIRROR_REGISTRY])
1951
+ fallbackRegistries: z.array(z.string().pattern(REGISTRY_URL)).default([NPMMIRROR_REGISTRY]),
1952
+ versionListLimit: z.number().step(1).min(1).default(20),
1953
+ versionLookupConcurrency: z.number().step(1).min(1).default(4),
1954
+ detailMaxBytes: z.natural().min(1).default(1024 * 1024),
1955
+ detailImageMaxBytes: z.natural().min(1).default(5 * 1024 * 1024),
1956
+ detailFetchTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(15e3),
1957
+ detailNpmFileSources: z.array(z.union(NPM_FILE_SOURCES)).min(1).default([...NPM_FILE_SOURCES])
1582
1958
  });
1583
1959
  /** Management bundles remain protected if their files become unreadable. */
1584
1960
  managementBundles = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Set());
@@ -1594,13 +1970,17 @@ let PluginManager = (() => {
1594
1970
  lockWaitMs;
1595
1971
  inspectTimeoutMs;
1596
1972
  githubConnectionTimeoutMs;
1973
+ gitTransportTimeoutMs;
1597
1974
  idleTimeoutMs;
1598
1975
  pnpmCommand;
1976
+ versionListLimit;
1977
+ versionLookupConcurrency;
1599
1978
  configuredRegistries;
1600
1979
  ownerContext;
1601
1980
  abort = new AbortController();
1602
1981
  /** Installations by request id, from their call until it settles. */
1603
1982
  installs = /* @__PURE__ */ new Map();
1983
+ detail;
1604
1984
  constructor(ctx, config) {
1605
1985
  super(ctx, "pluginManager");
1606
1986
  this.ownerEntryId = ctx.fiber.entry?.id;
@@ -1611,16 +1991,78 @@ let PluginManager = (() => {
1611
1991
  this.lockWaitMs = config.lockWaitMs;
1612
1992
  this.inspectTimeoutMs = config.inspectTimeoutMs;
1613
1993
  this.githubConnectionTimeoutMs = config.githubConnectionTimeoutMs;
1994
+ this.gitTransportTimeoutMs = config.gitTransportTimeoutMs;
1614
1995
  this.idleTimeoutMs = config.idleTimeoutMs;
1615
1996
  this.pnpmCommand = config.pnpmCommand;
1997
+ this.versionListLimit = config.versionListLimit;
1998
+ this.versionLookupConcurrency = config.versionLookupConcurrency;
1616
1999
  this.configuredRegistries = {
1617
2000
  registry: config.registry === void 0 ? null : normalizeRegistry(config.registry),
1618
2001
  fallbackRegistries: config.fallbackRegistries.map(normalizeRegistry)
1619
2002
  };
2003
+ const required = config;
2004
+ this.detail = {
2005
+ profile: this.profile,
2006
+ maxDocumentBytes: required.detailMaxBytes,
2007
+ maxImageBytes: required.detailImageMaxBytes,
2008
+ npmFileSources: required.detailNpmFileSources,
2009
+ timeoutMs: required.detailFetchTimeoutMs,
2010
+ lifetime: this.abort.signal
2011
+ };
1620
2012
  ctx.effect(() => async () => {
1621
2013
  this.abort.abort();
1622
2014
  await Promise.allSettled([...this.packageOperations]);
1623
2015
  }, "plugin-manager: package cancellation");
2016
+ ctx.inject(["connection"], (scope) => {
2017
+ scope.effect(() => scope.connection.fetch.register({
2018
+ path: DETAIL_FILE_PATH,
2019
+ methods: ["GET"],
2020
+ requestBody: "buffered",
2021
+ fetch: (request) => this.serveDetailFile(request)
2022
+ }), `plugin-manager: ${DETAIL_FILE_PATH}`);
2023
+ });
2024
+ }
2025
+ /**
2026
+ * Read a bundle's long description: the Markdown file its locale `meta.detail` names in `language`, otherwise its
2027
+ * README. An installed bundle is read from its directory without network access; an official bundle the installation
2028
+ * offers before it is installed is read from the npm file CDNs at its offered version. Nothing is cached.
2029
+ * @param name - the bundle's package name, as `listBundles()` lists it.
2030
+ * @param language - the display language, such as `zh-CN`; documents fall back through its prefixes to English.
2031
+ * @param options - `npmFileSources` names npm file CDNs to ask first for an offered bundle, in order, such as the one
2032
+ * a Client measured as fastest; configured CDNs it omits follow, and CDNs that are not configured are not asked.
2033
+ * @returns the document with its origin and path, or `none`.
2034
+ * @throws {RemoteError} `plugin-manager/unknown-bundle`, `plugin-manager/invalid-language`, or
2035
+ * `plugin-manager/detail-unavailable`.
2036
+ */
2037
+ async readBundleDetail(name, language, options) {
2038
+ return await readBundleDocument(await this.listedBundle(name), language, options?.npmFileSources ?? [], this.detail);
2039
+ }
2040
+ async listedBundle(name) {
2041
+ const bundle = (await this.listBundles()).find((candidate) => candidate.name === name);
2042
+ if (bundle === void 0) throw new RemoteError("plugin-manager/unknown-bundle", `No such bundle: ${name}`, { name });
2043
+ return bundle;
2044
+ }
2045
+ /**
2046
+ * Answer `GET ${DETAIL_FILE_PATH}?bundle=<name>&document=<path>&path=<destination>[&sources=<cdn>,...]` with one image
2047
+ * beside a bundle document; `sources` names npm file CDNs to ask first for an offered bundle, as `readBundleDetail` does.
2048
+ */
2049
+ async serveDetailFile(request) {
2050
+ const params = new URL(request.url).searchParams;
2051
+ const [bundle, document, path] = [
2052
+ params.get("bundle"),
2053
+ params.get("document"),
2054
+ params.get("path")
2055
+ ];
2056
+ const cache = "no-store";
2057
+ if (bundle === null || document === null || path === null) return detailImageResponse("invalid", cache);
2058
+ try {
2059
+ return detailImageResponse(await readBundleImage(await this.listedBundle(bundle), document, path, params.get("sources")?.split(",") ?? [], this.detail), cache);
2060
+ } catch (error) {
2061
+ const failure = remoteErrorOf(error);
2062
+ if (failure?.code === "plugin-manager/unknown-bundle") return detailImageResponse(void 0, cache);
2063
+ if (failure?.code === "plugin-manager/detail-unavailable") return detailImageResponse(failure.details.reason, cache);
2064
+ throw error;
2065
+ }
1624
2066
  }
1625
2067
  /** Read exact plugin-version exemptions saved in this profile.
1626
2068
  * @returns Accepted package-name@version keys with the runtime versions they may run on, and any
@@ -1648,7 +2090,7 @@ let PluginManager = (() => {
1648
2090
  stage: "enable",
1649
2091
  target: packageVersion,
1650
2092
  enabled
1651
- }, "bundle");
2093
+ }, "bundle", exemptionOperationIdentity(packageVersion, runtimeVersion));
1652
2094
  }
1653
2095
  /** Read current plugins, including why a row cannot be changed through the profile patch.
1654
2096
  * @returns Current runtime entries with persistent patch targets.
@@ -1659,7 +2101,7 @@ let PluginManager = (() => {
1659
2101
  const actual = [...this.ctx.loader.entries()].find((row) => row.id === entry.entryId);
1660
2102
  const candidates = rows.filter((row) => row.id === actual?.options.id);
1661
2103
  const candidate = candidates[0];
1662
- if (protectedModules.has(entry.moduleName) || entry.entryId === this.ownerEntryId) return {
2104
+ if (PROTECTED_PLUGINS.has(entry.moduleName) || entry.entryId === this.ownerEntryId) return {
1663
2105
  ...entry,
1664
2106
  readOnlyReason: "management-required"
1665
2107
  };
@@ -1679,6 +2121,13 @@ let PluginManager = (() => {
1679
2121
  * display metadata, activation selections, whether the installation offers the bundle, and removal availability.
1680
2122
  */
1681
2123
  listBundles() {
2124
+ return Promise.resolve(this.readBundles().map((bundle) => ({
2125
+ ...bundle,
2126
+ updatable: typeof updateRefusal(bundle, bundle.name) !== "string"
2127
+ })));
2128
+ }
2129
+ /** The bundle inventory before update eligibility, which is derived from each listed bundle. */
2130
+ readBundles() {
1682
2131
  const manifest = readProfileManifest("dsh", this.profile.dir);
1683
2132
  const exemptions = readProfileVersionExemptions(this.profile.dir);
1684
2133
  const selected = bundleSelection(manifest);
@@ -1710,6 +2159,13 @@ let PluginManager = (() => {
1710
2159
  }
1711
2160
  const catalogMeta = offered === void 0 ? {} : { meta: offered.meta };
1712
2161
  if (offered !== void 0 && !installed && !shipped) {
2162
+ let platformError;
2163
+ try {
2164
+ assertBundlePlatform(offered.platforms, process.platform);
2165
+ } catch (error) {
2166
+ platformError = managementError(error);
2167
+ }
2168
+ const error = platformError ?? targetError ?? (enabled ? { code: "not-bundle" } : void 0);
1713
2169
  bundles.push({
1714
2170
  name,
1715
2171
  official,
@@ -1719,10 +2175,12 @@ let PluginManager = (() => {
1719
2175
  enabled,
1720
2176
  installed,
1721
2177
  optional,
2178
+ ...offered.listedByDefault === void 0 ? {} : { listedByDefault: offered.listedByDefault },
2179
+ ...platformError?.code === "unsupported-platform" ? { listedByDefault: false } : {},
1722
2180
  removable: enabled,
1723
2181
  rows: [],
1724
2182
  overrides: [],
1725
- ...targetError !== void 0 ? { error: targetError } : enabled ? { error: { code: "not-bundle" } } : {}
2183
+ ...error === void 0 ? {} : { error }
1726
2184
  });
1727
2185
  continue;
1728
2186
  }
@@ -1732,6 +2190,7 @@ let PluginManager = (() => {
1732
2190
  const readOnlyReason = this.protectsManager(name) ? "management-required" : void 0;
1733
2191
  let availability = "missing";
1734
2192
  let version;
2193
+ let listing = {};
1735
2194
  try {
1736
2195
  const info = bundleManifest(name, this.profile.dir, this.profile.installAnchor);
1737
2196
  availability = shipped ? "installation" : "profile";
@@ -1755,14 +2214,28 @@ let PluginManager = (() => {
1755
2214
  continue;
1756
2215
  }
1757
2216
  version = info.version;
2217
+ const listedByDefault = info.dsh?.bundle?.listedByDefault;
2218
+ if (listedByDefault !== void 0) {
2219
+ if (typeof listedByDefault !== "boolean") throw new Error("dsh.bundle.listedByDefault must be a boolean");
2220
+ listing = { listedByDefault };
2221
+ }
1758
2222
  const compatibility = evaluatePluginCompatibility(info, exemptions);
1759
2223
  if (compatibility !== void 0 && !compatibility.exempted) throw new ManagementFailure("incompatible-version", [incompatiblePlugin(compatibility)]);
1760
2224
  const dir = resolveBundleDir("dsh", name, this.profile.installAnchor, this.profile.dir);
1761
2225
  const meta = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, "package.json")).href);
2226
+ let platformError;
2227
+ try {
2228
+ assertBundlePlatform(info.dsh?.bundle?.platforms, process.platform);
2229
+ } catch (error) {
2230
+ platformError = managementError(error);
2231
+ }
2232
+ if (platformError?.code === "unsupported-platform") listing = { listedByDefault: false };
2233
+ const error = platformError ?? targetError;
1762
2234
  bundles.push({
1763
2235
  name,
1764
2236
  official,
1765
2237
  availability,
2238
+ ...listing,
1766
2239
  ...target,
1767
2240
  ...version === void 0 ? {} : { version },
1768
2241
  ...info.description === void 0 || info.description === "" ? {} : { description: info.description },
@@ -1774,13 +2247,14 @@ let PluginManager = (() => {
1774
2247
  removable: removable && readOnlyReason === void 0,
1775
2248
  ...readOnlyReason === void 0 ? {} : { readOnlyReason },
1776
2249
  ...this.declaredRows(name, info),
1777
- ...targetError === void 0 ? {} : { error: targetError }
2250
+ ...error === void 0 ? {} : { error }
1778
2251
  });
1779
2252
  } catch (error) {
1780
2253
  if (enabled || installed || optional || offered !== void 0) bundles.push({
1781
2254
  name,
1782
2255
  official,
1783
2256
  availability,
2257
+ ...listing,
1784
2258
  ...catalogMeta,
1785
2259
  ...target,
1786
2260
  ...version === void 0 ? {} : { version },
@@ -1796,7 +2270,7 @@ let PluginManager = (() => {
1796
2270
  });
1797
2271
  }
1798
2272
  }
1799
- return Promise.resolve(bundles);
2273
+ return bundles;
1800
2274
  }
1801
2275
  /** Read the registries this manager asks: the configured first one, its fallbacks in order, and what pnpm's own configuration names.
1802
2276
  * @returns The registries in pnpm's comparison form; null is the one pnpm's own configuration names, `resolved` as pnpm reads it now.
@@ -1868,59 +2342,324 @@ let PluginManager = (() => {
1868
2342
  }
1869
2343
  case "registry": {
1870
2344
  if (known.has(parsed.name)) return refused("already-installed", `${parsed.name} is already installed`);
1871
- const registries = [];
1872
- const refusedBy = (problem, reason) => ({
2345
+ const asked = await this.askRegistries(spec.trim(), INSPECT_FIELDS, plan, parsed, signal);
2346
+ const registries = asked.attempts.map((attempt) => attempt.registry);
2347
+ if (asked.status === "refused") return {
2348
+ status: "refused",
2349
+ problem: asked.problem,
2350
+ reason: asked.reason,
2351
+ registries
2352
+ };
2353
+ const latest = Array.isArray(asked.answer) ? asked.answer.at(-1) : asked.answer;
2354
+ if (typeof latest !== "object" || latest === null) return {
2355
+ status: "refused",
2356
+ problem: "unknown",
2357
+ reason: "pnpm view answered no package",
2358
+ registries
2359
+ };
2360
+ const inspection = inspectionOf("registry", latest, asked.registry);
2361
+ const named = inspection.name === void 0 ? {
2362
+ ...inspection,
2363
+ name: parsed.name
2364
+ } : inspection;
2365
+ if (!named.bundle) return {
2366
+ status: "refused",
2367
+ problem: "not-a-bundle",
2368
+ reason: `${named.name} declares no dsh.bundle`,
2369
+ registries
2370
+ };
2371
+ return named;
2372
+ }
2373
+ }
2374
+ }
2375
+ /** Read the published versions newer than an installed registry package's version, from the first registry that answers.
2376
+ * Official bundles follow the DSH version and are not listed.
2377
+ * @param name Installed profile dependency name.
2378
+ * @param options The registry asked first; absent, the one the package was installed from in this process, else the configured one.
2379
+ * @param signal Ends the lookups early.
2380
+ * @returns At most `versionListLimit` newer versions, newest first, with their tags, deprecation, bundle declaration,
2381
+ * and DSH compatibility, and the registry that answered; or why no list could be read, with every registry asked.
2382
+ */
2383
+ async listVersions(name, options, signal) {
2384
+ const target = updateRefusal((await this.listBundles()).find((bundle) => bundle.name === name), name);
2385
+ if (typeof target === "string") return {
2386
+ status: "refused",
2387
+ problem: "not-updatable",
2388
+ reason: target,
2389
+ attempts: []
2390
+ };
2391
+ const plan = registryPlan(this.registryFor(name, options?.registry), await this.registries());
2392
+ const listing = await this.askRegistries(name, VERSION_LIST_FIELDS, plan, target.parsed, signal);
2393
+ if (listing.status === "refused") return listing;
2394
+ let newer;
2395
+ try {
2396
+ newer = newerVersions(listing.answer, target.installed);
2397
+ } catch (error) {
2398
+ return {
2399
+ status: "refused",
2400
+ problem: "unknown",
2401
+ reason: messageOf(error),
2402
+ attempts: listing.attempts
2403
+ };
2404
+ }
2405
+ const listed = newer.slice(0, this.versionListLimit);
2406
+ const exemptions = readProfileVersionExemptions(this.profile.dir);
2407
+ const looked = await mapConcurrent(listed, this.versionLookupConcurrency, async (published) => {
2408
+ const spec = `${name}@${published.version}`;
2409
+ const answer = await this.askRegistries(spec, VERSION_FIELDS, [listing.registry], {
2410
+ kind: "registry",
2411
+ spec,
2412
+ name
2413
+ }, signal);
2414
+ if (answer.status === "refused") return answer;
2415
+ const facts = versionFacts(answer.answer, name, published.version);
2416
+ let compatibility;
2417
+ try {
2418
+ compatibility = evaluatePluginCompatibility(facts.manifest, exemptions);
2419
+ } catch (error) {
2420
+ return {
2421
+ status: "refused",
2422
+ problem: "unknown",
2423
+ reason: messageOf(error),
2424
+ attempts: answer.attempts
2425
+ };
2426
+ }
2427
+ return {
2428
+ status: "read",
2429
+ version: {
2430
+ ...published,
2431
+ bundle: facts.bundle,
2432
+ ...facts.deprecated === void 0 ? {} : { deprecated: facts.deprecated },
2433
+ ...compatibility === void 0 || compatibility.exempted ? {} : { incompatible: incompatiblePlugin(compatibility) }
2434
+ }
2435
+ };
2436
+ }, (answer) => answer.status === "refused");
2437
+ const versions = [];
2438
+ for (const answer of looked) {
2439
+ /* v8 ignore next -- a lookup stops the rest only by refusing, which returns below */
2440
+ if (answer === void 0) continue;
2441
+ if (answer.status === "refused") return {
2442
+ ...answer,
2443
+ attempts: [...listing.attempts.slice(0, -1), ...answer.attempts]
2444
+ };
2445
+ versions.push(answer.version);
2446
+ }
2447
+ return {
2448
+ status: "listed",
2449
+ installed: target.installed,
2450
+ registry: listing.registry,
2451
+ attempts: listing.attempts,
2452
+ versions,
2453
+ omitted: newer.length - listed.length
2454
+ };
2455
+ }
2456
+ /**
2457
+ * Replace an installed registry bundle with a newer published version. The target is checked on the registry first:
2458
+ * it must exist, declare a bundle, and accept the running DSH version, or nothing changes. With HMR the installed
2459
+ * version is removed, so its plugins stop, and the target is installed with the same selection; when that
2460
+ * installation fails or is cancelled, the removed version is installed again from the registry it came from.
2461
+ * Without HMR the target is installed over the running version and the result reports the restart.
2462
+ * @param name Installed profile dependency name.
2463
+ * @param version Exact published version newer than the installed one.
2464
+ * @param options The registry asked first, as for `listVersions`, and the request id naming the progress and the
2465
+ * target installation's logs and cancellation.
2466
+ * @returns The versions, the last step that ran with its result, and the reinstallation when one ran.
2467
+ */
2468
+ async updateBundle(name, version, options) {
2469
+ const requestId = options?.requestId;
2470
+ const announce = (step) => {
2471
+ if (requestId !== void 0) this.ownerContext.emit("plugin-manager/update-state", {
2472
+ requestId,
2473
+ step
2474
+ });
2475
+ };
2476
+ announce("checking");
2477
+ const target = updateRefusal((await this.listBundles()).find((item) => item.name === name), name);
2478
+ const from = typeof target === "string" ? "" : target.installed;
2479
+ const refusedBefore = (error) => ({
2480
+ from,
2481
+ to: version,
2482
+ step: "check",
2483
+ result: {
2484
+ changed: false,
2485
+ application: "failed",
2486
+ stage: "install",
2487
+ target: name,
2488
+ error
2489
+ }
2490
+ });
2491
+ if (typeof target === "string") return refusedBefore({
2492
+ code: "invalid-spec",
2493
+ diagnostic: target
2494
+ });
2495
+ const { bundle } = target;
2496
+ if (semver.valid(version) === null || !semver.gt(version, from)) return refusedBefore({
2497
+ code: "invalid-spec",
2498
+ diagnostic: `${version} is not a version newer than the installed ${from}`
2499
+ });
2500
+ const spec = `${name}@${version}`;
2501
+ const plan = registryPlan(this.registryFor(name, options?.registry), await this.registries());
2502
+ const checked = await this.askRegistries(spec, VERSION_FIELDS, plan, {
2503
+ kind: "registry",
2504
+ spec,
2505
+ name
2506
+ });
2507
+ if (checked.status === "refused") return refusedBefore({
2508
+ code: "operation-error",
2509
+ diagnostic: checked.reason
2510
+ });
2511
+ const facts = versionFacts(checked.answer, name, version);
2512
+ if (!facts.bundle) return refusedBefore({ code: "not-bundle" });
2513
+ let compatibility;
2514
+ try {
2515
+ compatibility = evaluatePluginCompatibility(facts.manifest, readProfileVersionExemptions(this.profile.dir));
2516
+ } catch (error) {
2517
+ return refusedBefore({
2518
+ code: "operation-error",
2519
+ diagnostic: messageOf(error)
2520
+ });
2521
+ }
2522
+ if (compatibility !== void 0 && !compatibility.exempted) return refusedBefore({
2523
+ code: "incompatible-version",
2524
+ incompatible: [incompatiblePlugin(compatibility)]
2525
+ });
2526
+ const { enabled } = bundle;
2527
+ const settled = (stage, target, operation) => operation.catch((error) => ({
2528
+ changed: false,
2529
+ application: "failed",
2530
+ stage,
2531
+ target,
2532
+ error: managementError(error)
2533
+ }));
2534
+ const installTarget = () => settled("install", spec, this.installBundle(spec, {
2535
+ saveExact: true,
2536
+ registry: checked.registry,
2537
+ enabled,
2538
+ ...requestId === void 0 ? {} : { requestId }
2539
+ }));
2540
+ if (this.ownerContext.get("hmr") === void 0) {
2541
+ announce("installing");
2542
+ return {
2543
+ from,
2544
+ to: version,
2545
+ step: "install",
2546
+ result: await installTarget()
2547
+ };
2548
+ }
2549
+ const previousRegistry = this.installedFrom.get(name);
2550
+ announce("removing");
2551
+ const removal = await settled("remove", name, this.removeBundle(name));
2552
+ if (removal.application === "failed" || removal.application === "cancelled") return {
2553
+ from,
2554
+ to: version,
2555
+ step: "remove",
2556
+ result: removal
2557
+ };
2558
+ announce("installing");
2559
+ const result = await installTarget();
2560
+ if (result.application !== "failed" && result.application !== "cancelled") return {
2561
+ from,
2562
+ to: version,
2563
+ step: "install",
2564
+ result
2565
+ };
2566
+ announce("restoring");
2567
+ if (result.stage === "enable") await settled("remove", name, this.removeBundle(name));
2568
+ const previous = `${name}@${from}`;
2569
+ return {
2570
+ from,
2571
+ to: version,
2572
+ step: "install",
2573
+ result,
2574
+ restore: await settled("install", previous, this.installBundle(previous, {
2575
+ saveExact: true,
2576
+ enabled,
2577
+ ...previousRegistry === void 0 ? {} : { registry: previousRegistry }
2578
+ }))
2579
+ };
2580
+ }
2581
+ /**
2582
+ * The registry a version listing or an update asks first.
2583
+ * @param name The package name.
2584
+ * @param requested The caller's registry, when it named one.
2585
+ * @returns The requested registry, else the one this process last installed the package from, else undefined for the configured one.
2586
+ */
2587
+ registryFor(name, requested) {
2588
+ return requested !== void 0 ? requested : this.installedFrom.get(name);
2589
+ }
2590
+ /**
2591
+ * Ask registries in turn through `pnpm view`, moving to the next one while a failure is the registry's: unreachable,
2592
+ * timed out, or without the package or version, which a mirror not yet synced reports.
2593
+ * @param spec The registry spec viewed.
2594
+ * @param fields The manifest fields printed.
2595
+ * @param plan The registries, in order; never empty.
2596
+ * @param parsed The spec's form, which decides whether a failure was the registry's.
2597
+ * @param signal Ends the lookup; a dropped lookup is not carried to the next registry.
2598
+ * @returns The parsed answer and the registry that gave it, or the last refusal, with every registry asked.
2599
+ */
2600
+ async askRegistries(spec, fields, plan, parsed, signal) {
2601
+ const attempts = [];
2602
+ for (const [index, registry] of plan.entries()) {
2603
+ const view = await viewProfilePackage(this.profile.dir, spec, {
2604
+ ...this.profile.packageManager ?? { command: this.pnpmCommand },
2605
+ fields,
2606
+ timeoutMs: this.inspectTimeoutMs,
2607
+ ...signal === void 0 ? {} : { signal },
2608
+ registry
2609
+ });
2610
+ const printed = view.stdout.replace(ANSI_SEQUENCE, "").trim();
2611
+ if (view.exitCode !== 0 || view.cause !== void 0 || view.timedOut) {
2612
+ const log = [
2613
+ view.stderr.trim(),
2614
+ printedError(printed),
2615
+ view.cause === void 0 ? "" : messageOf(view.cause)
2616
+ ].filter(Boolean).join("\n");
2617
+ const kind = classifyInstallFailure({
2618
+ log,
2619
+ timedOut: view.timedOut,
2620
+ ...view.cause === void 0 ? {} : { cause: view.cause }
2621
+ });
2622
+ const reason = view.timedOut ? `pnpm view timed out after ${String(this.inspectTimeoutMs)}ms` : log || printed || `pnpm view exited with ${String(view.exitCode)}`;
2623
+ const problem = kind === "not-found" || kind === "no-matching-version" ? "not-found" : kind === "network" || kind === "timeout" ? "network" : "unknown";
2624
+ attempts.push({
2625
+ registry,
2626
+ problem,
2627
+ reason
2628
+ });
2629
+ if (index < plan.length - 1 && signal?.aborted !== true && attributeFailure(kind, log, parsed) === "registry") continue;
2630
+ return {
1873
2631
  status: "refused",
1874
2632
  problem,
1875
2633
  reason,
1876
- registries
2634
+ attempts
2635
+ };
2636
+ }
2637
+ try {
2638
+ const answer = JSON.parse(printed || "null");
2639
+ attempts.push({ registry });
2640
+ return {
2641
+ status: "answered",
2642
+ answer,
2643
+ registry,
2644
+ attempts
2645
+ };
2646
+ } catch (error) {
2647
+ const reason = `unreadable pnpm view output: ${messageOf(error)}`;
2648
+ attempts.push({
2649
+ registry,
2650
+ problem: "unknown",
2651
+ reason
1877
2652
  });
1878
- for (const current of plan) {
1879
- registries.push(current);
1880
- const view = await viewProfilePackage(this.profile.dir, spec.trim(), {
1881
- ...this.profile.packageManager ?? { command: this.pnpmCommand },
1882
- timeoutMs: this.inspectTimeoutMs,
1883
- ...signal === void 0 ? {} : { signal },
1884
- registry: current
1885
- });
1886
- const printed = view.stdout.replace(ANSI_SEQUENCE, "").trim();
1887
- if (view.exitCode !== 0 || view.cause !== void 0 || view.timedOut) {
1888
- const log = [
1889
- view.stderr.trim(),
1890
- printedError(printed),
1891
- view.cause === void 0 ? "" : messageOf(view.cause)
1892
- ].filter(Boolean).join("\n");
1893
- const kind = classifyInstallFailure({
1894
- log,
1895
- timedOut: view.timedOut,
1896
- ...view.cause === void 0 ? {} : { cause: view.cause }
1897
- });
1898
- if (registries.length < plan.length && signal?.aborted !== true && attributeFailure(kind, log, parsed) === "registry") continue;
1899
- const reason = view.timedOut ? `pnpm view timed out after ${String(this.inspectTimeoutMs)}ms` : log || printed || `pnpm view exited with ${String(view.exitCode)}`;
1900
- if (kind === "not-found" || kind === "no-matching-version") return refusedBy("not-found", reason);
1901
- if (kind === "network" || kind === "timeout") return refusedBy("network", reason);
1902
- return refusedBy("unknown", reason);
1903
- }
1904
- let answer;
1905
- try {
1906
- answer = JSON.parse(printed || "null");
1907
- } catch (error) {
1908
- return refusedBy("unknown", `unreadable pnpm view output: ${messageOf(error)}`);
1909
- }
1910
- const latest = Array.isArray(answer) ? answer.at(-1) : answer;
1911
- if (typeof latest !== "object" || latest === null) return refusedBy("unknown", "pnpm view answered no package");
1912
- const inspection = inspectionOf("registry", latest, current);
1913
- const named = inspection.name === void 0 ? {
1914
- ...inspection,
1915
- name: parsed.name
1916
- } : inspection;
1917
- if (!named.bundle) return refusedBy("not-a-bundle", `${named.name} declares no dsh.bundle`);
1918
- return named;
1919
- }
1920
- /* v8 ignore next -- the plan is never empty: every attempt returns or continues to the next */
1921
- throw new Error("no registry was asked");
2653
+ return {
2654
+ status: "refused",
2655
+ problem: "unknown",
2656
+ reason,
2657
+ attempts
2658
+ };
1922
2659
  }
1923
2660
  }
2661
+ /* v8 ignore next -- the plan is never empty: every attempt returns or continues to the next */
2662
+ throw new Error("no registry was asked");
1924
2663
  }
1925
2664
  /** Persist a plugin entry's desired enablement and apply it on live profiles.
1926
2665
  * @param id Loader entry identity returned by listPlugins.
@@ -1959,7 +2698,10 @@ let PluginManager = (() => {
1959
2698
  /**
1960
2699
  * Install a package using the same pnpm implementation as dsh plugin. GitHub
1961
2700
  * repositories get a connection check bounded by githubConnectionTimeoutMs before pnpm starts;
1962
- * only network failures or timeouts stop installation, while pnpm owns authentication and transport fallback. A run
2701
+ * only network failures or timeouts stop installation, and a stop streams the check's diagnostic
2702
+ * as the installation's install-log run under its request id, while pnpm owns authentication and transport fallback. An
2703
+ * HTTP(S) Git URL on another host is installed over SSH instead when access probes bounded by gitTransportTimeoutMs
2704
+ * find that only SSH can read it. A run
1963
2705
  * that fails, is cancelled, or adds a package without a bundle patch restores
1964
2706
  * `package.json` and `pnpm-lock.yaml` as they were; downloaded files can stay.
1965
2707
  * @param spec One package spec, including local paths relative to the invocation directory.
@@ -1998,11 +2740,14 @@ let PluginManager = (() => {
1998
2740
  let version;
1999
2741
  try {
2000
2742
  result.registries = [];
2001
- const connection = checkGithubConnection(parsedForRegistry(spec), this.profile.dir, {
2743
+ const parsed = parsedForRegistry(spec);
2744
+ const signal = AbortSignal.any([this.abort.signal, control.abort.signal]);
2745
+ const env = this.profile.packageManager?.env === void 0 ? {} : { env: this.profile.packageManager.env };
2746
+ const connection = checkGithubConnection(parsed, this.profile.dir, {
2002
2747
  timeoutMs: this.githubConnectionTimeoutMs,
2003
2748
  outputBytes: this.outputBytes,
2004
- signal: AbortSignal.any([this.abort.signal, control.abort.signal]),
2005
- ...this.profile.packageManager?.env === void 0 ? {} : { env: this.profile.packageManager.env }
2749
+ signal,
2750
+ ...env
2006
2751
  });
2007
2752
  this.packageOperations.add(connection);
2008
2753
  let connectionFailure;
@@ -2013,10 +2758,33 @@ let PluginManager = (() => {
2013
2758
  }
2014
2759
  if (stopped()) throw new InstallCancelledError();
2015
2760
  if (connectionFailure?.kind === "network" || connectionFailure?.kind === "timeout") {
2016
- result.packageResult = connectionFailure;
2761
+ const { argv, ...packageResult } = connectionFailure;
2762
+ result.packageResult = packageResult;
2017
2763
  result.failedAt = "spec-host";
2764
+ if (requestId !== void 0) this.ownerContext.emit("plugin-manager/install-log", {
2765
+ requestId,
2766
+ jobId: randomUUID(),
2767
+ argv,
2768
+ cwd: this.profile.dir,
2769
+ stream: "stderr",
2770
+ text: connectionFailure.output,
2771
+ exitCode: connectionFailure.timedOut === true ? null : connectionFailure.exitCode
2772
+ });
2018
2773
  throw new Error(connectionFailure.output);
2019
2774
  }
2775
+ const transport = chooseGitTransport(parsed, this.profile.dir, {
2776
+ timeoutMs: this.gitTransportTimeoutMs,
2777
+ signal,
2778
+ ...env
2779
+ });
2780
+ this.packageOperations.add(transport);
2781
+ let installSpec;
2782
+ try {
2783
+ installSpec = await transport;
2784
+ } finally {
2785
+ this.packageOperations.delete(transport);
2786
+ }
2787
+ if (stopped()) throw new InstallCancelledError();
2020
2788
  const plan = registryPlan(options?.registry, await this.registries());
2021
2789
  let run;
2022
2790
  let used = null;
@@ -2032,7 +2800,7 @@ let PluginManager = (() => {
2032
2800
  });
2033
2801
  run = await this.runPnpm([
2034
2802
  "add",
2035
- spec,
2803
+ installSpec,
2036
2804
  ...options?.saveExact === true ? ["--save-exact"] : [],
2037
2805
  ...registryArguments(registry)
2038
2806
  ], control.abort.signal, requestId);
@@ -2044,7 +2812,7 @@ let PluginManager = (() => {
2044
2812
  if (run.kind === void 0) break;
2045
2813
  delete result.failedAt;
2046
2814
  if (run.timedOut === true) break;
2047
- const failedAt = attributeFailure(run.kind, run.output, parsedForRegistry(spec));
2815
+ const failedAt = attributeFailure(run.kind, run.output, parsedForRegistry(installSpec));
2048
2816
  if (failedAt !== "other") result.failedAt = failedAt;
2049
2817
  if (failedAt !== "registry" || index === plan.length - 1) break;
2050
2818
  }
@@ -2284,6 +3052,7 @@ let PluginManager = (() => {
2284
3052
  const metadata = bundleManifest(name, this.profile.dir, this.profile.installAnchor);
2285
3053
  if (metadata === void 0) throw new ManagementFailure("not-bundle");
2286
3054
  if (enabled) {
3055
+ assertBundlePlatform(metadata.dsh?.bundle?.platforms, process.platform);
2287
3056
  const compatibility = evaluatePluginCompatibility(metadata, readProfileVersionExemptions(this.profile.dir));
2288
3057
  if (compatibility !== void 0 && !compatibility.exempted) throw new ManagementFailure("incompatible-version", [incompatiblePlugin(compatibility)]);
2289
3058
  this.bundleRows(name);
@@ -2317,7 +3086,7 @@ let PluginManager = (() => {
2317
3086
  } catch (_error) {
2318
3087
  return false;
2319
3088
  }
2320
- const protectedBundle = rows.some((row) => protectedModules.has(row.name) || `include:${row.id}` === this.ownerEntryId);
3089
+ const protectedBundle = rows.some((row) => PROTECTED_PLUGINS.has(row.name) || `include:${row.id}` === this.ownerEntryId);
2321
3090
  if (protectedBundle) this.managementBundles.add(name);
2322
3091
  return protectedBundle;
2323
3092
  }
@@ -2370,34 +3139,100 @@ let PluginManager = (() => {
2370
3139
  restartReason: restart
2371
3140
  };
2372
3141
  }
2373
- async change(operation, request, reason) {
2374
- return withFileLock(join(this.profile.dir, "package.json"), async () => {
2375
- this.abort.signal.throwIfAborted();
2376
- const before = this.diskState();
2377
- const result = {
2378
- ...request,
2379
- changed: false,
2380
- ...this.ownerContext.get("hmr") !== void 0 ? { application: "applied" } : {
2381
- application: "restart-required",
2382
- restartReason: "no-hmr"
2383
- }
2384
- };
2385
- try {
2386
- const outcome = await operation(result);
2387
- if (outcome !== void 0) result.application = outcome;
2388
- else if (result.application === "applied" && result.restartReason !== void 0) result.application = "restart-required";
2389
- } catch (error) {
2390
- if (error instanceof InstallCancelledError) result.application = "cancelled";
2391
- else {
2392
- result.application = "failed";
2393
- result.error = managementError(error);
3142
+ async change(operation, request, reason, identity) {
3143
+ const id = randomUUID();
3144
+ const target = identity === void 0 ? this.operationTarget(reason, request.target) : identity.target;
3145
+ const version = identity === void 0 ? this.operationVersion(reason, reason === "plugin" ? request.target : target) : identity.version;
3146
+ const facts = {
3147
+ id,
3148
+ reason,
3149
+ stage: request.stage,
3150
+ target,
3151
+ ...version === void 0 ? {} : { version },
3152
+ ...request.enabled === void 0 ? {} : { enabled: request.enabled }
3153
+ };
3154
+ this.reportOperation({
3155
+ ...facts,
3156
+ time: (/* @__PURE__ */ new Date()).toISOString(),
3157
+ phase: "started"
3158
+ });
3159
+ let settled;
3160
+ try {
3161
+ settled = await withFileLock(join(this.profile.dir, "package.json"), async () => {
3162
+ this.abort.signal.throwIfAborted();
3163
+ const before = this.diskState();
3164
+ const result = {
3165
+ ...request,
3166
+ changed: false,
3167
+ ...this.ownerContext.get("hmr") !== void 0 ? { application: "applied" } : {
3168
+ application: "restart-required",
3169
+ restartReason: "no-hmr"
3170
+ }
3171
+ };
3172
+ try {
3173
+ const outcome = await operation(result);
3174
+ if (outcome !== void 0) result.application = outcome;
3175
+ else if (result.application === "applied" && result.restartReason !== void 0) result.application = "restart-required";
3176
+ } catch (error) {
3177
+ if (error instanceof InstallCancelledError) result.application = "cancelled";
3178
+ else {
3179
+ result.application = "failed";
3180
+ result.error = managementError(error);
3181
+ }
2394
3182
  }
2395
- }
2396
- if (result.application !== "restart-required") delete result.restartReason;
2397
- result.changed = before !== this.diskState();
2398
- this.ownerContext.emit("plugin-manager/changed", { reason });
2399
- return result;
2400
- }, { waitMs: this.lockWaitMs });
3183
+ if (result.application !== "restart-required") delete result.restartReason;
3184
+ result.changed = before !== this.diskState();
3185
+ this.ownerContext.emit("plugin-manager/changed", { reason });
3186
+ return result;
3187
+ }, { waitMs: this.lockWaitMs });
3188
+ } catch (error) {
3189
+ this.reportOperation({
3190
+ ...facts,
3191
+ time: (/* @__PURE__ */ new Date()).toISOString(),
3192
+ phase: "unknown"
3193
+ });
3194
+ throw error;
3195
+ }
3196
+ const refusedVersion = reason === "install" ? settled.error?.incompatible?.find((plugin) => plugin.name === facts.target)?.version : void 0;
3197
+ const observedVersion = diagnosticVersion(settled.version ?? refusedVersion);
3198
+ this.reportOperation({
3199
+ ...facts,
3200
+ time: (/* @__PURE__ */ new Date()).toISOString(),
3201
+ phase: "settled",
3202
+ stage: settled.stage,
3203
+ target: settled.bundle === void 0 ? facts.target : installOperationTarget(settled.bundle),
3204
+ application: settled.application,
3205
+ changed: settled.changed,
3206
+ ...observedVersion === void 0 ? {} : { version: observedVersion },
3207
+ ...settled.error === void 0 ? {} : { errorCode: settled.error.code },
3208
+ ...settled.restartReason === void 0 ? {} : { restartReason: settled.restartReason }
3209
+ });
3210
+ return settled;
3211
+ }
3212
+ reportOperation(operation) {
3213
+ this.ownerContext.parallel("plugin-manager/operation", operation).catch((_error) => {
3214
+ console.error("dsh plugin-manager: operation diagnostic delivery failed");
3215
+ });
3216
+ }
3217
+ operationTarget(reason, target) {
3218
+ if (reason !== "plugin") {
3219
+ const name = installOperationTarget(target);
3220
+ return reason === "install" || name === target ? name : null;
3221
+ }
3222
+ return target.length <= 256 && [...this.ctx.loader.entries()].some((entry) => entry.id === target) ? target : null;
3223
+ }
3224
+ /** Read the request-time package version without preventing recovery from damaged metadata. */
3225
+ operationVersion(reason, target) {
3226
+ if (reason === "install" || target === null) return void 0;
3227
+ try {
3228
+ if (reason !== "plugin") return diagnosticVersion(bundleManifest(target, this.profile.dir, this.profile.installAnchor)?.version);
3229
+ const entry = [...this.ctx.loader.entries()].find((row) => row.id === target);
3230
+ const source = entry?.parent.tree.ctx.baseUrl;
3231
+ if (entry === void 0 || source === void 0) return void 0;
3232
+ return diagnosticVersion(this.ownerContext.get("pluginPackages")?.packageOf(entry.options.name, source)?.version);
3233
+ } catch (_error) {
3234
+ return;
3235
+ }
2401
3236
  }
2402
3237
  diskState() {
2403
3238
  return [