dsh-crate 0.5.5 → 0.5.6

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 (44) hide show
  1. package/client/client.js +1832 -617
  2. package/lib/changelog.js +71 -28
  3. package/lib/gist.js +1 -1
  4. package/lib/hot.js +18 -6
  5. package/lib/index.js +10 -3
  6. package/lib/install.js +200 -9
  7. package/lib/official-desktop.js +80 -16
  8. package/lib/patch.js +223 -25
  9. package/lib/pending-checkout-links.js +123 -0
  10. package/lib/pending-updates.js +7 -4
  11. package/lib/profile.js +36 -0
  12. package/lib/registry.js +38 -20
  13. package/lib/release-blockers.js +177 -0
  14. package/lib/release-history.js +149 -0
  15. package/lib/release-updates.js +1 -34
  16. package/lib/routes.js +843 -166
  17. package/lib/sources.js +42 -2
  18. package/lib/startup-repair-report.js +46 -0
  19. package/lib/themes.js +7 -5
  20. package/lib/types/changelog.d.ts +4 -1
  21. package/lib/types/dsh-cli.d.ts +8 -0
  22. package/lib/types/gist.d.ts +1 -1
  23. package/lib/types/hot.d.ts +2 -1
  24. package/lib/types/install.d.ts +22 -4
  25. package/lib/types/official-desktop.d.ts +4 -0
  26. package/lib/types/patch.d.ts +36 -0
  27. package/lib/types/pending-checkout-links.d.ts +35 -0
  28. package/lib/types/pending-updates.d.ts +2 -0
  29. package/lib/types/profile.d.ts +3 -0
  30. package/lib/types/registry.d.ts +6 -8
  31. package/lib/types/release-blockers.d.ts +34 -0
  32. package/lib/types/release-history.d.ts +34 -0
  33. package/lib/types/release-updates.d.ts +2 -11
  34. package/lib/types/routes.d.ts +3 -0
  35. package/lib/types/sources.d.ts +11 -0
  36. package/lib/types/startup-repair-report.d.ts +20 -0
  37. package/lib/types/themes.d.ts +2 -2
  38. package/lib/types/update-notifications.d.ts +6 -0
  39. package/lib/types/updates.d.ts +19 -0
  40. package/lib/update-notifications.js +6 -4
  41. package/lib/updates.js +16 -0
  42. package/locale/en.json +1 -1
  43. package/locale/ja.json +5 -0
  44. package/package.json +2 -2
@@ -25,7 +25,6 @@ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from '
25
25
  import { dirname, join } from 'node:path';
26
26
  import { logEvent } from './log.js';
27
27
  import { readInstalledManifest, readInstalledVersion, readManifestDeps, readProfileBundles } from './profile.js';
28
- import { statePath } from './state.js';
29
28
  const STATE_VERSION = 1;
30
29
  /**
31
30
  * The per-profile journal file.
@@ -35,7 +34,7 @@ const STATE_VERSION = 1;
35
34
  * resolution, and no path handed down from the host.
36
35
  */
37
36
  export function pendingUpdatesFile(profileDirectory) {
38
- return statePath(profileDirectory, 'pending-updates.json');
37
+ return join(profileDirectory, '.dsh-crate', 'pending-updates.json');
39
38
  }
