dshmarket 1.79.0 → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/client.js CHANGED
@@ -18335,7 +18335,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18335
18335
  }
18336
18336
  //#endregion
18337
18337
  //#region src/client/client-version.ts
18338
- const CLIENT_VERSION = "1.79.0";
18338
+ const CLIENT_VERSION = "1.80.0";
18339
18339
  /** Numeric x.y.z comparison; prerelease tags are ignored. null if either is not a version. */
18340
18340
  function compareMarketVersions(a, b) {
18341
18341
  const parse = (v) => {
@@ -18357,6 +18357,37 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18357
18357
  return (compareMarketVersions(clientVersion, serverVersion) ?? 0) > 0;
18358
18358
  }
18359
18359
  /**
18360
+ * Ask the server to swap in the version the page already is (POST
18361
+ * /dsh-market/reload-self), and wait until it has.
18362
+ *
18363
+ * 200 means the new server half is serving. 202 means the host was busy with
18364
+ * another change and will do it when that ends: poll /status until the
18365
+ * version catches up, within a bound. Any other answer carries the reason in
18366
+ * plain words (`error`, zh / en); an empty one means the server could not say.
18367
+ */
18368
+ async function requestSelfReload(post, readVersion, options = {}) {
18369
+ const res = await post();
18370
+ if (res.status !== 202) {
18371
+ if (res.ok) return { ok: true };
18372
+ const { body } = await readMarketJson(res);
18373
+ return {
18374
+ ok: false,
18375
+ error: typeof body.error === "string" ? body.error : ""
18376
+ };
18377
+ }
18378
+ const pollMs = options.pollMs ?? 1e3;
18379
+ const deadline = Date.now() + (options.timeoutMs ?? 12e4);
18380
+ while (Date.now() < deadline) {
18381
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
18382
+ const version = await readVersion().catch(() => null);
18383
+ if (version !== null && !serverIsBehind(version)) return { ok: true };
18384
+ }
18385
+ return {
18386
+ ok: false,
18387
+ error: ""
18388
+ };
18389
+ }
18390
+ /**
18360
18391
  * Read a JSON reply; an empty or non-JSON body from a route this server does
18361
18392
  * not have (the host answers 404/405 with nothing) becomes `stale-server`,
18362
18393
  * never a JSON parse error.
@@ -18666,9 +18697,34 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18666
18697
  */
18667
18698
  const MARKET_OFFER_CLOSED_KEY = "dshm-market-offer-closed";
18668
18699
  function MarketHead({ c }) {
18669
- const { activationWarnings, approveAndRetry, askRestore, backupBusy, backupMessage, blockedNames, bootId, brokenPluginNames, brokenPlugins, buildsSkipped, busyUrl, checkingUpdates, checkoutRecovery, compatibilityNotice, compatibilitySummary, configNamespaceIssues, data, debuggerLatch, describePlugin, dismissBrokenError, dismissBrokenPlugin, dismissingBroken, doCancel, doExportLog, doInstall, doRestart, doRollback, doUpdate, eligibleMarketVersion, enableSidebar, undoSidebar, showSidebarAdded, envFailed, envFixing, envReady, exportState, favoriteTabCount, fixEnv, hasUpdates, headRef, heldMarketVersion, hostBusy, hostDependencyFindings, hotNames, installError, installedOtherCount, lang, marketGone, missingRestoreCount, notificationSnapshot, openInHost, operationsOpen, pendingBackup, pendingRefreshNames, pendingRestart, profileBlocked, records, recordsRef, recovery, refreshInstalled, removingName, replacing, resolveConflict, restartEnabled, restartHold, restartReachable, restarting, restoreErrors, rollingBack, runQueuedNow, setBuildsSkipped, setCat, setOperationsOpen, setQ, setRecords, setRecoveryOpen, setRestartNoticeDismissed, setRestoreConfirmOpen, setSidebarTipDismissed, setTab, shadowSummary, showHostPending, showMarketWait, showSidebarTip, sidebarTipError, sidebarTipSaving, staleName, startupRepair, supervisor, surface, t, tab, themeSnap, uiLocale, updateCheckFailed, updates, updatingName, version, marketOffer, takeMarketOffer, hostCaps } = c;
18700
+ const { activationWarnings, approveAndRetry, askRestore, backupBusy, backupMessage, blockedNames, bootId, brokenPluginNames, brokenPlugins, buildsSkipped, busyUrl, checkingUpdates, checkoutRecovery, compatibilityNotice, compatibilitySummary, configNamespaceIssues, data, debuggerLatch, describePlugin, dismissBrokenError, dismissBrokenPlugin, dismissingBroken, doCancel, doExportLog, doInstall, doRestart, doRollback, doUpdate, eligibleMarketVersion, enableSidebar, undoSidebar, showSidebarAdded, envFailed, envFixing, envReady, exportState, favoriteTabCount, fixEnv, hasUpdates, headRef, heldMarketVersion, hostBusy, hostDependencyFindings, hotNames, installError, installedOtherCount, lang, marketGone, missingRestoreCount, notificationSnapshot, openInHost, operationsOpen, pendingBackup, pendingRefreshNames, pendingRestart, profileBlocked, records, recordsRef, recovery, refreshInstalled, removingName, replacing, resolveConflict, restartEnabled, restartHold, restartReachable, restarting, restoreErrors, rollingBack, runQueuedNow, setBuildsSkipped, setCat, setOperationsOpen, setQ, setRecords, setRecoveryOpen, setRestartNoticeDismissed, setRestoreConfirmOpen, setSidebarTipDismissed, setTab, shadowSummary, showHostPending, showMarketWait, showSidebarTip, sidebarTipError, sidebarTipSaving, staleName, startupRepair, supervisor, surface, t, tab, themeSnap, uiLocale, updateCheckFailed, updates, updatingName, version, marketOffer, takeMarketOffer, hostCaps, restartNames, updatedNames, activations } = c;
18670
18701
  const [reloadingSelf, setReloadingSelf] = (0, react.useState)("idle");
18702
+ const [reloadError, setReloadError] = (0, react.useState)("");
18671
18703
  const staleServer = serverIsBehind(version);
18704
+ /** Swap the new server half in, then reload the page so it matches. */
18705
+ const applyNow = () => {
18706
+ setReloadingSelf("working");
18707
+ requestSelfReload(() => fetch(api("/dsh-market/reload-self"), { method: "POST" }), async () => {
18708
+ const status = await (await fetch(api("/dsh-market/status"))).json();
18709
+ return typeof status.version === "string" ? status.version : null;
18710
+ }).then((result) => {
18711
+ if (result.ok) {
18712
+ location.reload();
18713
+ return;
18714
+ }
18715
+ setReloadError(localizeBilingual(result.error, lang));
18716
+ setReloadingSelf("failed");
18717
+ }, () => {
18718
+ setReloadError("");
18719
+ setReloadingSelf("failed");
18720
+ });
18721
+ };
18722
+ const marketWaiting = [
18723
+ ...restartNames,
18724
+ ...updatedNames,
18725
+ ...Object.keys(activations).filter((name) => activations[name]?.state === "restart")
18726
+ ].some((name) => name === "dshmarket" || name === "dsh-market");
18727
+ const applyInPlace = hostCaps.selfReload && marketWaiting && !staleServer && reloadingSelf !== "failed";
18672
18728
  const [moreOpen, setMoreOpen] = (0, react.useState)(false);
18673
18729
  const [restartClosedAt, setRestartClosedAt] = (0, react.useState)(0);
18674
18730
  const [offerClosed, setOfferClosed] = (0, react.useState)(() => {
@@ -19061,23 +19117,17 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
19061
19117
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
19062
19118
  className: Market_module_css_default.grow,
19063
19119
  children: [
19064
- t("staleBanner").replace("{0}", "1.79.0").replace("{1}", version ?? ""),
19120
+ t("staleBanner").replace("{0}", "1.80.0").replace("{1}", version ?? ""),
19065
19121
  " ",
19066
19122
  hostCaps.selfReload || restartEnabled && restartReachable && debuggerLatch === null ? null : t(hostCaps.desktop ? "staleDesktopHint" : "staleManualHint"),
19067
- reloadingSelf === "failed" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [" ", t(hostCaps.desktop ? "staleDesktopHint" : "staleManualHint")] })
19123
+ reloadingSelf === "failed" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [" ", reloadError !== "" ? reloadError : t(hostCaps.desktop ? "staleDesktopHint" : "staleManualHint")] })
19068
19124
  ]
