dsh-crate 0.5.3 → 0.5.4

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 (40) hide show
  1. package/client/client.js +2060 -459
  2. package/lib/body-progress.js +4 -3
  3. package/lib/changelog.js +15 -2
  4. package/lib/discovery-cache.js +210 -0
  5. package/lib/discovery-compatibility.js +91 -93
  6. package/lib/dsh-cli.js +36 -6
  7. package/lib/github-install-target.js +53 -0
  8. package/lib/hot.js +361 -27
  9. package/lib/index.js +6 -5
  10. package/lib/install.js +37 -0
  11. package/lib/patch.js +116 -72
  12. package/lib/pending-rows.js +3 -4
  13. package/lib/pnpm-compat.js +79 -1
  14. package/lib/proc-text.js +16 -1
  15. package/lib/recovery.js +2 -1
  16. package/lib/registry.js +24 -16
  17. package/lib/release-candidates.js +4 -0
  18. package/lib/routes.js +390 -131
  19. package/lib/themes.js +24 -8
  20. package/lib/types/body-progress.d.ts +2 -1
  21. package/lib/types/changelog.d.ts +10 -1
  22. package/lib/types/discovery-cache.d.ts +38 -0
  23. package/lib/types/discovery-compatibility.d.ts +16 -12
  24. package/lib/types/dsh-cli.d.ts +19 -2
  25. package/lib/types/github-install-target.d.ts +11 -0
  26. package/lib/types/hot.d.ts +87 -5
  27. package/lib/types/install.d.ts +19 -0
  28. package/lib/types/patch.d.ts +6 -2
  29. package/lib/types/registry.d.ts +9 -8
  30. package/lib/types/release-candidates.d.ts +2 -0
  31. package/lib/types/routes.d.ts +2 -2
  32. package/lib/types/themes.d.ts +7 -1
  33. package/lib/types/update-notification-settings.d.ts +5 -0
  34. package/lib/types/update-notifications.d.ts +51 -0
  35. package/lib/types/updates.d.ts +5 -1
  36. package/lib/update-notification-settings.js +6 -0
  37. package/lib/update-notifications.js +166 -0
  38. package/lib/updates.js +41 -11
  39. package/lib/verify.js +5 -2
  40. package/package.json +1 -1
@@ -0,0 +1,53 @@
1
+ import { resolveHeadCommit } from './accelerate.js';
2
+ import { readBodyWhileProgressing } from './body-progress.js';
3
+ import { marketFetch } from './net.js';
4
+ import { githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
5
+ import { NPM_NAME_RE } from './sources.js';
6
+ const ROOT_TARGET_RE = /^github:([A-Za-z0-9_.-]+\/([A-Za-z0-9_.-]+))(?:#([0-9a-f]{40}))?$/;
7
+ const FETCH_TIMEOUT_MS = 4000;
8
+ const MAX_MANIFEST_BYTES = 256 * 1024;
9
+ /**
10
+ * A package-like catalog name can point to the workspace root by mistake
11
+ * (#1208). Check a commit's manifest before handing that root to the host:
12
+ * Desktop can unpack it before refusing a package with no bundle.
13
+ *
14
+ * The curated catalog also lists entire collections (#18) and uses display
15
+ * names for ordinary Git plugins. Only a declared workspace with no DSH
16
+ * surface and a different root name gives enough evidence to refuse the add.
17
+ */
18
+ export async function mismatchedWorkspaceRoot(target, name, region) {
19
+ const source = ROOT_TARGET_RE.exec(target);
20
+ if (source === null || !NPM_NAME_RE.test(name) || source[2].toLowerCase() === name)
21
+ return null;
22
+ const repo = source[1];
23
+ const commit = source[3] ?? await resolveHeadCommit(repo, region);
24
+ if (commit === null)
25
+ return null;
26
+ const url = `https://raw.githubusercontent.com/${repo}/${commit}/package.json`;
27
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
28
+ for (const route of githubRoutesFor('raw', region)) {
29
+ if (signal.aborted)
30
+ break;
31
+ try {
32
+ const response = await marketFetch(throughProxy(route, url), { signal, redirect: 'manual' });
33
+ if (!response.ok) {
34
+ await response.body?.cancel();
35
+ continue;
36
+ }
37
+ const bytes = await readBodyWhileProgressing(response, FETCH_TIMEOUT_MS, 'GitHub package manifest', MAX_MANIFEST_BYTES);
38
+ const manifest = JSON.parse(new TextDecoder().decode(bytes));
39
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest))
40
+ continue;
41
+ rememberGithubRoute('raw', route);
42
+ const paths = Array.isArray(manifest.workspaces) ? manifest.workspaces : manifest.workspaces?.packages;
43
+ return manifest.dsh === undefined && typeof manifest.name === 'string' && NPM_NAME_RE.test(manifest.name)
44
+ && manifest.name !== name && Array.isArray(paths) && paths.some(path => typeof path === 'string' && path.trim() !== '')
45
+ ? manifest.name
46
+ : null;
47
+ }
48
+ catch {
49
+ // A missing or inaccessible manifest cannot establish what the root is.
50
+ }
51
+ }
52
+ return null;
53
+ }
package/lib/hot.js CHANGED
@@ -25,16 +25,16 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
25
25
  };