40
39
  export class PendingUpdateJournal {
41
40
  file;
@@ -289,6 +288,7 @@ export async function repairInterruptedUpdates(options) {
289
288
  journal.bump(entry.id);
290
289
  report.failed.push({
291
290
  name: entry.name,
291
+ cause: 'version-changed',
292
292
  reason: `installed version ${installed} is neither ${entry.from || 'the previous build'} nor ${entry.to || 'the requested build'}`,
293
293
  });
294
294
  continue;
@@ -299,11 +299,12 @@ export async function repairInterruptedUpdates(options) {
299
299
  if (entry.attempts === MAX_AUTO_REPAIR_ATTEMPTS) {
300
300
  logEvent('error', 'update-repair', gaveUpCopy(entry.name, entry.attempts));
301
301
  }
302
- report.failed.push({ name: entry.name, reason: gaveUpCopy(entry.name, entry.attempts) });
302
+ report.failed.push({ name: entry.name, reason: gaveUpCopy(entry.name, entry.attempts), cause: 'abandoned' });
303
303
  report.abandoned.push(entry.name);
304
304
  continue;
305
305
  }
306
306
  const spec = entry.to === '' ? entry.spec : `${entry.name}@${entry.to}`;
307
+ let cause = 'unknown';
307
308
  try {
308
309
  // The interrupted update may have died holding the profile lock; its
309
310
  // owner is gone by now, and without this the install below waits out
@@ -317,6 +318,7 @@ export async function repairInterruptedUpdates(options) {
317
318
  // authority, not the application stage.
318
319
  const after = readInstalledVersion(options.profile, entry.name, options.profileDirectory);
319
320
  if (after === null || (entry.to !== '' && after !== entry.to)) {
321
+ cause = 'refused';
320
322
  throw new Error(`the desktop app refused the reinstall (${result.application})`);
321
323
  }
322
324
  // The files landing is not the same answer as the plugin loading:
@@ -324,6 +326,7 @@ export async function repairInterruptedUpdates(options) {
324
326
  // that writes `dsh.profile.bundles` (#928). Finishing here cleared
325
327
  // the record for a package the host still would not compose.
326
328
  if (!composed(options.profile, options.profileDirectory, entry.name)) {
329
+ cause = 'not-composed';
327
330
  throw new Error(`the desktop app wrote ${after} but did not compose it — no dsh.profile.bundles row`);
328
331
  }
329
332
  journal.finish(entry.id);
@@ -338,7 +341,7 @@ export async function repairInterruptedUpdates(options) {
338
341
  catch (error) {
339
342
  journal.bump(entry.id);
340
343
  const reason = error instanceof Error ? error.message : String(error);
341
- report.failed.push({ name: entry.name, reason });
344
+ report.failed.push({ name: entry.name, reason, cause: error instanceof DeadlineExceeded ? 'timeout' : cause });
342
345
  logEvent('error', 'update-repair', `${entry.name}: could not finish the interrupted update (${reason}); the next start will try again`);
343
346
  }
344
347
  }
package/lib/profile.js CHANGED
@@ -1346,6 +1346,42 @@ export function removeProfileBundle(profileDirectory, name) {
1346
1346
  writeManifestAtomic(manifestPath, manifest);
1347
1347
  return true;
1348
1348
  }
1349
+ /** Undo one switch's removal without replacing other manifest fields or a
1350
+ * bundle order edited by another writer. The caller holds the profile lock. */
1351
+ export function restoreRemovedProfileBundle(profileDirectory, name, before) {
1352
+ if (!before.profileBundles.present || !Array.isArray(before.profileBundles.value))
1353
+ return false;
1354
+ const previous = before.profileBundles.value;
1355
+ const originalIndex = previous.indexOf(name);
1356
+ if (originalIndex === -1)
1357
+ return false;
1358
+ const manifestPath = join(profileDirectory, 'package.json');
1359
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
1360
+ const profile = manifest.dsh?.profile;
1361
+ const current = profile?.bundles;
1362
+ if (profile === undefined || !Array.isArray(current) || current.includes(name)
1363
+ || manifest.dependencies?.[name] !== before.dependencies[name])
1364
+ return false;
1365
+ const remaining = previous.filter(entry => entry !== name);
1366
+ if (isDeepStrictEqual(current, remaining)) {
1367
+ profile.bundles = previous;
1368
+ }
1369
+ else {
1370
+ // Nearby surviving entries keep the old position meaningful even
1371
+ // when someone has added, removed, or moved other bundles.
1372
+ if (previous.lastIndexOf(name) !== originalIndex)
1373
+ return false;
1374
+ const earlier = new Set(previous.slice(0, originalIndex));
1375
+ const later = new Set(previous.slice(originalIndex + 1));
1376
+ const left = current.findLastIndex(entry => earlier.has(entry));
1377
+ const right = current.findIndex(entry => later.has(entry));
1378
+ if ((left === -1 && right === -1) || (right !== -1 && left >= right))
1379
+ return false;
1380
+ current.splice(right === -1 ? left + 1 : right, 0, name);
1381
+ }
1382
+ writeManifestAtomic(manifestPath, manifest);
1383
+ return true;
1384
+ }
1349
1385
  /**
1350
1386
  * Re-add a bundle to `dsh.profile.bundles` after a carrier toggle-off (#224).
1351
1387
  * Idempotent: a bundle already present is left untouched. The name is appended
package/lib/registry.js CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Registry access: the curated list from awesome-dsh-plugin.com, fetched
3
- * fresh on every request. See `loadRegistry` for why there is nothing
4
- * behind it any more.
2
+ * Access to the curated list from awesome-dsh-plugin.com. Each new load
3
+ * revalidates the catalog with its source.
5
4
  */
6
5
  import { BODY_STALL_TIMEOUT_MS, HEADERS_TIMEOUT_MS, readBodyWhileProgressing } from './body-progress.js';
7
6
  import { logEvent } from './log.js';
@@ -92,10 +91,9 @@ export function pluginPreviousNpm(plugin) {
92
91
  * This is NOT the cache that was removed, and the difference is the whole
93
92
  * point. That cache SKIPPED the request for an hour and answered from
94
93
  * memory — it asserted freshness without ever asking. This asks the origin
95
- * every single time; the validator only lets the origin answer "still the
96
- * same" (304) instead of resending a megabyte. Freshness is verified on
97
- * every call either way, so `data` below is only ever returned when the
98
- * server has just confirmed it is current.
94
+ * on each new load; concurrent readers share that validation. The validator
95
+ * lets the origin answer "still the same" (304) instead of resending a megabyte.
96
+ * `data` below is only returned after the origin confirms it is current.
99
97
  *
100
98
  * In memory rather than on disk: a restart is rare enough that paying one
101
99
  * full download for it costs nothing, and a file would be one more thing
@@ -107,6 +105,9 @@ export function pluginPreviousNpm(plugin) {
107
105
  * downloading the full 1.07 MB every time they opened the market.
108
106
  */
109
107
  let served = null;
108
+ let pendingCatalog = null;
109
+ // Each new load or explicit reset supersedes the previous cache writer.
110
+ let catalogRevision = 0;
110
111
  /** Identity of a catalog source, for scoping the validator to its origin. */
111
112
  function sourceKey(source) {
112
113
  return source.kind === 'npm' ? `npm:${source.registry}/${source.pkg}` : `url:${source.url}`;
@@ -144,16 +145,17 @@ function asRegistry(value) {
144
145
  return { ...data, plugins };
145
146
  }
146
147
  /**
147
- * Drop what we remember, so the next call is unconditional.
148
- *
149
- * Exists for tests: the memo is module state, and a spec that asserted a
150
- * 304 would otherwise leak a validator into the next one.
148
+ * Drop the validator and detach any earlier load, so the next call starts an
149
+ * unconditional request. Earlier callers can still receive their own result.
151
150
  */
152
151
  export function forgetCatalog() {
153
152
  served = null;
153
+ pendingCatalog = null;
154
+ catalogRevision += 1;
154
155
  }
155
156
  /**
156
- * The catalog, revalidated every time it is asked for.
157
+ * The catalog, revalidated on each new load. Discovery and the update check
158
+ * share a revalidation while it is in flight for the same configured sources.
157
159
  *
158
160
  * There used to be three answers here — live, a one-hour in-memory cache,
159
161
  * and a snapshot bundled into the npm package — and only the first was
@@ -172,8 +174,23 @@ export function forgetCatalog() {
172
174
  * would rebuild exactly the fallback this replaced.
173
175
  * @throws when the catalog cannot be fetched or does not look like one.
174
176
  */
175
- export async function loadRegistry(region = activeRegion()) {
177
+ export function loadRegistry(region = activeRegion()) {
178
+ const ownSources = routesFor(region).catalog.length;
179
+ const catalogSources = catalogSourcesFor(region);
180
+ const key = JSON.stringify([region, ownSources, catalogSources.map(sourceKey)]);
181
+ if (pendingCatalog?.key === key)
182
+ return pendingCatalog.result;
183
+ const revision = ++catalogRevision;
184
+ const result = fetchCatalog(region, ownSources, catalogSources, revision).finally(() => {
185
+ if (revision === catalogRevision)
186
+ pendingCatalog = null;
187
+ });
188
+ pendingCatalog = { key, result };
189
+ return result;
190
+ }
191
+ async function fetchCatalog(region, ownSources, catalogSources, revision) {
176
192
  const started = Date.now();
193
+ const previous = served;
177
194
  let last;
178
195
  let attempts = 0;
179
196
  /**
@@ -198,8 +215,6 @@ export async function loadRegistry(region = activeRegion()) {
198
215
  // decided once and persisted. The catalog's published package, on the
199
216
  // registry the probe just proved reachable, is the repair that needs
200
217
  // neither the probe nor the decision to change.
201
- const ownSources = routesFor(region).catalog.length;
202
- const catalogSources = catalogSourcesFor(region);
203
218
  for (const [sourceIndex, source] of catalogSources.entries()) {
204
219
  const key = sourceKey(source);
205
220
  const servedBy = (data) => {
@@ -226,7 +241,7 @@ export async function loadRegistry(region = activeRegion()) {
226
241
  // A validator only ever goes back to the source that issued it.
227
242
  // Carried across a region switch it could earn a "not modified" from
228
243
  // an origin whose body we have never seen.
229
- const reusable = served?.key === key ? served : null;
244
+ const reusable = previous?.key === key ? previous : null;
230
245
  if (source.kind === 'npm') {
231
246
  const { version, data } = await catalogFromPackage(source.registry, source.pkg, reusable?.version ?? undefined);
232
247
  // `data === null` means the published version is the one in hand.
@@ -235,7 +250,8 @@ export async function loadRegistry(region = activeRegion()) {
235
250
  if (data === null)
236
251
  throw new Error('the catalog package reported no change with nothing to reuse');
237
252
  const parsed = parseCatalog(data);
238
- served = { key, etag: null, modified: null, version, data: parsed };
253
+ if (revision === catalogRevision)
254
+ served = { key, etag: null, modified: null, version, data: parsed };
239
255
  return servedBy(parsed);
240
256
  }
241
257
  // ETag first: it is exact, while a date has one-second resolution and
@@ -274,9 +290,11 @@ export async function loadRegistry(region = activeRegion()) {
274
290
  if (!res.ok)
275
291
  throw new Error(`HTTP ${String(res.status)}`);
276
292
  const data = parseCatalog(JSON.parse(new TextDecoder().decode(await readBodyWhileProgressing(res, BODY_STALL_TIMEOUT_MS))));
277
- served = {
278
- key, etag: res.headers.get('etag'), modified: res.headers.get('last-modified'), version: null, data,
279
- };
293
+ if (revision === catalogRevision) {
294
+ served = {
295
+ key, etag: res.headers.get('etag'), modified: res.headers.get('last-modified'), version: null, data,
296
+ };
297
+ }
280
298
  return servedBy(data);
281
299
  }
282
300
  catch (error) {
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Profile-level fresh-release blockers (#1252).
3
+ *
4
+ * pnpm checks the WHOLE lockfile against `minimumReleaseAge` before it lets
5
+ * any change through. One young entry (say `dsh-mobile-plugin@0.5.71`) makes
6
+ * every update, install and removal of that profile fail, whichever plugin
7
+ * the user clicked. The update check only judges each plugin's own target
8
+ * (#945), so every row still looked updatable.
9
+ *
10
+ * The market does not ask the registry for the publish time of every lockfile
11
+ * entry. It learns from the first refusal instead: pnpm prints each offending
12
+ * `name@version` with its publish time, and that is kept here until the wait
13
+ * ends. No extra registry traffic, and nothing is guessed: a time that cannot
14
+ * be read is recorded as unknown and held for a short, fixed time (#961).
15
+ */
16
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join } from 'node:path';
18
+ /** How long a blocker with an unknown end time is believed (same as #961). */
19
+ export const UNKNOWN_BLOCKER_TTL_MS = 30 * 60 * 1000;
20
+ const MAX_BLOCKERS = 50;
21
+ const FILE = join('.dsh-crate', 'release-blockers.json');
22
+ const ISO_TIME = /\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})/;
23
+ const LINE = /^\s*((?:@[^/\s@]+\/)?[^\s@]+)@(\d[^\s]*?)\s+was published at\b(.*)$/;
24
+ /** `a-{x,y}` becomes `a-x`, `a-y`; any other name is returned as is. */
25
+ function expandBraces(name) {
26
+ const match = /^(.*)\{([^{}]+)\}(.*)$/.exec(name);
27
+ if (match === null)
28
+ return [name];
29
+ return match[2].split(',').map(part => `${match[1]}${part.trim()}${match[3]}`);
30
+ }
31
+ /**
32
+ * Read the entries pnpm refused out of its violation output.
33
+ * @param output - pnpm's combined stdout and stderr.
34
+ * @param windowMs - the profile's effective wait, or null when it is unknown.
35
+ * @param now - epoch ms, injectable for tests.
36
+ * @returns one blocker per `name@version`; empty when the output names none.
37
+ */
38
+ export function parseReleaseAgeBlockers(output, windowMs, now = Date.now()) {
39
+ // Only the lockfile verification lists entries that are already in the
40
+ // profile. Any other release-age failure is about a target and says nothing
41
+ // about what else would be refused.
42
+ if (!output.includes('ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION') || !/lockfile entr(?:y|ies) failed verification/.test(output))
43
+ return [];
44
+ const seen = new Set();
45
+ const blockers = [];
46
+ for (const line of output.split(/\r?\n/)) {
47
+ const match = LINE.exec(line);
48
+ if (match === null)
49
+ continue;
50
+ const time = ISO_TIME.exec(match[3] ?? '')?.[0];
51
+ const published = time === undefined ? Number.NaN : Date.parse(time);
52
+ const publishedAt = Number.isFinite(published) ? new Date(published).toISOString() : null;
53
+ // A window that would already have ended contradicts pnpm's refusal: the
54
+ // market is reading a different wait than pnpm used. Say "unknown" rather
55
+ // than record a wait that is over and would never be believed.
56
+ const ready = publishedAt === null || windowMs === null ? null : published + windowMs;
57
+ const readyAt = ready === null || ready <= now ? null : new Date(ready).toISOString();
58
+ for (const name of expandBraces(match[1])) {
59
+ const key = `${name}@${match[2]}`;
60
+ if (seen.has(key))
61
+ continue;
62
+ seen.add(key);
63
+ blockers.push({ name, version: match[2], publishedAt, readyAt });
64
+ if (blockers.length >= MAX_BLOCKERS)
65
+ return blockers;
66
+ }
67
+ }
68
+ return blockers;
69
+ }
70
+ const memory = new Map();
71
+ function load(dir) {
72
+ const cached = memory.get(dir);
73
+ if (cached !== undefined)
74
+ return cached;
75
+ let loaded = [];
76
+ try {
77
+ const raw = JSON.parse(readFileSync(join(dir, FILE), 'utf8'));
78
+ if (Array.isArray(raw.blockers)) {
79
+ loaded = raw.blockers.flatMap((item) => {
80
+ const entry = item;
81
+ if (entry === null || typeof entry !== 'object')
82
+ return [];
83
+ if (typeof entry.name !== 'string' || typeof entry.version !== 'string' || typeof entry.learnedAt !== 'number')
84
+ return [];
85
+ return [{
86
+ name: entry.name, version: entry.version, learnedAt: entry.learnedAt,
87
+ publishedAt: typeof entry.publishedAt === 'string' ? entry.publishedAt : null,
88
+ readyAt: typeof entry.readyAt === 'string' ? entry.readyAt : null,
89
+ }];
90
+ });
91
+ }
92
+ }
93
+ catch { /* no file, or unreadable: start empty */ }
94
+ memory.set(dir, loaded);
95
+ return loaded;
96
+ }
97
+ function save(dir, blockers) {
98
+ memory.set(dir, blockers);
99
+ try {
100
+ const file = join(dir, FILE);
101
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
102
+ writeFileSync(file, JSON.stringify({ blockers }));
103
+ }
104
+ catch { /* memory still holds it; a restart just relearns on the next refusal */ }
105
+ }
106
+ /** Remember what pnpm just refused, replacing whatever was known for this profile. */
107
+ export function recordReleaseBlockers(dir, blockers, now = Date.now()) {
108
+ if (blockers.length === 0)
109
+ return;
110
+ save(dir, blockers.map(blocker => ({ ...blocker, learnedAt: now })));
111
+ }
112
+ /** Forget every blocker of this profile (a mutation went through without a bypass). */
113
+ export function clearReleaseBlockers(dir) {
114
+ if (load(dir).length === 0)
115
+ return;
116
+ save(dir, []);
117
+ }
118
+ /** Test seam: drop the in-memory copy so the next read comes from disk (a restart). */
119
+ export function forgetReleaseBlockerMemory() {
120
+ memory.clear();
121
+ }
122
+ /** Whether the lockfile still pins `name@version`; true when it cannot be read. */
123
+ function lockfileStillHas(dir, blocker) {
124
+ let text;
125
+ try {
126
+ text = readFileSync(join(dir, 'pnpm-lock.yaml'), 'utf8');
127
+ }
128
+ catch {
129
+ return true;
130
+ }
131
+ const escaped = `${blocker.name}@${blocker.version}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
132
+ return new RegExp(`(?:^|[\\s'"/(])${escaped}(?![\\w.+-])`, 'm').test(text);
133
+ }
134
+ /**
135
+ * The blockers that still hold, with the ended and the departed dropped.
136
+ * A blocker ends at its time, or after {@link UNKNOWN_BLOCKER_TTL_MS} when
137
+ * the time is unknown, or as soon as the lockfile no longer pins it.
138
+ */
139
+ export function activeReleaseBlockers(dir, now = Date.now()) {
140
+ const all = load(dir);
141
+ if (all.length === 0)
142
+ return [];
143
+ const live = all.filter(blocker => (blocker.readyAt === null
144
+ ? blocker.learnedAt + UNKNOWN_BLOCKER_TTL_MS > now
145
+ : Date.parse(blocker.readyAt) > now) && lockfileStillHas(dir, blocker));
146
+ if (live.length !== all.length)
147
+ save(dir, live);
148
+ return live.map(({ learnedAt: _learnedAt, ...blocker }) => blocker);
149
+ }
150
+ /** The one blocker to name: an unknown time first (nothing is certain), else the last to end. */
151
+ export function headlineBlocker(blockers) {
152
+ let best = null;
153
+ for (const blocker of blockers) {
154
+ if (blocker.readyAt === null)
155
+ return blocker;
156
+ if (best === null || Date.parse(blocker.readyAt) > Date.parse(best.readyAt))
157
+ best = blocker;
158
+ }
159
+ return best;
160
+ }
161
+ function pad(value) {
162
+ return String(value).padStart(2, '0');
163
+ }
164
+ /** `11-19 12:56` in the server's local time. */
165
+ function clock(at) {
166
+ const date = new Date(at);
167
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
168
+ }
169
+ /** What the update route says when it declines to start (bilingual, `zh / en`). */
170
+ export function releaseBlockedMessage(blocker) {
171
+ const what = `${blocker.name} ${blocker.version}`;
172
+ if (blocker.readyAt === null) {
173
+ return `要等 ${what} 满安全等待期后才能更新(时间未知)。在那之前,任何插件都更新不了,所以没有开始。 / Updates wait until ${what} has passed the safety wait (time unknown). Until then no plugin can be updated, so nothing was started.`;
174
+ }
175
+ const when = clock(blocker.readyAt);
176
+ return `要等 ${what} 满安全等待期(约 ${when})后才能更新。在那之前,任何插件都更新不了,所以没有开始。 / Updates wait until ${what} has passed the safety wait (about ${when}). Until then no plugin can be updated, so nothing was started.`;
177
+ }
@@ -0,0 +1,149 @@
1
+ import { marketFetch } from './net.js';
2
+ import { isStableReleaseVersion } from './release-candidates.js';
3
+ import { compareVersions } from './updates.js';
4
+ const MAX_BYTES = 1_048_576;
5
+ const MAX_RELEASES = 256;
6
+ const MAX_CACHED_REPOS = 32;
7
+ const HISTORY_TTL_MS = 60 * 60 * 1000;
8
+ const RETRY_MS = 30_000;
9
+ const cache = new Map();
10
+ export function isCommitId(value) {
11
+ return /^[0-9a-f]{40}$/i.test(value);
12
+ }
13
+ export function invalidateReleaseHistory() {
14
+ cache.clear();
15
+ }
16
+ function asRelease(value) {
17
+ if (value === null || typeof value !== 'object')
18
+ return null;
19
+ const { tag, body, name, publishedAt, url, commit } = value;
20
+ if (typeof tag !== 'string' || tag.length > 256 || typeof body !== 'string')
21
+ return null;
22
+ return {
23
+ tag, body,
24
+ name: typeof name === 'string' ? name : null,
25
+ publishedAt: typeof publishedAt === 'string' ? publishedAt : null,
26
+ url: typeof url === 'string' ? url : null,
27
+ commit: typeof commit === 'string' && isCommitId(commit) ? commit.toLowerCase() : null,
28
+ };
29
+ }
30
+ /** Only the built catalog origin and a validated repository path can be fetched. */
31
+ async function fetchHistory(origin, repo) {
32
+ const url = new URL(`release-history/v1/${repo}.json`, origin);
33
+ const response = await marketFetch(url.href, {
34
+ signal: AbortSignal.timeout(5_000),
35
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
36
+ });
37
+ if (response.body === null)
38
+ return null;
39
+ if (!response.ok || Number(response.headers.get('content-length')) > MAX_BYTES) {
40
+ await response.body.cancel();
41
+ return null;
42
+ }
43
+ const reader = response.body.getReader();
44
+ const decoder = new TextDecoder();
45
+ let size = 0;
46
+ let json = '';
47
+ try {
48
+ for (;;) {
49
+ const { done, value } = await reader.read();
50
+ if (done)
51
+ break;
52
+ size += value.byteLength;
53
+ if (size > MAX_BYTES) {
54
+ await reader.cancel();
55
+ return null;
56
+ }
57
+ json += decoder.decode(value, { stream: true });
58
+ }
59
+ }
60
+ finally {
61
+ reader.releaseLock();
62
+ }
63
+ const data = JSON.parse(json + decoder.decode());
64
+ if (data?.repo !== repo || !Array.isArray(data.releases) || data.releases.length > MAX_RELEASES)
65
+ return null;
66
+ const releases = data.releases.map(asRelease).filter((release) => release !== null);
67
+ return { releases, complete: data.complete === true && releases.length === data.releases.length };
68
+ }
69
+ export function loadReleaseHistory(origin, repo) {
70
+ if (!/^[a-z0-9-]+\/[a-z0-9_.-]+$/.test(repo) || repo.endsWith('/.') || repo.endsWith('/..')) {
71
+ return Promise.resolve(null);
72
+ }
73
+ const key = `${origin}\n${repo}`;
74
+ const hit = cache.get(key);
75
+ if (hit !== undefined && Date.now() < hit.expires)
76
+ return hit.result;
77
+ cache.delete(key);
78
+ const entry = {
79
+ expires: Date.now() + HISTORY_TTL_MS,
80
+ result: fetchHistory(origin, repo).catch(() => null).then(result => {
81
+ if (result === null)
82
+ entry.expires = Date.now() + RETRY_MS;
83
+ return result;
84
+ }),
85
+ };
86
+ cache.set(key, entry);
87
+ if (cache.size > MAX_CACHED_REPOS)
88
+ cache.delete(cache.keys().next().value);
89
+ return entry.result;
90
+ }
91
+ /** A sibling's version or a number embedded in an unrelated tag is not a package release. */
92
+ export function packageReleaseVersion(tag, source) {
93
+ if (tag === null)
94
+ return null;
95
+ const separator = ['@', '-', '/'].find(mark => tag.startsWith(source.packageName + mark));
96
+ if (separator === undefined && !source.allowPlainTag)
97
+ return null;
98
+ const version = (separator === undefined ? tag : tag.slice(source.packageName.length + 1)).replace(/^v/, '');
99
+ return isStableReleaseVersion(version) ? version : null;
100
+ }
101
+ /** Installed and target versions are given by npm, or by exact release-tag SHAs for Git. */
102
+ export function releaseHistoryBetween(data, source, installed, target, current) {
103
+ const versions = new Map();
104
+ for (const release of data?.releases ?? []) {
105
+ const version = packageReleaseVersion(release.tag, source);
106
+ if (version !== null)
107
+ versions.set(version, versions.has(version) ? null : release);
108
+ }
109
+ const gitTarget = isCommitId(target);
110
+ const anchors = gitTarget && current !== null && versions.get(installed)?.commit === current.toLowerCase()
111
+ ? [...versions].filter(([version, release]) => release?.commit === target.toLowerCase()
112
+ && (compareVersions(version, installed) ?? 0) > 0)
113
+ : [];
114
+ const targetVersion = gitTarget ? anchors.length === 1 ? anchors[0][0] : null : target;
115
+ const items = [];
116
+ let preview = null;
117
+ let missing = targetVersion === null;
118
+ if (targetVersion !== null) {
119
+ missing = !versions.get(targetVersion)?.body.trim();
120
+ for (const [version, release] of versions) {
121
+ if ((compareVersions(version, installed) ?? 0) <= 0)
122
+ continue;
123
+ const beyond = (compareVersions(version, targetVersion) ?? 0) > 0;
124
+ if (release === null) {
125
+ if (!beyond)
126
+ missing = true;
127
+ continue;
128
+ }
129
+ const { tag, name, publishedAt, url, body } = release;
130
+ const item = { version, tag, name, publishedAt, url, body };
131
+ if (beyond) {
132
+ if (preview === null || (compareVersions(version, preview.version) ?? 0) > 0)
133
+ preview = item;
134
+ }
135
+ else {
136
+ items.push(item);
137
+ if (body.trim() === '')
138
+ missing = true;
139
+ }
140
+ }
141
+ items.sort((a, b) => compareVersions(b.version, a.version) ?? 0);
142
+ }
143
+ return {
144
+ history: { items, partial: data?.complete !== true || missing },
145
+ targetVersion,
146
+ targetCommit: gitTarget ? target : versions.get(target)?.commit ?? null,
147
+ preview,
148
+ };
149
+ }
@@ -1,40 +1,7 @@
1
1
  /** Published GitHub archives stay archive installs; never infer an npm identity. */
2
2
  import { marketFetch } from './net.js';
3
3
  import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
4
- import { installTargetFor, parseSourceUrl } from './sources.js';
5
- /** Only the catalog's own floating asset opts an existing archive into updates. */
6
- export function catalogReleaseSourceOf(spec, entry) {
7
- if (entry.npm !== null && entry.npm !== undefined)
8
- return null;
9
- const source = parseSourceUrl(entry.url);
10
- if (source === null || typeof entry.tarball !== 'string' || installTargetFor(entry) !== entry.tarball)
11
- return null;
12
- try {
13
- const approved = new URL(entry.tarball);
14
- const installed = new URL(spec);
15
- const asset = /^\/[^/]+\/[^/]+\/releases\/latest\/download\/([A-Za-z0-9._-]+\.(?:tgz|tar\.gz))$/.exec(approved.pathname)?.[1];
16
- if (asset === undefined)
17
- return null;
18
- for (const url of [approved, installed]) {
19
- if (url.protocol !== 'https:' || url.host !== 'github.com' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '')
20
- return null;
21
- }
22
- const match = /^\/([^/]+\/[^/]+)\/releases\/(?:latest\/download|download\/([^/]+))\/([^/]+)$/.exec(installed.pathname);
23
- if (match === null || match[1].toLowerCase() !== source.repo.toLowerCase())
24
- return null;
25
- const [, , tag, installedAsset] = match;
26
- if (installedAsset !== asset) {
27
- // A legacy filename can only add the version from its own stable release tag.
28
- const version = /^v?(\d+\.\d+\.\d+)$/.exec(tag ?? '')?.[1];
29
- if (version === undefined || installedAsset !== asset.replace(/\.(?:tgz|tar\.gz)$/, extension => `-${version}${extension}`))
30
- return null;
31
- }
32
- return { repo: source.repo, asset, manifest: source.subpath === null ? 'package.json' : `${source.subpath}/package.json` };
33
- }
34
- catch {
35
- return null;
36
- }
37
- }
4
+ export { catalogReleaseSourceOf } from './sources.js';
38
5
  export async function publishedReleaseUpdate(source, name) {
39
6
  try {
40
7
  const init = { headers: { 'user-agent': 'dsh-crate' }, signal: AbortSignal.timeout(10_000) };