19069
19125
  }),
19070
19126
  hostCaps.selfReload && reloadingSelf !== "failed" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
19071
19127
  variant: "primary",
19072
19128
  size: "sm",
19073
19129
  disabled: reloadingSelf === "working" || hostBusy || busyUrl !== null || updatingName !== null || removingName !== null,
19074
- onClick: () => {
19075
- setReloadingSelf("working");
19076
- fetch(api("/dsh-market/reload-self"), { method: "POST" }).then((res) => {
19077
- if (res.ok) location.reload();
19078
- else setReloadingSelf("failed");
19079
- }).catch(() => setReloadingSelf("failed"));
19080
- },
19130
+ onClick: applyNow,
19081
19131
  children: reloadingSelf === "working" ? t("restarting") : t("staleReload")
19082
19132
  }) : restartEnabled && restartReachable && debuggerLatch === null && recovery === null && !marketGone && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
19083
19133
  variant: "primary",
@@ -19157,13 +19207,23 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
19157
19207
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconQuestionOutline14, { size: 14 })
19158
19208
  })
19159
19209
  }),
19160
- restartEnabled && restartReachable && debuggerLatch === null && recovery === null && !marketGone && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
19210
+ applyInPlace ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
19211
+ variant: "primary",
19212
+ size: "sm",
19213
+ disabled: reloadingSelf === "working" || hostBusy || busyUrl !== null || updatingName !== null || removingName !== null,
19214
+ onClick: applyNow,
19215
+ children: reloadingSelf === "working" ? t("restarting") : t("staleReload")
19216
+ }) : restartEnabled && restartReachable && debuggerLatch === null && recovery === null && !marketGone && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
19161
19217
  variant: "primary",
19162
19218
  size: "sm",
19163
19219
  disabled: restarting || hostBusy || busyUrl !== null || updatingName !== null || removingName !== null,
19164
19220
  onClick: doRestart,
19165
19221
  children: restarting ? t("restarting") : t("restartNow")
19166
19222
  }),
19223
+ reloadingSelf === "failed" && reloadError !== "" && marketWaiting && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
19224
+ className: Market_module_css_default.grow,
19225
+ children: reloadError
19226
+ }),
19167
19227
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
19168
19228
  type: "button",
19169
19229
  className: Market_module_css_default.bannerClose,
package/lib/hot.js CHANGED
@@ -741,6 +741,24 @@ export function forgetInstalled(profileDir, name) {
741
741
  state.installTimes = trimInstallTimes(map);
742
742
  writeState(profileDir, state, true);
743
743
  }