26
26
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
27
27
  import { createRequire } from 'node:module';
28
- import { join } from 'node:path';
29
- import { pathToFileURL } from 'node:url';
28
+ import { dirname, join } from 'node:path';
29
+ import { fileURLToPath, pathToFileURL } from 'node:url';
30
+ import { isUpdateCheckIntervalHours } from './update-notification-settings.js';
30
31
  import { asChannel } from './channels.js';
31
32
  import { asRegion, normalizeGithubProxy } from './regions.js';
32
33
  import { findDshInstallDir } from './dsh-install.js';
33
34
  import { logEvent } from './log.js';
34
35
  import { bundlePatchTargets, declaredBundlePatchFiles, entryArtifactExists } from './profile.js';
35
- import { stateDir, statePath } from './state.js';
36
36
  /**
37
- * Profile-scoped resolution for hot-mount rows: turn a bare package name into
37
+ * Profile-scoped resolution for hot-mount imports: turn a bare package name into
38
38
  * the absolute `file://` entry URL of the package just installed into
39
39
  * `profileDir`.
40
40
  *
@@ -48,7 +48,7 @@ import { stateDir, statePath } from './state.js';
48
48
  * back to "restart required", blaming the plugin for what is a resolution
49
49
  * anchor problem.
50
50
  *
51
- * Resolving the row name HERE, against the profile the package was actually
51
+ * Resolving the module at import time, against the profile it was actually
52
52
  * installed into, is anchor-independent: `require.resolve` walks
53
53
  * `profileDir/node_modules` natively, so the tree hands the loader a
54
54
  * `file://` URL needing no further resolution. Non-bare specifiers (relative
@@ -60,8 +60,8 @@ import { stateDir, statePath } from './state.js';
60
60
  * whose entry cannot be located via `require.resolve` (no `main`/exports —
61
61
  * the market's own `entryArtifactExists` heuristic covers those shapes before
62
62
  * an install is accepted) is not something this resolver should guess about.
63
- * Client-only shims never reach this function (their rows are replaced by a
64
- * no-op host module before the file is written).
63
+ * Client-only shims never reach this function: their import returns a no-op
64
+ * host module before attempting package resolution.
65
65
  */
66
66
  export function resolveProfileEntry(profileDir, name) {
67
67
  if (!name || name.startsWith('.') || name.startsWith('cordis:') || name.startsWith('file://'))
@@ -82,10 +82,11 @@ export function resolveProfileEntry(profileDir, name) {
82
82
  return name;
83
83
  }
84
84
  }
85
- // File URLs may contain apostrophes; YAML single-quoted scalars escape them by doubling.
85
+ // Row names and ids may contain apostrophes; YAML single-quoted scalars double them.
86
86
  function yamlSingleQuoted(value) {
87
87
  return value.replace(/'/g, "''");
88
88
  }
89
+ const HOT_DIR = '.dsh-crate';
89
90
  /**
90
91
  * Ceiling for one hot-mount activation, env-overridable like the install
91
92
  * timeout in dsh-cli.ts. An activation that exceeds it is treated as wedged
@@ -94,6 +95,12 @@ function yamlSingleQuoted(value) {
94
95
  */
95
96
  const HOT_MOUNT_TIMEOUT_MS = Number(process.env.DSH_MARKET_HOT_MOUNT_TIMEOUT_MS) || 10000;
96
97
  let hotTreeClass;
98
+ // Cordis declares FiberState as a const enum, so the installed host exposes its numeric values.
99
+ const FAILED_FIBER_STATE = 3;
100
+ /** Live hot-mount trees by input file URL, so an unmount can reach the entries. */
101
+ const hotTrees = new Map();
102
+ /** Package name -> the input file URL of its live hot mount. */
103
+ const hotTreeOf = new Map();
97
104
  /**
98
105
  * The Include subclass, built once per process; null when the loader's include
99
106
  * plugin is not importable (older harness) — callers fall back to restart.
@@ -118,12 +125,19 @@ async function loadHotTreeClass() {
118
125
  if (Include === undefined)
119
126
  throw new Error('no Include export');
120
127
  class MarketHotTree extends Include {
128
+ profileDir;
129
+ constructor(...args) {
130
+ super(...args);
131
+ const path = args[1].path;
132
+ this.profileDir = dirname(dirname(fileURLToPath(path)));
133
+ hotTrees.set(path, this);
134
+ }
121
135
  /** Runtime-only mount list; the bundle layer owns persistence. */
122
136
  write() { }
123
137
  import(name, getOuterStack) {
124
138
  if (shimNames.has(name))
125
139
  return { name, apply: () => { } };
126
- return super.import(name, getOuterStack);
140
+ return super.import(resolveProfileEntry(this.profileDir, name), getOuterStack);
127
141
  }
128
142
  }
