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
@@ -70,8 +70,9 @@ export const MAX_BODY_BYTES = 256 * 1024 * 1024;
70
70
  * @param res - the response whose body to read.
71
71
  * @param stallMs - silence that ends the read, in milliseconds.
72
72
  * @param what - the download, for the rejection message ("the catalog").
73
+ * @param maxBytes - maximum decoded response size.
73
74
  */
74
- export function readBodyWhileProgressing(res, stallMs, what = 'the catalog') {
75
+ export function readBodyWhileProgressing(res, stallMs, what = 'the catalog', maxBytes = MAX_BODY_BYTES) {
75
76
  // The stand-in closes at once, so an absent body reads as "no body"
76
77
  // below instead of parking this reader on a stream that never ends.
77
78
  const reader = (res.body ?? new ReadableStream({ start(controller) { controller.close(); } })).getReader();
@@ -118,8 +119,8 @@ export function readBodyWhileProgressing(res, stallMs, what = 'the catalog') {
118
119
  }
119
120
  chunks.push(r.value);
120
121
  received += r.value.byteLength;
121
- if (received > MAX_BODY_BYTES) {
122
- finish(new Error(`${what} response grew past ${String(MAX_BODY_BYTES / 1024 / 1024)} MB without ending (received ${String(received)} bytes)`));
122
+ if (received > maxBytes) {
123
+ finish(new Error(`${what} response grew past ${String(maxBytes / 1024 / 1024)} MB without ending (received ${String(received)} bytes)`));
123
124
  return;
124
125
  }
125
126
  arm();
package/lib/changelog.js CHANGED
@@ -344,7 +344,9 @@ function catalogEntryForGitSource(plugins, spec) {
344
344
  * same contract the issue promised — a dialog that cannot load its data shows
345
345
  * a neutral statement, not an error.
346
346
  */
347
- export async function updateNotesFor(profile, explicitDir, name) {
347
+ export async function updateNotesFor(profile, explicitDir, name,
348
+ /** The version the Update button installs, when it is not simply "latest". */
349
+ target) {
348
350
  const activeProfileDir = profileDir(profile, explicitDir);
349
351
  const spec = readInstalled(profile, activeProfileDir)[name];
350
352
  if (spec === undefined || spec.startsWith('link:') || spec.startsWith('file:')) {
@@ -438,7 +440,18 @@ export async function updateNotesFor(profile, explicitDir, name) {
438
440
  && (compareVersions(released, installed) ?? 0) <= 0;
439
441
  const hasCommits = (entry.commits?.length ?? 0) > 0;
440
442
  if (!(behind && (hasCommits || (specKey === null && npmName !== null)))) {
441
- return { kind: 'release', release: entry.release };
443
+ const beyond = target !== undefined && released !== null
444
+ && (compareVersions(released, target) ?? 0) > 0;
445
+ // Attach the commit slice so the dialog can list what changed between
446
+ // the installed commit and the update target, not just the release (#1193).
447
+ // Only when the installed commit is found in the list: otherwise the
448
+ // slice is just "recent commits" unrelated to this update, and next to
449
+ // release notes it would be noise (npm installs never match a sha).
450
+ const sliced = hasCommits ? sliceCommitsAt(entry.commits, current) : undefined;
451
+ const withCommits = sliced !== undefined && sliced.found && sliced.items.length > 0 ? { commits: sliced } : {};
452
+ return beyond
453
+ ? { kind: 'release', release: entry.release, beyondTarget: target, ...withCommits }
454
+ : { kind: 'release', release: entry.release, ...withCommits };
442
455
  }
443
456
  }
444
457
  if (entry?.commits !== undefined && entry.commits.length > 0) {
@@ -0,0 +1,210 @@
1
+ import fs from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ const V1_SCHEMA = 'dsh-crate/discovery-compatibility-cache/v1';
4
+ const JOURNAL_HEADER = JSON.stringify({ schema: 'dsh-crate/discovery-compatibility-cache/v2' });
5
+ // A full scan of the catalog must stay cached (#1170).
6
+ const MAX_ENTRIES = 20_000;
7
+ const COMPACT_AFTER = 2 * MAX_ENTRIES;
8
+ const BATCH_DELAY_MS = 100;
9
+ const MIN_RETRY_MS = 1_000;
10
+ const MAX_RETRY_MS = 30_000;
11
+ function parseJson(text) {
12
+ try {
13
+ return JSON.parse(text);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ async function readIfPresent(path) {
20
+ try {
21
+ return await fs.readFile(path, 'utf8');
22
+ }
23
+ catch (error) {
24
+ if (error.code === 'ENOENT')
25
+ return null;
26
+ throw error;
27
+ }
28
+ }
29
+ function encodeRows(entries) {
30
+ return [...entries].map(([key, entry]) => JSON.stringify([key, entry]) + '\n').join('');
31
+ }
32
+ /**
33
+ * A single writer and shared view per cache path. The old JSON remains readable
34
+ * until a complete journal has been published. Later writes append only the
35
+ * changed rows, with occasional atomic snapshots to bound the log.
36
+ */
37
+ class DiscoveryCache {
38
+ file;
39
+ decode;
40
+ journal;
41
+ entries = new Map();
42
+ pending = new Map();
43
+ loaded;
44
+ timer;
45
+ writing;
46
+ journalRows = 0;
47
+ canAppend = false;
48
+ retryMs = 0;
49
+ owners = 0;
50
+ constructor(file, decode) {
51
+ this.file = file;
52
+ this.decode = decode;
53
+ this.journal = file + '.journal';
54
+ }
55
+ acquire() {
56
+ this.owners += 1;
57
+ this.schedule();
58
+ }
59
+ async release() {
60
+ this.owners -= 1;
61
+ if (this.owners !== 0)
62
+ return;
63
+ if (this.timer !== undefined)
64
+ clearTimeout(this.timer);
65
+ this.timer = undefined;
66
+ // Give a normal unload one immediate drain. A mounted replacement keeps
67
+ // sharing the same writer even if it arrives before that drain completes.
68
+ while (this.pending.size > 0 && await this.flushOnce()) {
69
+ if (this.owners !== 0)
70
+ break;
71
+ }
72
+ this.schedule();
73
+ }
74
+ async restore() {
75
+ const journal = await readIfPresent(this.journal);
76
+ const saved = new Map();
77
+ const add = (key, raw) => {
78
+ const entry = this.decode(raw);
79
+ if (entry === null || (saved.get(key)?.checkedAt ?? -Infinity) > entry.checkedAt)
80
+ return;
81
+ saved.set(key, entry);
82
+ };
83
+ if (journal === null) {
84
+ const legacy = await readIfPresent(this.file);
85
+ const data = legacy === null ? null : parseJson(legacy);
86
+ if (data?.schema === V1_SCHEMA && data.entries !== null && typeof data.entries === 'object' && !Array.isArray(data.entries)) {
87
+ for (const [key, value] of Object.entries(data.entries))
88
+ add(key, value);
89
+ }
90
+ }
91
+ else {
92
+ const [header, ...rows] = journal.split('\n');
93
+ if (header === JOURNAL_HEADER) {
94
+ this.canAppend = true;
95
+ this.journalRows = rows.length - 1;
96
+ for (const row of rows) {
97
+ if (row === '')
98
+ continue;
99
+ const value = parseJson(row);
100
+ if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string')
101
+ add(value[0], value[1]);
102
+ }
103
+ }
104
+ }
105
+ // A prior read error may have left locally refreshed entries in memory.
106
+ // Replay must not replace them with old copies, including timestamp ties.
107
+ for (const [key, entry] of saved) {
108
+ if ((this.entries.get(key)?.checkedAt ?? -Infinity) < entry.checkedAt)
109
+ this.entries.set(key, entry);
110
+ }
111
+ this.trim();
112
+ }
113
+ ready() {
114
+ return this.loaded ??= this.restore();
115
+ }
116
+ async get(key) {
117
+ await this.ready().catch(() => { });
118
+ return this.entries.get(key);
119
+ }
120
+ set(key, entry) {
121
+ if ((this.entries.get(key)?.checkedAt ?? -Infinity) > entry.checkedAt)
122
+ return;
123
+ this.entries.set(key, entry);
124
+ this.pending.set(key, entry);
125
+ this.schedule();
126
+ }
127
+ trim() {
128
+ if (this.entries.size <= MAX_ENTRIES)
129
+ return;
130
+ const newest = [...this.entries].sort(([, a], [, b]) => b.checkedAt - a.checkedAt);
131
+ for (const [key] of newest.slice(MAX_ENTRIES)) {
132
+ this.entries.delete(key);
133
+ this.pending.delete(key);
134
+ }
135
+ }
136
+ schedule() {
137
+ if (this.timer !== undefined || this.writing !== undefined)
138
+ return;
139
+ if (this.pending.size === 0) {
140
+ if (this.owners === 0 && caches.get(this.file) === this)
141
+ caches.delete(this.file);
142
+ return;
143
+ }
144
+ this.timer = setTimeout(() => {
145
+ this.timer = undefined;
146
+ void this.flushOnce().then(() => { this.schedule(); });
147
+ }, this.retryMs || BATCH_DELAY_MS);
148
+ this.timer.unref();
149
+ }
150
+ flushOnce() {
151
+ this.writing ??= this.write().then(() => {
152
+ this.retryMs = 0;
153
+ return true;
154
+ }, () => {
155
+ this.retryMs = Math.min(MAX_RETRY_MS, this.retryMs === 0 ? MIN_RETRY_MS : this.retryMs * 2);
156
+ return false;
157
+ }).finally(() => { this.writing = undefined; });
158
+ return this.writing;
159
+ }
160
+ async write() {
161
+ try {
162
+ await this.ready();
163
+ }
164
+ catch (error) {
165
+ this.loaded = undefined;
166
+ throw error;
167
+ }
168
+ this.trim();
169
+ const batch = new Map(this.pending);
170
+ if (batch.size === 0)
171
+ return;
172
+ if (!this.canAppend || this.journalRows + batch.size > COMPACT_AFTER) {
173
+ const snapshot = JOURNAL_HEADER + '\n' + encodeRows(this.entries);
174
+ const rows = this.entries.size;
175
+ const temporary = this.journal + '.tmp';
176
+ await fs.mkdir(dirname(this.journal), { recursive: true, mode: 0o700 });
177
+ try {
178
+ await fs.writeFile(temporary, snapshot, { mode: 0o600 });
179
+ await fs.rename(temporary, this.journal);
180
+ }
181
+ catch (error) {
182
+ await fs.rm(temporary, { force: true }).catch(() => { });
183
+ throw error;
184
+ }
185
+ this.canAppend = true;
186
+ this.journalRows = rows;
187
+ }
188
+ else {
189
+ // Start at a fresh line even if an interrupted append left a partial
190
+ // record behind. Recovery ignores malformed rows and keeps valid ones.
191
+ await fs.appendFile(this.journal, '\n' + encodeRows(batch), { mode: 0o600 });
192
+ this.journalRows += batch.size + 1;
193
+ }
194
+ for (const [key, entry] of batch) {
195
+ if (this.pending.get(key) === entry)
196
+ this.pending.delete(key);
197
+ }
198
+ }
199
+ }
200
+ const caches = new Map();
201
+ export function openDiscoveryCache(file, decode) {
202
+ const path = resolve(file);
203
+ let cache = caches.get(path);
204
+ if (cache === undefined) {
205
+ cache = new DiscoveryCache(path, decode);
206
+ caches.set(path, cache);
207
+ }
208
+ cache.acquire();
209
+ return cache;
210
+ }
@@ -8,24 +8,31 @@
8
8
  * profile state; conclusions are never cached because they depend on the DSH
9
9
  * version of the process serving the page.
10
10
  */
11
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
12
- import { dirname } from 'node:path';
11
+ import { createHash } from 'node:crypto';
13
12
  import { compareSemver, isSemver, satisfiesRange } from './check.js';
14
13
  import { classifyPeer, crossesImplicitCeiling } from './compatibility.js';
14
+ import { openDiscoveryCache } from './discovery-cache.js';
15
15
  import { marketFetch } from './net.js';
16
16
  import { isStableReleaseVersion } from './release-candidates.js';
17
17
  import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
18
18
  import { parseSourceUrl } from './sources.js';
19
- const CACHE_SCHEMA = 'dsh-crate/discovery-compatibility-cache/v1';
20
19
  const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
21
20
  const FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
22
21
  const OUTAGE_COOLDOWN_MS = 30 * 1000;
23
22
  const FETCH_TIMEOUT_MS = 8_000;
24
23
  const DEFAULT_CONCURRENCY = 8;
25
- // Larger than the catalog (10k+ and growing). A cap below the catalog size
26
- // made a full scan evict its own first half, so no scan ever stayed cached (#1170).
27
- const MAX_CACHE_ENTRIES = 20_000;
28
24
  const MAX_RANGE_LENGTH = 256;
25
+ /** Only the selected artifact and its declarations determine a discovery verdict. */
26
+ export function githubCompatibilityRevision(source) {
27
+ const facts = catalogReleaseManifest(source);
28
+ return createHash('sha256').update(JSON.stringify([
29
+ source.url,
30
+ source.tarball ?? null,
31
+ range(source.version),
32
+ facts === null ? null : [facts.version, facts.enginesDsh,
33
+ Object.entries(facts.peerDependencies).sort(), Object.entries(facts.dependencies ?? {}).sort()],
34
+ ])).digest('hex');
35
+ }
29
36
  /** Reuse catalog facts only for this repository's exact pinned install asset. */
30
37
  export function catalogReleaseManifest(source) {
31
38
  const facts = record(source.releaseManifest);
@@ -41,6 +48,14 @@ export function catalogReleaseManifest(source) {
41
48
  dependencies: facts.dependencies ?? {},
42
49
  };
43
50
  }
51
+ function npmDiscoveryKey(name, registry, version) {
52
+ return version === undefined ? name : `npm:${registry}\u0000${name}\u0000${version}`;
53
+ }
54
+ function githubDiscoveryKey(source) {
55
+ const key = `github:${source.url}\u0000${source.tarball ?? ''}`;
56
+ const version = range(source.version);
57
+ return version === null ? key : `${key}\u0000${version}`;
58
+ }
44
59
  /** Read the linked package at its selected release, never the repository root by accident. */
45
60
  async function githubManifest(source, fetcher) {
46
61
  const parsed = parseSourceUrl(source.url);
@@ -167,6 +182,14 @@ function validFacts(value) {
167
182
  && Object.entries(peers).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item)
168
183
  && (dependencies === null || Object.entries(dependencies).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item));
169
184
  }
185
+ function decodeCacheEntry(value) {
186
+ const entry = record(value);
187
+ if (entry === null || typeof entry.checkedAt !== 'number' || !Number.isFinite(entry.checkedAt) || !validFacts(entry.facts))
188
+ return null;
189
+ // Normalize the pre-upgrade shape so every consumer sees an object.
190
+ const facts = entry.facts.dependencies === undefined ? { ...entry.facts, dependencies: {} } : entry.facts;
191
+ return { checkedAt: entry.checkedAt, facts };
192
+ }
170
193
  function displayRequirement(declarations) {
171
194
  const unique = [...new Set(declarations.map(item => item.range))];
172
195
  return unique.length === 0 ? null : unique.join(' ∩ ');
@@ -262,114 +285,89 @@ export function deriveHostCompatibility(facts, hostVersion, hostPackages) {
262
285
  return { status, basis: 'manifest', requirement, declarations };
263
286
  }
264
287
  /**
265
- * Durable, bounded lookup of npm `latest` and catalog GitHub manifests.
288
+ * Durable, bounded lookup of npm releases and catalog GitHub manifests.
266
289
  *
267
290
  * Failed requests are intentionally memory-only and short-lived: a mirror
268
291
  * outage must not become a day-long false "undeclared" result on disk.
269
292
  */
270
293
  export class DiscoveryManifestIndex {
271
- cacheFile;
272
- entries = new Map();
294
+ cache;
273
295
  failures = new Map();
274
296
  inflight = new Map();
275
297
  fetcher;
276
298
  now;
277
299
  ttlMs;
278
300
  concurrency;
279
- loaded = false;
280
301
  consecutiveFailures = 0;
281
302
  unavailableUntil = 0;
282
- dirty = false;
303
+ disposed = false;
283
304
  activeFetches = 0;
284
305
  fetchWaiters = [];
285
306
  constructor(cacheFile, options = {}) {
286
- this.cacheFile = cacheFile;
307
+ this.cache = openDiscoveryCache(cacheFile, decodeCacheEntry);
287
308
  this.fetcher = options.fetcher ?? marketFetch;
288
309
  this.now = options.now ?? Date.now;
289
310
  this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
290
311
  this.concurrency = Math.max(1, Math.floor(options.concurrency ?? DEFAULT_CONCURRENCY));
291
312
  }
292
- load() {
293
- if (this.loaded)
313
+ /** Unmount this index, retaining any writes already queued for this profile. */
314
+ async dispose() {
315
+ if (this.disposed)
294
316
  return;
295
- this.loaded = true;
296
- try {
297
- const parsed = JSON.parse(readFileSync(this.cacheFile, 'utf8'));
298
- if (parsed.schema !== CACHE_SCHEMA || record(parsed.entries) === null)
299
- return;
300
- for (const [name, raw] of Object.entries(parsed.entries)) {
301
- const entry = record(raw);
302
- if (entry === null || typeof entry.checkedAt !== 'number' || !validFacts(entry.facts))
303
- continue;
304
- // Normalize the pre-upgrade shape so every consumer sees an object.
305
- const facts = entry.facts.dependencies === undefined
306
- ? { ...entry.facts, dependencies: {} }
307
- : entry.facts;
308
- this.entries.set(name, { checkedAt: entry.checkedAt, facts });
309
- }
310
- }
311
- catch { /* first run or a truncated cache — fetch fresh */ }
312
- }
313
- persist() {
314
- try {
315
- mkdirSync(dirname(this.cacheFile), { recursive: true, mode: 0o700 });
316
- const newest = [...this.entries.entries()]
317
- .sort(([, a], [, b]) => b.checkedAt - a.checkedAt)
318
- .slice(0, MAX_CACHE_ENTRIES);
319
- this.entries.clear();
320
- for (const [name, entry] of newest)
321
- this.entries.set(name, entry);
322
- const data = { schema: CACHE_SCHEMA, entries: Object.fromEntries(newest) };
323
- writeFileSync(this.cacheFile, JSON.stringify(data), { mode: 0o600 });
324
- }
325
- catch { /* cache failure degrades to in-memory lookups */ }
317
+ this.disposed = true;
318
+ await this.cache.release();
326
319
  }
327
320
  /** One semaphore for the whole index, including overlapping HTTP batches. */
328
321
  async withFetchPermit(operation) {
329
322
  if (this.activeFetches >= this.concurrency) {
330
323
  await new Promise(resolve => this.fetchWaiters.push(resolve));
331
324
  }
332
- this.activeFetches += 1;
325
+ else
326
+ this.activeFetches += 1;
333
327
  try {
334
328
  return await operation();
335
329
  }
336
330
  finally {
337
- this.activeFetches -= 1;
338
- this.fetchWaiters.shift()?.();
331
+ const next = this.fetchWaiters.shift();
332
+ if (next === undefined)
333
+ this.activeFetches -= 1;
334
+ else
335
+ next();
339
336
  }
340
337
  }
341
- async fetchOne(name, registry, record = true, readManifest) {
342
- this.load();
338
+ retryDelay(key, now = this.now()) {
339
+ return Math.max(0, Math.max(this.failures.get(key) ?? 0, this.unavailableUntil) - now);
340
+ }
341
+ npmRetryAfterMs(name, registry, version) {
342
+ return this.retryDelay(npmDiscoveryKey(name, registry, version));
343
+ }
344
+ githubRetryAfterMs(source) {
345
+ return this.retryDelay(githubDiscoveryKey(source));
346
+ }
347
+ async fetchOne(cacheKey, record, readManifest, expectedVersion) {
348
+ const cached = await this.cache.get(cacheKey);
343
349
  const now = this.now();
344
- const cached = this.entries.get(name);
345
- if (cached !== undefined && now - cached.checkedAt < this.ttlMs)
350
+ if (cached !== undefined && now - cached.checkedAt < this.ttlMs
351
+ && (expectedVersion === undefined || cached.facts.version === expectedVersion))
346
352
  return cached.facts;
347
- if ((this.failures.get(name) ?? 0) > now || this.unavailableUntil > now)
353
+ if (this.retryDelay(cacheKey, now) > 0)
348
354
  return null;
349
355
  // Advisory and recording lookups keep separate in-flight slots: an
350
356
  // advisory call must not be answered by — or hand its answer to — a
351
357
  // recording one, or `record` would stop meaning anything when the two
352
358
  // overlap on the same package.
353
- const key = record ? name : `${name}\u0000advisory`;
359
+ const key = record ? cacheKey : `${cacheKey}\u0000advisory`;
354
360
  const pending = this.inflight.get(key);
355
361
  if (pending !== undefined)
356
362
  return await pending;
357
363
  const request = (async () => {
358
364
  try {
359
- const value = await this.withFetchPermit(readManifest ?? (async () => {
360
- const response = await this.fetcher(`${registry}/${encodeURIComponent(name)}/latest`, {
361
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
362
- headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
363
- });
364
- if (!response.ok)
365
- throw new Error(`HTTP ${String(response.status)}`);
366
- return await response.json();
367
- }));
368
- const facts = manifestFacts(value);
369
- if (record) {
370
- this.entries.set(name, { checkedAt: this.now(), facts });
371
- this.dirty = true;
372
- this.failures.delete(name);
365
+ const facts = await this.withFetchPermit(readManifest);
366
+ if (expectedVersion !== undefined && facts.version !== expectedVersion)
367
+ throw new Error('npm returned a different release');
368
+ if (record && !this.disposed) {
369
+ this.cache.set(cacheKey, { checkedAt: this.now(), facts });
370
+ this.failures.delete(cacheKey);
373
371
  this.consecutiveFailures = 0;
374
372
  }
375
373
  return facts;
@@ -377,7 +375,7 @@ export class DiscoveryManifestIndex {
377
375
  catch {
378
376
  if (record) {
379
377
  const failedAt = this.now();
380
- this.failures.set(name, failedAt + FAILURE_COOLDOWN_MS);
378
+ this.failures.set(cacheKey, failedAt + FAILURE_COOLDOWN_MS);
381
379
  this.consecutiveFailures += 1;
382
380
  if (this.consecutiveFailures >= this.concurrency) {
383
381
  this.unavailableUntil = failedAt + OUTAGE_COOLDOWN_MS;
@@ -392,6 +390,15 @@ export class DiscoveryManifestIndex {
392
390
  this.inflight.set(key, request);
393
391
  return await request;
394
392
  }
393
+ async readNpmManifest(name, version, registry) {
394
+ const response = await this.fetcher(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
395
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
396
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
397
+ });
398
+ if (!response.ok)
399
+ throw new Error(`HTTP ${String(response.status)}`);
400
+ return await response.json();
401
+ }
395
402
  /**
396
403
  * Facts for ONE named release, rather than for `latest`.
397
404
  *
@@ -403,24 +410,16 @@ export class DiscoveryManifestIndex {
403
410
  * release declares a range this host misses), and it would equally pass a
404
411
  * pinned release that is itself incompatible.
405
412
  *
406
- * Deliberately outside the cache. The index is keyed by package name, and a
407
- * version-keyed one would grow with every release anyone ever pinned to
408
- * answer a question asked once per install. Nothing is recorded either: a
409
- * pre-flight verdict must not decide what the diagnostics panel sees next
410
- * (#619).
413
+ * Deliberately outside the cache. An install can target any old release,
414
+ * whereas a discovery query is for the version shown in the catalog. A
415
+ * pre-flight verdict must not decide what the diagnostics panel sees next (#619).
411
416
  *
412
417
  * A release whose manifest cannot be read is `null`, like every other
413
418
  * unreadable manifest: absence of a claim is not a verdict.
414
419
  */
415
420
  async lookupVersion(name, version, registry) {
416
421
  try {
417
- const response = await this.withFetchPermit(async () => await this.fetcher(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
418
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
419
- headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
420
- }));
421
- if (!response.ok)
422
- return null;
423
- return manifestFacts(await response.json());
422
+ return manifestFacts(await this.withFetchPermit(() => this.readNpmManifest(name, version, registry)));
424
423
  }
425
424
  catch {
426
425
  return null;
@@ -436,21 +435,25 @@ export class DiscoveryManifestIndex {
436
435
  * diagnostics panel sees next (#619).
437
436
  */
438
437
  async lookup(names, registry, options = {}) {
439
- const record = options.record !== false;
438
+ const shouldRecord = options.record !== false;
440
439
  const unique = [...new Set(names)];
441
440
  const result = {};
442
441
  let next = 0;
443
442
  const worker = async () => {
444
443
  while (next < unique.length) {
445
444
  const name = unique[next++];
446
- result[name] = await this.fetchOne(name, registry, record);
445
+ const version = options.versions?.get(name);
446
+ result[name] = await this.fetchOne(npmDiscoveryKey(name, registry, version), shouldRecord, async () => {
447
+ const manifest = await this.readNpmManifest(name, version ?? 'latest', registry);
448
+ const returnedName = record(manifest)?.name;
449
+ if (version !== undefined && returnedName !== undefined && returnedName !== name) {
450
+ throw new Error('npm returned a different package');
451
+ }
452
+ return manifestFacts(manifest);
453
+ }, version);
447
454
  }
448
455
  };
449
456
  await Promise.all(Array.from({ length: Math.min(this.concurrency, unique.length) }, worker));
450
- if (this.dirty) {
451
- this.dirty = false;
452
- this.persist();
453
- }
454
457
  return result;
455
458
  }
456
459
  /** Catalog-approved GitHub sources, cached by both package path and selected archive. */
@@ -461,15 +464,10 @@ export class DiscoveryManifestIndex {
461
464
  const worker = async () => {
462
465
  while (next < unique.length) {
463
466
  const source = unique[next++];
464
- const key = `github:${source.url}\u0000${source.tarball ?? ''}`;
465
- result[source.url] = await this.fetchOne(key, '', true, () => githubManifest(source, this.fetcher));
467
+ result[source.url] = await this.fetchOne(githubDiscoveryKey(source), true, async () => manifestFacts(await githubManifest(source, this.fetcher)));
466
468
  }
467
469
  };
468
470
  await Promise.all(Array.from({ length: Math.min(this.concurrency, unique.length) }, worker));
469
- if (this.dirty) {
470
- this.persist();
471
- this.dirty = false;
472
- }
473
471
  return result;
474
472
  }
475
473
  }
package/lib/dsh-cli.js CHANGED
@@ -971,20 +971,50 @@ export const BOOT_ID = `${String(process.pid)}-${String(Date.now())}`;
971
971
  * it (defense in depth on top of per-route validation — the win32 bare-dsh
972
972
  * fallback runs through a shell). Suggested in #16 by @anupamme.
973
973
  *
974
- * `^`, `~` and `=` are intentionally allowed: restore/install flows turn
975
- * manifest specs such as "dsh-better-sidebar": "^0.14.0" into targets like
974
+ * `^`, `~` and `=`: restore/install flows turn manifest specs such as
975
+ * "dsh-better-sidebar": "^0.14.0" into targets like
976
976
  * `dsh-better-sidebar@^0.14.0`, and regex-valid semver ranges must not be
977
977
  * mistaken for shell injection (whitespace and shell metacharacters remain
978
978
  * rejected — the win32 bare-dsh fallback is the reason to keep them out).
979
+ *
980
+ * `&` is deliberately absent: a bare `&` backgrounds the child and must stay
981
+ * rejected. The one shape that needs it — pnpm's monorepo selector,
982
+ * `#<ref>&path:/packages/x` — is admitted by `isSafePluginTarget` instead.
979
983
  */
980
984
  export const TARGET_RE = /^[A-Za-z0-9@:./_#+~^=-]+$/;
985
+ /** pnpm's monorepo selector inside a git target: `&path:/<subdirectory>`. */
986
+ const GIT_SUBPATH_SELECTOR_RE = /^&path:\/[A-Za-z0-9._\-/]*$/;
987
+ /**
988
+ * Whether one plugin target is safe to hand to a spawned pnpm.
989
+ *
990
+ * A target is safe when `TARGET_RE` accepts it whole, or when it is that same
991
+ * allowlisted head followed only by `&path:` selectors. pnpm spells a
992
+ * monorepo subdirectory as `github:owner/repo#<ref>&path:/packages/x`, which
993
+ * `TARGET_RE` alone rejects — every GitHub subpath install then failed as
994
+ * "unsafe plugin target".
995
+ *
996
+ * @param target - the last argv element the caller built.
997
+ * @returns true when no segment could be read as a shell separator.
998
+ */
999
+ export function isSafePluginTarget(target) {
1000
+ if (TARGET_RE.test(target))
1001
+ return true;
1002
+ if (!target.includes('&'))
1003
+ return false;
1004
+ // Every `&` must OPEN a selector: a trailing `&`, `&&`, or `& ` leaves a
1005
+ // segment that is not one, and the head itself still has to pass TARGET_RE.
1006
+ const [head = '', ...selectors] = target.split('&');
1007
+ if (!TARGET_RE.test(head))
1008
+ return false;
1009
+ return selectors.every(selector => GIT_SUBPATH_SELECTOR_RE.test(`&${selector}`));
1010
+ }
981
1011
  /** Mutating pnpm commands get the structured reporter appended. */
982
1012
  const NDJSON_COMMANDS = new Set(['add', 'remove', 'install', 'update']);
983
1013
  /** Apply profile-specific pnpm compatibility and the structured reporter. */
984
1014
  function preparePluginArgs(profileDirectory, pluginArgs) {
985
1015
  let args = pluginArgsFor(profileDirectory, [...pluginArgs]);
986
1016
  const target = args[args.length - 1] ?? '';
987
- if (!TARGET_RE.test(target)) {
1017
+ if (!isSafePluginTarget(target)) {
988
1018
  return { error: `unsafe plugin target rejected: ${JSON.stringify(target)}` };
989
1019
  }
990
1020
  if (NDJSON_COMMANDS.has(args[0]))
@@ -1096,7 +1126,7 @@ export function runHostPnpm(invocation, cwd, args) {
1096
1126
  timedOut,
1097
1127
  stdout: stdoutBytes.text(),
1098
1128
  stderr: stderrBytes.text(),
1099
- cancelled: cancelRequested,
1129
+ cancelled: cancelRequested && code !== 0,
1100
1130
  });
1101
1131
  });
1102
1132
  });
@@ -1177,7 +1207,7 @@ export function runDshPlugin(profile, pluginArgs) {
1177
1207
  timedOut,
1178
1208
  stdout: stdoutBytes.text(),
1179
1209
  stderr: stderrBytes.text(),
1180
- cancelled: cancelRequested,
1210
+ cancelled: cancelRequested && code !== 0,
1181
1211
  ...(pnpmError !== null ? { pnpmError } : {}),
1182
1212
  ...(pnpmErrorCode !== null ? { pnpmErrorCode } : {}),
1183
1213
  ...(ignoredBuilds.length > 0 ? { ignoredBuilds } : {}),
@@ -1285,7 +1315,7 @@ export function createDesktopPluginRuntime(service, activeProfileDir, invokingDi
1285
1315
  timedOut,
1286
1316
  stdout: stdoutBytes.text(),
1287
1317
  stderr: stderrBytes.text(),
1288
- cancelled: active.userCancelled,
1318
+ cancelled: active.userCancelled && failed,
1289
1319
  ...(ignoredBuilds.length > 0 ? { ignoredBuilds } : {}),
1290
1320
  ...(pnpmError !== null ? { pnpmError } : {}),
1291
1321
  ...(pnpmErrorCode !== null ? { pnpmErrorCode } : {}),