744
+ /**
745
+ * Forget every hot mount. Called when the market's routes unload.
746
+ *
747
+ * The trees these tables point at hang off the market's own instance, so
748
+ * they go down with it. The tables do not: they are module state, and a
749
+ * module the host did not replace — its file did not change — is still
750
+ * loaded when the next instance starts (src/self-reload.ts). Left as they
751
+ * are, the new instance would believe a plugin is still mounted that its
752
+ * predecessor took down: its shim would never be mounted again, and
753
+ * "switch off" would dispose a handle that is already gone while the plugin,
754
+ * brought back by the host's own composition, kept running.
755
+ */
756
+ export function resetHotState() {
757
+ hotHandles.clear();
758
+ hotTrees.clear();
759
+ hotTreeOf.clear();
760
+ shimNames.clear();
761
+ }
744
762
  /** Package names whose hot-mount trees are still attached and can be removed. */
745
763
  export function listHotMounts() {
746
764
  return [...hotHandles.keys()];
package/lib/routes.js CHANGED
@@ -21,7 +21,7 @@ import { clientPolicy, getPolicy, pinnedVersion } from './policy.js';
21
21
  import { setNpmrcProfileDir } from './npmrc.js';
22
22
  import { BundleError, extractBundle, isInsideOfflineRoot, MAX_BUNDLE_BYTES } from './offline.js';
23
23
  import { settingsNamespaceState } from './settings.js';
24
- import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
24
+ import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, resetHotState, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
25
25
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
26
26
  import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
27
27
  import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion, githubCompatibilityRevision } from './discovery-compatibility.js';
@@ -63,6 +63,7 @@ import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from
63
63
  import { createThemeManager } from './themes.js';
64
64
  import { readJsonBody, readRawBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
65
65
  import { resolveDshHome } from './home-paths.js';
66
+ import { asHmr, claimInstance, reloadSelf, selfReloadReply } from './self-reload.js';
66
67
  import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
67
68
  import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
68
69
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
@@ -140,6 +141,27 @@ function isGitHubReleaseTarballSpec(spec) {
140
141
  * in frame the first reply always has to ask which one it was.
141
142
  */
142
143
  let cachedVersion = null;
144
+ /**
145
+ * Forget the version read from disk. Called when the routes unload: a module
146
+ * the host did not replace (its file did not change) stays loaded across an
147
+ * in-process reload (src/self-reload.ts), and the instance that comes next
148
+ * must report the package.json that is on disk now, not the one it started
149
+ * beside.
150
+ */
151
+ export function forgetMarketVersion() {
152
+ cachedVersion = null;
153
+ }
154
+ /**
155
+ * True only while this market is asking the host to swap in its own new build.
156
+ *
157
+ * The version a market reports must be the version of the CODE that is
158
+ * running. Any other reason this instance unloads (a settings change makes
159
+ * the host restart the entry) leaves the same code running, so the version
160
+ * read at first use stays true even though a newer package.json is on disk —
161
+ * forgetting it there would report the new version over the old code and
162
+ * hide exactly the mismatch the page needs to see.
163
+ */
164
+ let swappingSelf = false;
143
165
  export function marketVersion() {
144
166
  if (cachedVersion !== null)
145
167
  return cachedVersion;
@@ -3234,6 +3256,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3234
3256
  kind: () => (config.desktopHost === true ? 'desktop' : 'web'),
3235
3257
  region: () => region,
3236
3258
  };
3259
+ /**
3260
+ * In-process reload of the market itself (see src/self-reload.ts).
3261
+ *
3262
+ * Available when the host can replace modules (its HMR service, DSH 0.2.1
3263
+ * and later) and the market is an installed package of this profile — a
3264
+ * development checkout has no newer files on disk to switch to.
3265
+ */
3266
+ const selfPackageName = () => ['dshmarket', 'dsh-market'].find(candidate => readInstalled(config.profile, activeProfileDir)[candidate] !== undefined) ?? null;
3267
+ const hostHmr = () => asHmr(host.get?.('hmr'));
3268
+ const selfReloadAvailable = () => hostHmr() !== undefined && host.get?.('profileContext') !== undefined && selfPackageName() !== null;
3269
+ // Announced once the routes below are up; handlers read it lazily.
3270
+ let instanceClaim;
3237
3271
  const disposers = [
3238
3272
  // The market page was opened. The page says so once per load; the count
3239
3273
  // keeps the first one of each UTC day and ignores the rest. Answered at
@@ -5715,6 +5749,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5715
5749
  // card hides a remove button that could only ever answer 403.
5716
5750
  selfUninstallReachable: selfUninstallReachableFrom(request),
5717
5751
  selfManaged: installed.dshmarket !== undefined || installed['dsh-market'] !== undefined,
5752
+ // Whether POST /dsh-market/reload-self can swap a newer build of the
5753
+ // market in without restarting DSH. The page that has just loaded a
5754
+ // newer client than this server reads it to choose between "reload
5755
+ // the market" and "restart DSH".
5756
+ selfReload: selfReloadAvailable(),
5718
5757
  // Whether the host took the market's settings namespace (#677).
5719
5758
  // `unsupported-by-host` is 0.1.7 and newer, where settings come from
5720
5759
  // a plugin's Config schema and no third-party namespace is served —
@@ -8184,6 +8223,56 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8184
8223
  }
8185
8224
  },
8186
8225
  }),