129
143
  hotTreeClass = MarketHotTree;
@@ -233,7 +247,7 @@ export function patchBlockerReason(blocker, key) {
233
247
  * `state.json` (disable choices + groups) deliberately survives.
234
248
  */
235
249
  export function cleanHotDir(profileDir) {
236
- const dir = stateDir(profileDir);
250
+ const dir = join(profileDir, HOT_DIR);
237
251
  let entries;
238
252
  try {
239
253
  entries = readdirSync(dir);
@@ -247,7 +261,7 @@ export function cleanHotDir(profileDir) {
247
261
  }
248
262
  }
249
263
  function stateFile(profileDir) {
250
- return statePath(profileDir, 'state.json');
264
+ return join(profileDir, HOT_DIR, 'state.json');
251
265
  }
252
266
  const BROKEN_REASONS = new Set(['incomplete-build-locked', 'incomplete-build-cancelled']);
253
267
  /** The on-disk shape of {@link MarketState.brokenPlugins}, sanitized. */
@@ -310,6 +324,69 @@ function blockedNames(value) {
310
324
  function updateExemptNames(value) {
311
325
  return cappedPackageNames(value, MAX_UPDATE_EXEMPT);
312
326
  }
327
+ /**
328
+ * Upper bound on the install-time map (#1142). One entry per package the
329
+ * market itself installed, and a profile with 500 of those is already an
330
+ * outlier; the cap keeps state.json from growing with every plugin the user
331
+ * ever tried and removed.
332
+ */
333
+ export const MAX_INSTALL_TIMES = 500;
334
+ /** An ISO 8601 timestamp, normalized; anything else is "not recorded". */
335
+ function installTimestamp(value) {
336
+ if (typeof value !== 'string' || value === '')
337
+ return undefined;
338
+ const at = Date.parse(value);
339
+ if (!Number.isFinite(at))
340
+ return undefined;
341
+ return new Date(at).toISOString();
342
+ }
343
+ /**
344
+ * Sanitize the stored install-time map. A hand-edited file is not trusted:
345
+ * a key that is not a name, a value that is not an object, and a stamp that
346
+ * is not a timestamp are all dropped rather than carried into the UI, where
347
+ * an unparseable date would sort as `NaN` and land in the middle of the list.
348
+ *
349
+ * The cap keeps the entries with the most recent activity, not the first
350
+ * ones written: the map is a lookup for "when did I install this", and the
351
+ * oldest 50 installs are exactly the ones nobody is asking about.
352
+ */
353
+ function installTimesFromUnknown(value) {
354
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
355
+ return undefined;
356
+ const out = {};
357
+ for (const [name, raw] of Object.entries(value)) {
358
+ if (name === '' || name.length > MAX_BLOCKED_NAME)
359
+ continue;
360
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
361
+ continue;
362
+ const record = raw;
363
+ const installedAt = installTimestamp(record.installedAt);
364
+ const updatedAt = installTimestamp(record.updatedAt);
365
+ // An entry with neither stamp says nothing; keeping it would list a row
366
+ // that looks known and sorts nowhere.
367
+ if (installedAt === undefined && updatedAt === undefined)
368
+ continue;
369
+ out[name] = {
370
+ ...(installedAt === undefined ? {} : { installedAt }),
371
+ ...(updatedAt === undefined ? {} : { updatedAt }),
372
+ };
373
+ }
374
+ const names = Object.keys(out);
375
+ if (names.length === 0)
376
+ return undefined;
377
+ return trimInstallTimes(out);
378
+ }
379
+ /** Keep the cap, dropping the entries nobody is asking about (oldest first). */
380
+ function trimInstallTimes(map) {
381
+ const names = Object.keys(map);
382
+ if (names.length === 0)
383
+ return undefined;
384
+ if (names.length <= MAX_INSTALL_TIMES)
385
+ return map;
386
+ const stamp = (entry) => Date.parse(entry.updatedAt ?? entry.installedAt ?? '');
387
+ const recent = names.sort((a, b) => stamp(map[b]) - stamp(map[a])).slice(0, MAX_INSTALL_TIMES);
388
+ return Object.fromEntries(recent.map(name => [name, map[name]]));
389
+ }
313
390
  /** A POSIX-looking environment variable name: the name part of `KEY=value`. */
314
391
  const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
315
392
  /** Upper bound on one pinned env value, so state.json cannot balloon. */
@@ -379,6 +456,7 @@ export function readMarketState(profileDir) {
379
456
  }
380
457
  const githubProxy = normalizeGithubProxy(state.githubProxy);
381
458
  const brokenPlugins = brokenPluginsFromUnknown(state.brokenPlugins);
459
+ const installTimes = installTimesFromUnknown(state.installTimes);
382
460
  // The order and the map are two halves of one fact, and a state file can
383
461
  // carry them out of step (#964): the UI then lists a group the routes
384
462
  // cannot find, so "assign to" and even "delete" answer group-not-found
@@ -403,8 +481,11 @@ export function readMarketState(profileDir) {
403
481
  favorites: favoriteUrls(state.favorites),
404
482
  blocked: blockedNames(state.blocked),
405
483
  updateExempt: updateExemptNames(state.updateExempt),
484
+ ...(typeof state.backgroundUpdateChecks === 'boolean' ? { backgroundUpdateChecks: state.backgroundUpdateChecks } : {}),
485
+ ...(isUpdateCheckIntervalHours(state.backgroundUpdateIntervalHours) ? { backgroundUpdateIntervalHours: state.backgroundUpdateIntervalHours } : {}),
406
486
  ...(githubProxy === null ? {} : { githubProxy }),
407
487
  ...(brokenPlugins === undefined ? {} : { brokenPlugins }),
488
+ ...(installTimes === undefined ? {} : { installTimes }),
408
489
  // true AND false are both preserved: on a host with no settings page
409
490
  // this switch is the market's only entry, so "the user turned it off"
410
491
  // must be distinguishable from "nobody has chosen yet" (#846).
@@ -489,7 +570,17 @@ function publishFile(path, contents) {
489
570
  * the whole document" safe for callers that only hold part of it.
490
571
  */
491
572
  export function writeMarketState(profileDir, state) {
492
- mkdirSync(stateDir(profileDir), { recursive: true, mode: 0o700 });
573
+ writeState(profileDir, state, false);
574
+ }
575
+ /**
576
+ * `ownStamps` is true only for the three stamp functions below. Every other
577
+ * writer holds a whole-state object that may be minutes old (the routes keep
578
+ * one from boot and save it whole, #435), so a stamp it carries is a stale
579
+ * copy: letting it through put the install date of the last install back to
580
+ * what boot saw.
581
+ */
582
+ function writeState(profileDir, state, ownStamps) {
583
+ mkdirSync(join(profileDir, HOT_DIR), { recursive: true, mode: 0o700 });
493
584
  const onDisk = readMarketState(profileDir);
494
585
  // `?? {}` only for the type: MarketState declares notes optional, while
495
586
  // readMarketState always returns an object.
@@ -505,6 +596,8 @@ export function writeMarketState(profileDir, state) {
505
596
  const favorites = state.favorites ?? onDisk.favorites ?? [];
506
597
  const blocked = state.blocked ?? onDisk.blocked ?? [];
507
598
  const updateExempt = state.updateExempt ?? onDisk.updateExempt ?? [];
599
+ const backgroundUpdateChecks = state.backgroundUpdateChecks ?? onDisk.backgroundUpdateChecks;
600
+ const backgroundUpdateIntervalHours = state.backgroundUpdateIntervalHours ?? onDisk.backgroundUpdateIntervalHours;
508
601
  // This field does have a clear action ("restore automatic"). As with
509
602
  // regionAuto, omission preserves while an explicit undefined removes it.
510
603
  const githubProxy = Object.prototype.hasOwnProperty.call(state, 'githubProxy')
@@ -513,6 +606,9 @@ export function writeMarketState(profileDir, state) {
513
606
  const broken = Object.prototype.hasOwnProperty.call(state, 'brokenPlugins')
514
607
  ? state.brokenPlugins
515
608
  : onDisk.brokenPlugins;
609
+ // Only the stamp functions replace the map (an empty one, after the last
610
+ // uninstall, included); every other writer leaves what is on disk alone.
611
+ const installTimes = ownStamps ? state.installTimes : onDisk.installTimes;
516
612
  const sidebarEntry = Object.prototype.hasOwnProperty.call(state, 'sidebarEntry')
517
613
  ? state.sidebarEntry
518
614
  : onDisk.sidebarEntry;
@@ -531,6 +627,8 @@ export function writeMarketState(profileDir, state) {
531
627
  ...(favorites.length > 0 ? { favorites } : {}),
532
628
  ...(blocked.length > 0 ? { blocked } : {}),
533
629
  ...(updateExempt.length > 0 ? { updateExempt } : {}),
630
+ ...(typeof backgroundUpdateChecks === 'boolean' ? { backgroundUpdateChecks } : {}),
631
+ ...(isUpdateCheckIntervalHours(backgroundUpdateIntervalHours) ? { backgroundUpdateIntervalHours } : {}),
534
632
  ...(Object.keys(notes).length > 0 ? { notes } : {}),
535
633
  // Omitted while unchosen, so "never picked" survives a round trip and
536
634
  // keeps deriving from the running build — but only when disk has not
@@ -545,6 +643,9 @@ export function writeMarketState(profileDir, state) {
545
643
  // githubProxy above, and the one a repaired plugin needs: the entry
546
644
  // exists only while the declaration is still missing.
547
645
  ...(broken === undefined ? {} : { brokenPlugins: broken }),
646
+ // Omitted while empty, so a profile that never installed through the
647
+ // market keeps a state file with no such key at all.
648
+ ...(installTimes === undefined || Object.keys(installTimes).length === 0 ? {} : { installTimes }),
548
649
  // Written for both answers: on a host with no settings page this switch
549
650
  // is the market's only entry, so a deliberate OFF has to survive a reload
550
651
  // instead of being read back as "never chosen" (#846).
@@ -578,10 +679,89 @@ export function readDisabledThemes(profileDir) {
578
679
  export function writeDisabledThemes(profileDir, disabled) {
579
680
  writeDisabled(profileDir, disabled);
580
681
  }
581
- /** Package names currently live through a market hot mount (patch or shim). */
682
+ /**
683
+ * The market installed these packages just now (#1142): both stamps are this
684
+ * moment, because the first install is also the last change so far.
685
+ */
686
+ export function recordInstalled(profileDir, names, at = new Date()) {
687
+ const stamp = at.toISOString();
688
+ const state = readMarketState(profileDir);
689
+ const map = { ...state.installTimes };
690
+ for (const name of names) {
691
+ if (name === '')
692
+ continue;
693
+ map[name] = { installedAt: stamp, updatedAt: stamp };
694
+ }
695
+ state.installTimes = trimInstallTimes(map);
696
+ writeState(profileDir, state, true);
697
+ }
698
+ /**
699
+ * An update of these packages landed: only the update stamp moves.
700
+ *
701
+ * A package with no entry keeps `installedAt` absent — the market never saw
702
+ * it installed, and "when I first noticed it" is a different fact. Writing it
703
+ * here would make the sort report a guessed install order as history.
704
+ */
705
+ export function recordUpdated(profileDir, names, at = new Date()) {
706
+ const stamp = at.toISOString();
707
+ const state = readMarketState(profileDir);
708
+ const map = { ...state.installTimes };
709
+ for (const name of names) {
710
+ if (name === '')
711
+ continue;
712
+ map[name] = { ...map[name], updatedAt: stamp };
713
+ }
714
+ state.installTimes = trimInstallTimes(map);
715
+ writeState(profileDir, state, true);
716
+ }
717
+ /** The package is gone: its stamps must not outlive it. */
718
+ export function forgetInstalled(profileDir, name) {
719
+ const state = readMarketState(profileDir);
720
+ if (state.installTimes === undefined || state.installTimes[name] === undefined)
721
+ return;
722
+ const map = { ...state.installTimes };
723
+ delete map[name];
724
+ state.installTimes = trimInstallTimes(map);
725
+ writeState(profileDir, state, true);
726
+ }
727
+ /** Package names whose hot-mount trees are still attached and can be removed. */
582
728
  export function listHotMounts() {
583
729
  return [...hotHandles.keys()];
584
730
  }
731
+ function mountedFile(packageName, profileDir) {
732
+ const file = hotTreeOf.get(packageName);
733
+ if (file === undefined || profileDir === undefined)
734
+ return file;
735
+ return dirname(fileURLToPath(file)) === join(profileDir, HOT_DIR) ? file : undefined;
736
+ }
737
+ /** Report a failed child only when it belongs to this package's hot-mount tree. */
738
+ export function hotMountFailure(packageName, profileDir) {
739
+ const file = mountedFile(packageName, profileDir);
740
+ if (file === undefined)
741
+ return null;
742
+ const tree = hotTrees.get(file);
743
+ if (typeof tree?.entries !== 'function')
744
+ return null;
745
+ const failed = [];
746
+ try {
747
+ for (const entry of tree.entries()) {
748
+ if (entry.fiber?.state === FAILED_FIBER_STATE && typeof entry.id === 'string')
749
+ failed.push(entry.id);
750
+ }
751
+ }
752
+ catch {
753
+ // Older loaders can have an unreadable activation state.
754
+ return null;
755
+ }
756
+ if (failed.length === 0)
757
+ return null;
758
+ const components = failed.join(', ');
759
+ return `组件 ${components} 启动失败。请在诊断中查看原因。 / Components failed to start (${components}). Check Diagnostics for the error.`;
760
+ }
761
+ /** Hot mounts the market can report as live. */
762
+ export function listLiveHotMounts() {
763
+ return listHotMounts().filter(name => hotMountFailure(name) === null);
764
+ }
585
765
  let hotSequence = 0;
586
766
  const hotHandles = new Map();
587
767
  /** Activation did not settle within HOT_MOUNT_TIMEOUT_MS. */
@@ -603,6 +783,107 @@ function raceActivationTimeout(awaitable) {
603
783
  Promise.resolve(awaitable).then(value => { clearTimeout(timer); resolve(value); }, error => { clearTimeout(timer); reject(error); });
604
784
  });
605
785
  }
786
+ /** Cap on host log lines attached to one hot mount (#1197). */
787
+ const MOUNT_LOG_MAX = 5;
788
+ const MOUNT_LOG_LINE_MAX = 200;
789
+ /** Render one structured host record as a single log line. */
790
+ function mountLogLine(message) {
791
+ const parts = Array.isArray(message.args) ? message.args : [message.args];
792
+ const text = parts
793
+ .filter(part => part !== undefined && part !== null)
794
+ .map(part => {
795
+ if (typeof part === 'string')
796
+ return part;
797
+ // Align with `Logger.format`: an Error records its stack (or message as
798
+ // a fallback), never the empty object `JSON.stringify` yields. cordis'
799
+ // `_method` hands the raw `args: [Error]` to exporters without
800
+ // formatting, so this is what keeps `the host logged this while
801
+ // mounting — name: Error: ...` readable in the exportable log.
802
+ if (part instanceof Error)
803
+ return part.stack || part.message;
804
+ try {
805
+ return JSON.stringify(part) ?? String(part);
806
+ }
807
+ catch {
808
+ return String(part);
809
+ }
810
+ })
811
+ .join(' ');
812
+ const name = typeof message.name === 'string' && message.name !== '' ? `${message.name}: ` : '';
813
+ return `${name}${text}`.slice(0, MOUNT_LOG_LINE_MAX);
814
+ }
815
+ /**
816
+ * Collect the host's warn/error records for the duration of one hot mount.
817
+ *
818
+ * `Fiber#await()` resolves normally when an entry is still waiting on a
819
+ * service that never arrives (#1197): the mount reports live, and the only
820
+ * trace of the problem is whatever the host logged while composing it.
821
+ * Recording those lines next to the `live` event keeps that trace in the
822
+ * exportable log without changing the verdict — the mount really did finish,
823
+ * and "this entry was the one that complained" is not something the market can
824
+ * prove yet.
825
+ *
826
+ * Attribution stays open on purpose: the exporter is process-wide, so these
827
+ * lines read as "logged while mounting", not as this entry's own records.
828
+ * Filtering on a name prefix would bake in a naming contract the host has not
829
+ * promised.
830
+ *
831
+ * @param ctx - host context; the sink is skipped when there is no `exporter`.
832
+ * @returns the collected lines plus a disposer that is safe to call twice.
833
+ */
834
+ function watchMountLog(ctx) {
835
+ const logger = ctx.logger;
836
+ const register = logger?.exporter;
837
+ if (logger === undefined || typeof register !== 'function')
838
+ return { finish: () => [], stop: () => { } };
839
+ const lines = [];
840
+ let disposable;
841
+ try {
842
+ disposable = register.call(logger, {
843
+ // Ask for every level and filter below: the sink exists to catch
844
+ // warnings, and the service's own default threshold (`1`) drops them
845
+ // before `export` is ever called.
846
+ levels: { default: 3 },
847
+ export(message) {
848
+ if (lines.length >= MOUNT_LOG_MAX)
849
+ return;
850
+ if (message?.type !== 'warn' && message?.type !== 'error')
851
+ return;
852
+ lines.push(mountLogLine(message));
853
+ },
854
+ });
855
+ }
856
+ catch {
857
+ // A host whose exporter rejects this sink shape is not a mount failure.
858
+ return { finish: () => [], stop: () => { } };
859
+ }
860
+ let stopped = false;
861
+ const stop = () => {
862
+ if (stopped)
863
+ return;
864
+ stopped = true;
865
+ try {
866
+ if (typeof disposable === 'function')
867
+ void disposable();
868
+ else if (disposable !== null && typeof disposable === 'object' && 'dispose' in disposable) {
869
+ void disposable.dispose();
870
+ }
871
+ }
872
+ catch {
873
+ // The mount result matters more than the sink teardown.
874
+ }
875
+ };
876
+ return {
877
+ finish: () => {
878
+ stop();
879
+ return lines.slice();
880
+ },
881
+ stop,
882
+ };
883
+ }
884
+ function mountResult(failure) {
885
+ return failure === null ? { ok: true, reason: null } : { ok: false, reason: failure, retained: true };
886
+ }
606
887
  /**
607
888
  * Dispose a plugin hot-mounted earlier in this session, removing it from the
608
889
  * running composition immediately.
@@ -618,7 +899,29 @@ export async function hotUnmount(packageName) {
618
899
  // state instead of reusing a handle already being disposed.
619
900
  hotHandles.delete(packageName);
620
901
  shimNames.delete(packageName);
621
- const disposal = Promise.resolve().then(() => handle.dispose());
902
+ const treeKey = hotTreeOf.get(packageName);
903
+ hotTreeOf.delete(packageName);
904
+ const tree = treeKey === undefined ? undefined : hotTrees.get(treeKey);
905
+ if (treeKey !== undefined)
906
+ hotTrees.delete(treeKey);
907
+ const disposal = Promise.resolve().then(async () => {
908
+ // Switch the tree's entries off BEFORE disposing the tree (#1188).
909
+ // Disposing the tree stops the plugins but leaves each entry still holding
910
+ // its fiber, and the host's client-module registry keeps serving a package
911
+ // to the page for as long as an entry names a live fiber: the browser half
912
+ // of a plugin switched off here stayed on screen, across reloads, until
913
+ // the host restarted. Updating the entry itself is the path the host's own
914
+ // entries take when they are switched off, and the registry follows it.
915
+ if (tree !== undefined) {
916
+ for (const entry of [...tree.entries()]) {
917
+ try {
918
+ await entry.update({ disabled: true }, false, true);
919
+ }
920
+ catch { /* the dispose below still stops it */ }
921
+ }
922
+ }
923
+ await handle.dispose();
924
+ });
622
925
  // Same ceiling as mounting, and the same reason (#582, measured class of
623
926
  // report): a plugin whose teardown waits for something that never arrives
624
927
  // used to hold the toggle route open forever, and every later operation
@@ -669,6 +972,9 @@ export async function hotUnmount(packageName) {
669
972
  */
670
973
  export async function hotMount(ctx, profileDir, packageName) {
671
974
  try {
975
+ if (mountedFile(packageName, profileDir) !== undefined) {
976
+ return mountResult(hotMountFailure(packageName, profileDir));
977
+ }
672
978
  const HotTree = await loadHotTreeClass();
673
979
  if (HotTree === null) {
674
980
  return {
@@ -740,25 +1046,36 @@ export async function hotMount(ctx, profileDir, packageName) {
740
1046
  shimNames.add(packageName);
741
1047
  rows = [{ id: `client-${packageName.replace(/[^A-Za-z0-9_.-]/g, '-')}`, name: packageName }];
742
1048
  }
743
- const dir = stateDir(profileDir);
1049
+ const dir = join(profileDir, HOT_DIR);
744
1050
  mkdirSync(dir, { recursive: true, mode: 0o700 });
745
1051
  hotSequence += 1;
746
1052
  const file = join(dir, `hot-${String(hotSequence)}.yml`);
747
- // Rows carry ABSOLUTE file:// entry URLs, resolved against this profile:
748
- // the loader's own parent-walk (from the host closure) can never reach
749
- // `profileDir/node_modules`, so bare names in the file would fail to
750
- // import on closure-hosted loaders. The file remains a faithful record —
751
- // `cleanHotDir` wipes it on every boot and the bundle layer owns
752
- // persistence, so nothing reads these files back.
1053
+ // Keep the package identity on loader entries: the host's client-module
1054
+ // registry uses it to find package.json and the browser bundle. Only the
1055
+ // import resolves against this profile, so closure-hosted loaders still
1056
+ // receive an absolute module URL without making it the plugin's name.
753
1057
  const yml = rows
754
- .map(row => `- id: '${yamlSingleQuoted(`mkt-${row.id}`)}'\n name: '${yamlSingleQuoted(resolveProfileEntry(profileDir, row.name))}'\n`)
1058
+ .map(row => `- id: '${yamlSingleQuoted(`mkt-${row.id}`)}'\n name: '${yamlSingleQuoted(row.name)}'\n`)
755
1059
  .join('');
756
1060
  writeFileSync(file, yml);
757
- const handle = ctx.plugin(HotTree, { path: pathToFileURL(file).href });
1061
+ const mountLog = watchMountLog(ctx);
1062
+ let handle;
1063
+ try {
1064
+ handle = ctx.plugin(HotTree, { path: pathToFileURL(file).href });
1065
+ }
1066
+ catch (error) {
1067
+ // `ctx.plugin()` bails out before creating anything when the fiber is no
1068
+ // longer active (a mount issued during teardown) or the plugin is
1069
+ // rejected. The sink is already registered by then, so release it here:
1070
+ // the outer catch reports the failure, it does not clean this up.
1071
+ mountLog.stop();
1072
+ throw error;
1073
+ }
758
1074
  try {
759
1075
  await raceActivationTimeout(handle.await());
760
1076
  }
761
1077
  catch (error) {
1078
+ mountLog.stop();
762
1079
  // A failed or wedged mount must leave NOTHING behind: the disposed
763
1080
  // subtree stops retrying the import, and the input file is removed so
764
1081
  // it cannot be re-imported by a later boot or replay (a leftover file
@@ -772,6 +1089,7 @@ export async function hotMount(ctx, profileDir, packageName) {
772
1089
  rmSync(file, { force: true });
773
1090
  }
774
1091
  catch { /* best effort */ }
1092
+ hotTrees.delete(pathToFileURL(file).href);
775
1093
  if (error instanceof ActivationTimeout) {
776
1094
  // A wedged activation would otherwise hold this request open forever:
777
1095
  // the route's `finally { installing = false }` never runs, so every
@@ -782,9 +1100,25 @@ export async function hotMount(ctx, profileDir, packageName) {
782
1100
  throw error;
783
1101
  }
784
1102
  hotHandles.set(packageName, handle);
785
- ctx.logger?.info?.(`[dsh-crate] hot-mounted ${packageName}`);
786
- logEvent('info', 'hot-mount', `${packageName}: live${shimNames.has(packageName) ? ' (client-only shim)' : ''}`);
787
- return { ok: true, reason: null };
1103
+ hotTreeOf.set(packageName, pathToFileURL(file).href);
1104
+ const failure = hotMountFailure(packageName, profileDir);
1105
+ const lines = mountLog.finish();
1106
+ if (failure === null) {
1107
+ ctx.logger?.info?.(`[dsh-crate] hot-mounted ${packageName}`);
1108
+ logEvent('info', 'hot-mount', `${packageName}: live${shimNames.has(packageName) ? ' (client-only shim)' : ''}`);
1109
+ }
1110
+ else {
1111
+ ctx.logger?.warn(`[dsh-crate] ${packageName}: ${failure}`);
1112
+ logEvent('warn', 'hot-mount', `${packageName}: ${failure}`);
1113
+ }
1114
+ // A mount that resolves while an entry is still waiting on a service is
1115
+ // "live" by the host's own verdict, so the verdict stands — but the lines
1116
+ // the host logged meanwhile are the only record of why the entry never
1117
+ // started serving (#1197).
1118
+ for (const line of lines) {
1119
+ logEvent('warn', 'hot-mount', `${packageName}: the host logged this while mounting — ${line}`);
1120
+ }
1121
+ return mountResult(failure);
788
1122
  }
789
1123
  catch (error) {
790
1124
  const message = error instanceof Error ? error.message : String(error);
@@ -940,7 +1274,7 @@ export function patchLayerManages(controls, name) {
940
1274
  * @returns true when a directory was there to remove.
941
1275
  */
942
1276
  export function purgeMarketState(profileDir) {
943
- const dir = stateDir(profileDir);
1277
+ const dir = join(profileDir, HOT_DIR);
944
1278
  try {
945
1279
  rmSync(dir, { recursive: true, force: true });
946
1280
  return true;
package/lib/index.js CHANGED
@@ -328,9 +328,9 @@ export function apply(ctx, config) {
328
328
  repairTimer.unref?.();
329
329
  return async () => {
330
330
  clearTimeout(repairTimer);
331
- disposeRoutes();
331
+ const routesDisposed = disposeRoutes();
332
332
  restoreTrustedHosts();
333
- await runtime.dispose();
333
+ await Promise.all([routesDisposed, runtime.dispose()]);
334
334
  };
335
335
  }, 'dsh-crate: official Desktop routes and package operations');
336
336
  return;
@@ -368,8 +368,9 @@ export function apply(ctx, config) {
368
368
  const restoreTrustedHosts = useTrustedHosts(ctx);
369
369
  const disposeRoutes = mountMarketRoutes(host, resolved, undefined, agentsLookupOf(ctx));
370
370
  return () => {
371
- disposeRoutes();
371
+ const routesDisposed = disposeRoutes();
372
372
  restoreTrustedHosts();
373
+ return routesDisposed;
373
374
  };
374
375
  }, 'dsh-crate: http routes');
375
376
  return;
@@ -420,9 +421,9 @@ export function apply(ctx, config) {
420
421
  // market can ask for a replay instead of mounting a second entry.
421
422
  const disposeRoutes = mountMarketRoutes(host, resolved, runtime, agentsLookupOf(ctx), desktopProfiles.pluginActivation);
422
423
  return async () => {
423
- disposeRoutes();
424
+ const routesDisposed = disposeRoutes();
424
425
  restoreTrustedHosts();
425
- await runtime.dispose();
426
+ await Promise.all([routesDisposed, runtime.dispose()]);
426
427
  };
427
428
  }, 'dsh-crate: Desktop http routes and package operations');
428
429
  });