8226
+ registerRoute({
8227
+ kind: 'exact',
8228
+ path: '/dsh-market/reload-self',
8229
+ handler: async (request, response) => {
8230
+ if (request.method !== 'POST') {
8231
+ response.writeHead(405, { allow: 'POST' });
8232
+ response.end();
8233
+ return;
8234
+ }
8235
+ if (!sameOrigin(request)) {
8236
+ sendJson(response, 403, { error: 'untrusted origin' });
8237
+ return;
8238
+ }
8239
+ if (restarting) {
8240
+ sendJson(response, 409, { busy: true, error: 'restart already scheduled' });
8241
+ return;
8242
+ }
8243
+ try {
8244
+ // Under the same lock as every other change: a swap ends the instance
8245
+ // that would have finished a running install, so none may be running,
8246
+ // and none may start while it happens. A second request answers 409.
8247
+ const outcome = await withMutationLock(response, 'write', async () => {
8248
+ const name = selfPackageName();
8249
+ swappingSelf = true;
8250
+ try {
8251
+ return await reloadSelf({
8252
+ hmr: hostHmr,
8253
+ runningVersion: marketVersion(),
8254
+ installedVersion: () => name === null ? null : readInstalledVersion(config.profile, name, activeProfileDir),
8255
+ packageDir: () => join(activeProfileDir, 'node_modules', name ?? 'dshmarket'),
8256
+ instanceId: instanceClaim?.id ?? '',
8257
+ log: (level, detail) => logEvent(level, 'reload', detail),
8258
+ });
8259
+ }
8260
+ finally {
8261
+ swappingSelf = false;
8262
+ }
8263
+ });
8264
+ if (outcome === null)
8265
+ return;
8266
+ const reply = selfReloadReply(outcome);
8267
+ sendJson(response, reply.status, reply.body);
8268
+ }
8269
+ catch (error) {
8270
+ const message = error instanceof Error ? error.message : String(error);
8271
+ logEvent('error', 'reload', `route error: ${message}`);
8272
+ sendJson(response, 500, { ok: false, error: message });
8273
+ }
8274
+ },
8275
+ }),
8187
8276
  registerRoute(captureLegacy('/dsh-market/restart', {
8188
8277
  kind: 'exact',
8189
8278
  path: '/dsh-market/restart',
@@ -9535,8 +9624,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
9535
9624
  ];
9536
9625
  startCheckoutRepair();
9537
9626
  const stopHeartbeat = startHeartbeat(telemetryOptions);
9627
+ instanceClaim = claimInstance(marketVersion());
9538
9628
  return async () => {
9539
9629
  disposed = true;
9630
+ instanceClaim?.release();
9631
+ if (swappingSelf)
9632
+ forgetMarketVersion();
9633
+ resetHotState();
9540
9634
  stopHeartbeat();
9541
9635
  checkoutRepairRound = undefined;
9542
9636
  if (checkoutRepairTimer !== undefined)
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Reload the market's OWN server half inside the running DSH process.
3
+ *
4
+ * Why this exists: the market updates itself by replacing its files, and the
5
+ * Node module it already imported keeps running. The browser, meanwhile, loads
6
+ * the NEW client bundle, which calls routes the old process does not have (the
7
+ * host answers 405 with an empty body). The only cure used to be a restart,
8
+ * and on DSH Desktop even that is not ours to do (`allowRestart: false`).
9
+ *
10
+ * How: not by re-importing ourselves — Node never re-evaluates a module at a
11
+ * URL it has already loaded, and a cache-busted URL only renews the entry
12
+ * file while every sibling it imports stays the old one. The host already
13
+ * solves exactly this for every plugin: `hmr.reconcileProfile()` (the service
14
+ * `@deepseek-ai/dsh-hmr` publishes as `ctx.hmr`, present from DSH 0.2.1)
15
+ * compares the files of every loaded module with the disk, evicts the ones
16
+ * that changed together with their importers, stops the loader entries that
17
+ * ran them and starts those entries again from the new files. The market is a
18
+ * loader entry like any other, so it is replaced the same way. This module is
19
+ * the orchestration around that one call.
20
+ *
21
+ * The part that is ours, and the reason this is more than one call:
22
+ *
23
+ * - The request that asks for the swap is served by the instance about to be
24
+ * replaced. Its closure outlives its own disposal (the HTTP response object
25
+ * belongs to the web server, not to the plugin), so the SAME request can
26
+ * still report how the swap went.
27
+ * - The host does not restore the old code when the new code cannot start: it
28
+ * evicts the old modules without a backup. So the new build is imported
29
+ * first, from a private copy at a path Node has never seen, and the swap is
30
+ * only asked for when that worked. A build that cannot even load never
31
+ * replaces a market that is running fine.
32
+ * - Which instance is serving is a fact held outside every module — on
33
+ * `globalThis` under a registered symbol — because the module that would
34
+ * hold it is exactly what gets replaced.
35
+ */
36
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
37
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
38
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
39
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
40
+ });
41
+ }
42
+ return path;
43
+ };
44
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from 'node:fs';
45
+ import { basename, dirname, join } from 'node:path';
46
+ import { pathToFileURL } from 'node:url';
47
+ /**
48
+ * The host's HMR service when it can replace modules, otherwise undefined.
49
+ * Checked by shape: DSH 0.2.0 and earlier publish an `hmr` service without
50
+ * `reconcileProfile`, and a call into it would fail after we had decided to
51
+ * go ahead.
52
+ */
53
+ export function asHmr(value) {
54
+ if (value === null || typeof value !== 'object')
55
+ return undefined;
56
+ const candidate = value;
57
+ return typeof candidate.runExclusive === 'function' && typeof candidate.reconcileProfile === 'function'
58
+ ? value
59
+ : undefined;
60
+ }
61
+ // ── Which instance is serving ─────────────────────────────────────────────
62
+ const INSTANCE_KEY = Symbol.for('dsh-market.serving-instance');
63
+ let instanceSequence = 0;
64
+ /**
65
+ * Announce this instance as the one serving. Returns the id to compare
66
+ * against, and a release that only clears the record when it is still this
67
+ * instance's own — a late release from a replaced instance must not erase the
68
+ * record its replacement has already written.
69
+ */
70
+ export function claimInstance(version) {
71
+ instanceSequence += 1;
72
+ const id = `${String(process.pid)}-${String(Date.now())}-${String(instanceSequence)}-${Math.random().toString(16).slice(2, 8)}`;
73
+ const holder = globalThis;
74
+ holder[INSTANCE_KEY] = { id, version };
75
+ return {
76
+ id,
77
+ release: () => {
78
+ if (holder[INSTANCE_KEY]?.id === id)
79
+ delete holder[INSTANCE_KEY];
80
+ },
81
+ };
82
+ }
83
+ /** The instance serving right now, or undefined while none is. */
84
+ export function currentInstance() {
85
+ return globalThis[INSTANCE_KEY];
86
+ }
87
+ let preflightSequence = 0;
88
+ /**
89
+ * Whether the package now on disk can be loaded at all.
90
+ *
91
+ * Imports a private copy of its `lib/` from a path nobody has imported, so
92
+ * the whole module graph is evaluated fresh and any failure — a syntax error,
93
+ * a dependency that is missing, a top-level throw — surfaces here, while the
94
+ * running market is still untouched. The copy sits NEXT TO the package so
95
+ * bare imports resolve through the same `node_modules` chain as the real one,
96
+ * and is deleted again afterwards; the host forgets files that disappeared.
97
+ *
98
+ * What it cannot see: a build that loads fine and then fails inside `apply`.
99
+ * That is only learnable by running it.
100
+ *
101
+ * `checked: false` means the check could not be run (the directory is not
102
+ * writable); the caller proceeds, because refusing every reload on a
103
+ * read-only profile would make the feature useless there.
104
+ */
105
+ export async function preflightBuild(packageDir) {
106
+ let real;
107
+ let main;
108
+ try {
109
+ real = realpathSync(packageDir);
110
+ const manifest = JSON.parse(readFileSync(join(real, 'package.json'), 'utf8'));
111
+ main = typeof manifest.main === 'string' ? manifest.main : 'index.js';
112
+ }
113
+ catch (error) {
114
+ return { ok: false, detail: `the installed package cannot be read — ${messageOf(error)}` };
115
+ }
116
+ if (!existsSync(join(real, main)))
117
+ return { ok: false, detail: `the entry file ${main} is missing` };
118
+ preflightSequence += 1;
119
+ const copy = join(dirname(real), `.dsh-market-reload-${String(process.pid)}-${String(preflightSequence)}`);
120
+ try {
121
+ mkdirSync(copy, { recursive: true });
122
+ cpSync(join(real, 'package.json'), join(copy, 'package.json'));
123
+ cpSync(join(real, dirname(main)), join(copy, dirname(main)), {
124
+ recursive: true,
125
+ // Declarations are not loaded and a second copy of them is dead weight.
126
+ filter: source => {
127
+ const base = basename(source);
128
+ return base !== 'types' && base !== 'node_modules' && !base.endsWith('.d.ts');
129
+ },
130
+ });
131
+ }
132
+ catch {
133
+ rmSync(copy, { recursive: true, force: true });
134
+ return { ok: true, checked: false };
135
+ }
136
+ try {
137
+ const loaded = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ pathToFileURL(join(copy, main)).href));
138
+ if (typeof loaded.apply !== 'function')
139
+ return { ok: false, detail: 'the new build does not export a plugin entry (apply)' };
140
+ return { ok: true, checked: true };
141
+ }
142
+ catch (error) {
143
+ return { ok: false, detail: messageOf(error) };
144
+ }
145
+ finally {
146
+ rmSync(copy, { recursive: true, force: true });
147
+ }
148
+ }
149
+ function messageOf(error) {
150
+ const text = error instanceof Error ? error.message : String(error);
151
+ // The copy's own path means nothing to the reader; the file name does.
152
+ return text.replace(/\.dsh-market-reload-\d+-\d+/g, 'the new build').slice(0, 400);
153
+ }
154
+ const DEFAULT_QUEUE_WAIT_MS = 60_000;
155
+ const DEFAULT_SETTLE_MS = 5_000;
156
+ const sleep = (ms) => new Promise(resolve => { setTimeout(resolve, ms); });
157
+ /**
158
+ * Ask the host to replace this market with the version on disk.
159
+ *
160
+ * The caller has already refused when an operation is running: a swap ends
161
+ * the instance that would have finished it. Nothing here writes a file.
162
+ */
163
+ export async function reloadSelf(deps) {
164
+ const log = deps.log ?? (() => { });
165
+ const serving = deps.serving ?? currentInstance;
166
+ const hmr = deps.hmr();
167
+ if (hmr === undefined)
168
+ return { state: 'unsupported', reason: 'no-hmr' };
169
+ const target = deps.installedVersion();
170
+ if (target === null)
171
+ return { state: 'unsupported', reason: 'not-installed' };
172
+ if (target === deps.runningVersion)
173
+ return { state: 'current', version: target };
174
+ const verdict = await (deps.preflight ?? preflightBuild)(deps.packageDir());
175
+ if (!verdict.ok) {
176
+ log('warn', `reload to ${target} refused, the new build does not load: ${verdict.detail}`);
177
+ return { state: 'refused', detail: verdict.detail };
178
+ }
179
+ if (!verdict.checked)
180
+ log('warn', `reload to ${target}: the new build could not be test-loaded first`);
181
+ log('info', `reloading ${deps.runningVersion} -> ${target}`);
182
+ const queueWaitMs = deps.queueWaitMs ?? DEFAULT_QUEUE_WAIT_MS;
183
+ const swap = hmr.runExclusive(() => hmr.reconcileProfile());
184
+ // The swap itself is never abandoned: it was asked for, and running it a
185
+ // little late is what the user wants. Only the WAITING for it has a limit.
186
+ let timer;
187
+ const waited = await Promise.race([
188
+ swap.then(report => ({ report }), (error) => ({ error })),
189
+ new Promise(resolve => { timer = setTimeout(() => { resolve('queued'); }, queueWaitMs); }),
190
+ ]).finally(() => { clearTimeout(timer); });
191
+ if (waited === 'queued') {
192
+ void swap.catch((error) => { log('warn', `queued reload failed: ${messageOf(error)}`); });
193
+ return { state: 'queued' };
194
+ }
195
+ if ('error' in waited) {
196
+ const detail = messageOf(waited.error);
197
+ const stillOurs = serving()?.id === deps.instanceId;
198
+ log('warn', `reload to ${target} failed${stillOurs ? ' (the running market was not touched)' : ''}: ${detail}`);
199
+ return stillOurs
200
+ ? { state: 'restart-needed', detail }
201
+ : { state: 'failed', detail, serving: serving() !== undefined };
202
+ }
203
+ // The host says it is done. Believe the instance record, not the report: the
204
+ // new instance announces itself when its routes are up, which is the fact
205
+ // that matters.
206
+ const deadline = Date.now() + (deps.settleMs ?? DEFAULT_SETTLE_MS);
207
+ for (;;) {
208
+ const now = serving();
209
+ if (now !== undefined && now.id !== deps.instanceId) {
210
+ log('info', `reloaded to ${now.version}`);
211
+ return { state: 'reloaded', from: deps.runningVersion, to: now.version };
212
+ }
213
+ if (Date.now() >= deadline)
214
+ break;
215
+ await sleep(100);
216
+ }
217
+ const now = serving();
218
+ if (now?.id === deps.instanceId) {
219
+ // Nothing was replaced: the host could not compare or evict the modules
220
+ // (a loader without access to Node's module cache, a host-owned module).
221
+ const why = waited.report.restartReason !== undefined
222
+ ? `the host could not replace modules (${waited.report.restartReason})`
223
+ : waited.report.pending.length > 0
224
+ ? `the host keeps ${String(waited.report.pending.length)} changed module(s) until a restart (${waited.report.pending[0].reason})`
225
+ : 'the host reported done but the old code is still running';
226
+ log('warn', `reload to ${target}: ${why}`);
227
+ return { state: 'restart-needed', detail: why };
228
+ }
229
+ const detail = 'the new version did not start serving';
230
+ log('warn', `reload to ${target}: ${detail}`);
231
+ return { state: 'failed', detail, serving: false };
232
+ }
233
+ /**
234
+ * The HTTP answer for an outcome. Every failure says what happened, why and
235
+ * what to do now, in the project's two-language style; the state code is for
236
+ * the page, which decides what to offer next.
237
+ */
238
+ export function selfReloadReply(outcome) {
239
+ switch (outcome.state) {
240
+ case 'reloaded':
241
+ return { status: 200, body: { ok: true, outcome: 'reloaded', from: outcome.from, to: outcome.to } };
242
+ case 'current':
243
+ return { status: 200, body: { ok: true, outcome: 'current', version: outcome.version } };
244
+ case 'queued':
245
+ return {
246
+ status: 202,
247
+ body: {
248
+ ok: true,
249
+ outcome: 'queued',
250
+ message: 'DSH 正在处理另一项变更,市场会在它结束后自动换成新版。 / DSH is busy with another change. The market will switch to the new version when it finishes.',
251
+ },
252
+ };
253
+ case 'unsupported':
254
+ return {
255
+ status: 501,
256
+ body: {
257
+ ok: false,
258
+ outcome: 'unsupported',
259
+ error: outcome.reason === 'no-hmr'
260
+ ? '这个 DSH 版本不能原地换上新版市场。重启 DSH 就会用上新版。 / This DSH version cannot switch to the new market in place. Restart DSH to use it.'
261
+ : '市场不是作为插件装在这里的,没有新版文件可换。要用磁盘上的文件,请重启 DSH。 / The market is not installed as a plugin here, so there is no new version to switch to. Restart DSH to run what is on disk.',
262
+ },
263
+ };
264
+ case 'refused':
265
+ return {
266
+ status: 422,
267
+ body: {
268
+ ok: false,
269
+ outcome: 'refused',
270
+ detail: outcome.detail,
271
+ error: '新版本没能加载,已保留正在运行的版本,它照常可用。请再更新一次;重启 DSH 能看到具体原因。 / The new version could not load, so the running one was kept and still works. Update again, or restart DSH to see why.',
272
+ },
273
+ };
274
+ case 'restart-needed':
275
+ return {
276
+ status: 502,
277
+ body: {
278
+ ok: false,
279
+ outcome: 'restart-needed',
280
+ detail: outcome.detail,
281
+ error: 'DSH 这次没能换上新版,当前仍是旧版,功能照常。重启 DSH 就会用上新版。 / DSH could not switch to the new version this time. The old one keeps working. Restart DSH to use the new one.',
282
+ },
283
+ };
284
+ case 'failed':
285
+ return {
286
+ status: 502,
287
+ body: {
288
+ ok: false,
289
+ outcome: 'failed',
290
+ serving: outcome.serving,
291
+ detail: outcome.detail,
292
+ error: '切换到新版时出了问题,市场暂时不可用。重启 DSH 即可恢复。 / Switching to the new version went wrong and the market is unavailable. Restart DSH to recover.',
293
+ },
294
+ };
295
+ }
296
+ }
@@ -429,6 +429,19 @@ export declare function recordInstalled(profileDir: string, names: readonly stri
429
429
  export declare function recordUpdated(profileDir: string, names: readonly string[], at?: Date): void;
430
430
  /** The package is gone: its stamps must not outlive it. */
431
431
  export declare function forgetInstalled(profileDir: string, name: string): void;
432
+ /**
433
+ * Forget every hot mount. Called when the market's routes unload.
434
+ *
435
+ * The trees these tables point at hang off the market's own instance, so
436
+ * they go down with it. The tables do not: they are module state, and a
437
+ * module the host did not replace — its file did not change — is still
438
+ * loaded when the next instance starts (src/self-reload.ts). Left as they
439
+ * are, the new instance would believe a plugin is still mounted that its
440
+ * predecessor took down: its shim would never be mounted again, and
441
+ * "switch off" would dispose a handle that is already gone while the plugin,
442
+ * brought back by the host's own composition, kept running.
443
+ */
444
+ export declare function resetHotState(): void;
432
445
  /** Package names whose hot-mount trees are still attached and can be removed. */
433
446
  export declare function listHotMounts(): string[];
434
447
  /** Report a failed child only when it belongs to this package's hot-mount tree. */
@@ -33,6 +33,8 @@ export interface MarketHost {
33
33
  dispose(): Promise<unknown> | void;
34
34
  };
35
35
  on?(event: string, callback: (payload: unknown) => void): () => void;
36
+ /** Service lookup; the host context has it, test doubles may not. */
37
+ get?(name: string): unknown;
36
38
  logger?: {
37
39
  info?(message: string): void;
38
40
  warn(message: string): void;
@@ -123,6 +125,14 @@ export interface MarketConfig {
123
125
  launcherNow: () => string;
124
126
  };
125
127
  }
128
+ /**
129
+ * Forget the version read from disk. Called when the routes unload: a module
130
+ * the host did not replace (its file did not change) stays loaded across an
131
+ * in-process reload (src/self-reload.ts), and the instance that comes next
132
+ * must report the package.json that is on disk now, not the one it started
133
+ * beside.
134
+ */
135
+ export declare function forgetMarketVersion(): void;
126
136
  export declare function marketVersion(): string;
127
137
  /**
128
138
  * Register the market's HTTP routes.
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Reload the market's OWN server half inside the running DSH process.
3
+ *
4
+ * Why this exists: the market updates itself by replacing its files, and the
5
+ * Node module it already imported keeps running. The browser, meanwhile, loads
6
+ * the NEW client bundle, which calls routes the old process does not have (the
7
+ * host answers 405 with an empty body). The only cure used to be a restart,
8
+ * and on DSH Desktop even that is not ours to do (`allowRestart: false`).
9
+ *
10
+ * How: not by re-importing ourselves — Node never re-evaluates a module at a
11
+ * URL it has already loaded, and a cache-busted URL only renews the entry
12
+ * file while every sibling it imports stays the old one. The host already
13
+ * solves exactly this for every plugin: `hmr.reconcileProfile()` (the service
14
+ * `@deepseek-ai/dsh-hmr` publishes as `ctx.hmr`, present from DSH 0.2.1)
15
+ * compares the files of every loaded module with the disk, evicts the ones
16
+ * that changed together with their importers, stops the loader entries that
17
+ * ran them and starts those entries again from the new files. The market is a
18
+ * loader entry like any other, so it is replaced the same way. This module is
19
+ * the orchestration around that one call.
20
+ *
21
+ * The part that is ours, and the reason this is more than one call:
22
+ *
23
+ * - The request that asks for the swap is served by the instance about to be
24
+ * replaced. Its closure outlives its own disposal (the HTTP response object
25
+ * belongs to the web server, not to the plugin), so the SAME request can
26
+ * still report how the swap went.
27
+ * - The host does not restore the old code when the new code cannot start: it
28
+ * evicts the old modules without a backup. So the new build is imported
29
+ * first, from a private copy at a path Node has never seen, and the swap is
30
+ * only asked for when that worked. A build that cannot even load never
31
+ * replaces a market that is running fine.
32
+ * - Which instance is serving is a fact held outside every module — on
33
+ * `globalThis` under a registered symbol — because the module that would
34
+ * hold it is exactly what gets replaced.
35
+ */
36
+ /** The slice of the host's `hmr` service this relies on. */
37
+ export interface HmrLike {
38
+ runExclusive<T>(operation: () => Promise<T>): Promise<T>;
39
+ reconcileProfile(requiredIds?: readonly string[]): Promise<{
40
+ warnings: readonly string[];
41
+ /** Changed modules that keep running their old code until a restart. */
42
+ pending: readonly {
43
+ url: string;
44
+ reason: string;
45
+ }[];
46
+ /** Why every change waits for a restart, when the host could not compare modules at all. */
47
+ restartReason?: string;
48
+ }>;
49
+ }
50
+ /**
51
+ * The host's HMR service when it can replace modules, otherwise undefined.
52
+ * Checked by shape: DSH 0.2.0 and earlier publish an `hmr` service without
53
+ * `reconcileProfile`, and a call into it would fail after we had decided to
54
+ * go ahead.
55
+ */
56
+ export declare function asHmr(value: unknown): HmrLike | undefined;
57
+ /** The instance that registered its routes last. */
58
+ export interface InstanceRecord {
59
+ id: string;
60
+ version: string;
61
+ }
62
+ /**
63
+ * Announce this instance as the one serving. Returns the id to compare
64
+ * against, and a release that only clears the record when it is still this
65
+ * instance's own — a late release from a replaced instance must not erase the
66
+ * record its replacement has already written.
67
+ */
68
+ export declare function claimInstance(version: string): {
69
+ id: string;
70
+ release(): void;
71
+ };
72
+ /** The instance serving right now, or undefined while none is. */
73
+ export declare function currentInstance(): InstanceRecord | undefined;
74
+ /** Verdict of {@link preflightBuild}. */
75
+ export type Preflight = {
76
+ ok: true;
77
+ checked: boolean;
78
+ } | {
79
+ ok: false;
80
+ detail: string;
81
+ };
82
+ /**
83
+ * Whether the package now on disk can be loaded at all.
84
+ *
85
+ * Imports a private copy of its `lib/` from a path nobody has imported, so
86
+ * the whole module graph is evaluated fresh and any failure — a syntax error,
87
+ * a dependency that is missing, a top-level throw — surfaces here, while the
88
+ * running market is still untouched. The copy sits NEXT TO the package so
89
+ * bare imports resolve through the same `node_modules` chain as the real one,
90
+ * and is deleted again afterwards; the host forgets files that disappeared.
91
+ *
92
+ * What it cannot see: a build that loads fine and then fails inside `apply`.
93
+ * That is only learnable by running it.
94
+ *
95
+ * `checked: false` means the check could not be run (the directory is not
96
+ * writable); the caller proceeds, because refusing every reload on a
97
+ * read-only profile would make the feature useless there.
98
+ */
99
+ export declare function preflightBuild(packageDir: string): Promise<Preflight>;
100
+ /** What a reload attempt came to. */
101
+ export type SelfReloadOutcome =
102
+ /** The host cannot replace modules (or the market is not an installed package here). */
103
+ {
104
+ state: 'unsupported';
105
+ reason: 'no-hmr' | 'not-installed';
106
+ }
107
+ /** The files on disk are the version already running: nothing to do. */
108
+ | {
109
+ state: 'current';
110
+ version: string;
111
+ }
112
+ /** The new build cannot load. The running market was not touched. */
113
+ | {
114
+ state: 'refused';
115
+ detail: string;
116
+ }
117
+ /** The new server half is serving. */
118
+ | {
119
+ state: 'reloaded';
120
+ from: string;
121
+ to: string;
122
+ }
123
+ /** The host could not replace the module; the running market is untouched. */
124
+ | {
125
+ state: 'restart-needed';
126
+ detail: string;
127
+ }
128
+ /** Another host operation holds the reload queue; the swap will run when it ends. */
129
+ | {
130
+ state: 'queued';
131
+ }
132
+ /** The swap started and went wrong. `serving` says whether any instance is up. */
133
+ | {
134
+ state: 'failed';
135
+ detail: string;
136
+ serving: boolean;
137
+ };
138
+ export interface SelfReloadDeps {
139
+ /** The host's HMR service, read at call time. */
140
+ hmr: () => HmrLike | undefined;
141
+ /** The version this process is running. */
142
+ runningVersion: string;
143
+ /** The version of the files on disk, or null when the market is not an installed package. */
144
+ installedVersion: () => string | null;
145
+ /** Where the installed package lives. */
146
+ packageDir: () => string;
147
+ /** This instance's id, from {@link claimInstance}. */
148
+ instanceId: string;
149
+ /** The instance serving now; injectable for the specs. */
150
+ serving?: () => InstanceRecord | undefined;
151
+ /** Defaults to {@link preflightBuild}. */
152
+ preflight?: (packageDir: string) => Promise<Preflight>;
153
+ /** How long to wait for the host's reload queue before reporting `queued`. */
154
+ queueWaitMs?: number;
155
+ /** How long to wait for the new instance to announce itself once the host reports done. */
156
+ settleMs?: number;
157
+ log?: (level: 'info' | 'warn', detail: string) => void;
158
+ }
159
+ /**
160
+ * Ask the host to replace this market with the version on disk.
161
+ *
162
+ * The caller has already refused when an operation is running: a swap ends
163
+ * the instance that would have finished it. Nothing here writes a file.
164
+ */
165
+ export declare function reloadSelf(deps: SelfReloadDeps): Promise<SelfReloadOutcome>;
166
+ /**
167
+ * The HTTP answer for an outcome. Every failure says what happened, why and
168
+ * what to do now, in the project's two-language style; the state code is for
169
+ * the page, which decides what to offer next.
170
+ */
171
+ export declare function selfReloadReply(outcome: SelfReloadOutcome): {
172
+ status: number;
173
+ body: Record<string, unknown>;
174
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dshmarket",
3
3
  "description": "Visual plugin market inside DeepSeek Harness — browse, search, and one-click install community plugins. · DSH 可视化插件市场:逛一逛,点一下,装好。",
4
- "version": "1.79.0",
4
+ "version": "1.80.0",
5
5
  "icon": "assets/logo.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",