dsh-crate 0.0.0-stage → 0.5.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.
Files changed (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +243 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +447 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +871 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1978 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +353 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +405 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +904 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
@@ -0,0 +1,462 @@
1
+ /**
2
+ * Update notes: what changed between an installed version and HEAD.
3
+ *
4
+ * Every byte of GitHub data comes from the catalog side's daily probe,
5
+ * published as the `dsh-plugin-updates` package (origin fallback
6
+ * `updates.json` beside `plugins.json`). The market asks GitHub for nothing:
7
+ * anonymous REST quota is shared per egress IP and already unreliable behind
8
+ * common proxies, and this data is wanted by thousands of markets but
9
+ * produced perfectly well once a day by one probe.
10
+ *
11
+ * What the catalog cannot know is where each user's installed version sits,
12
+ * so slicing the commit tail at that boundary happens here: the same sha the
13
+ * update check resolved (`current`) marks where "new" begins. A tail that
14
+ * does not contain it means the range is wider than the tail — those are
15
+ * labelled recent commits rather than pretending to be an exact interval.
16
+ * npm installs with neither notes nor commits fall back to npm publish times,
17
+ * and a plugin nothing answers for gets a neutral "no notes" — absence of
18
+ * release notes is the ordinary condition of small plugins, not a defect.
19
+ * A plugin installed from any other source the notes hold nothing for gets
20
+ * `source` instead: its history is where it came from, and the market says
21
+ * it has none on hand rather than that the plugin publishes none (#819).
22
+ */
23
+ import { absoluteTarballUrl, fileFromTarball } from './catalog-npm.js';
24
+ import { marketFetch } from './net.js';
25
+ import { activeRegion, routesFor } from './regions.js';
26
+ import { profileDir, readGitResolutionCommit, readInstalled, readInstalledRepoEvidence, readInstalledVersion, readLockCommits } from './profile.js';
27
+ import { githubRepoOfRemote, hostedRepoKey, isGitHostedSpec, lookupRepoFromUrl, parseHostShorthand, parseSourceUrl, repoOf, repoOfTarget } from './sources.js';
28
+ import { checkUpdates, compareVersions } from './updates.js';
29
+ import { loadRegistry } from './registry.js';
30
+ const UPDATES_PACKAGE = 'dsh-plugin-updates';
31
+ const UPDATES_FILE = 'package/updates.json';
32
+ /** The origin copy sits beside plugins.json on the catalog host. */
33
+ const ORIGIN_UPDATES = process.env.DSHM_UPDATES_ORIGIN ?? 'https://awesome-dsh-plugin.com/updates.json';
34
+ /** Notes are produced daily; re-checking hourly bounds staleness without churn. */
35
+ const NOTES_TTL_MS = 60 * 60 * 1000;
36
+ const TIMEOUT_MS = 15_000;
37
+ let notesCache = null;
38
+ /**
39
+ * The update-notes payload from whichever route the region serves.
40
+ *
41
+ * Same source order as the catalog itself — the npm package first where one
42
+ * exists (its mirror reach is the reason the package exists), then the
43
+ * origin. Version-keyed like the catalog too: an unchanged payload costs one
44
+ * packument read per TTL, not a tarball.
45
+ */
46
+ export async function loadUpdateNotes(force = false) {
47
+ if (!force && notesCache !== null && Date.now() - notesCache.at < NOTES_TTL_MS) {
48
+ return notesCache.data;
49
+ }
50
+ const routes = routesFor(activeRegion());
51
+ const attempt = async () => {
52
+ // The npm package, on the region's registry — mirrors rewrite dist.tarball
53
+ // to themselves, so following that field keeps the download local.
54
+ const metaRes = await marketFetch(`${routes.npmRegistry}/${encodeURIComponent(UPDATES_PACKAGE)}/latest`, {
55
+ signal: AbortSignal.timeout(TIMEOUT_MS),
56
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
57
+ });
58
+ if (!metaRes.ok)
59
+ throw new Error(`HTTP ${String(metaRes.status)} reading ${UPDATES_PACKAGE} metadata`);
60
+ const meta = await metaRes.json();
61
+ const tarball = typeof meta.dist?.tarball === 'string' ? meta.dist.tarball : null;
62
+ if (tarball === null)
63
+ throw new Error(`${UPDATES_PACKAGE} names no tarball`);
64
+ // A registry under a path prefix may answer with a relative tarball, the
65
+ // same case the catalog route resolves (#1117).
66
+ const tarRes = await marketFetch(absoluteTarballUrl(tarball, routes.npmRegistry), { signal: AbortSignal.timeout(TIMEOUT_MS) });
67
+ if (!tarRes.ok)
68
+ throw new Error(`HTTP ${String(tarRes.status)} reading ${UPDATES_PACKAGE} tarball`);
69
+ const bytes = fileFromTarball(Buffer.from(await tarRes.arrayBuffer()), UPDATES_FILE);
70
+ if (bytes === null)
71
+ throw new Error(`${UPDATES_PACKAGE} carries no ${UPDATES_FILE}`);
72
+ return JSON.parse(bytes.toString('utf8'));
73
+ };
74
+ const attemptOrigin = async () => {
75
+ const res = await marketFetch(ORIGIN_UPDATES, {
76
+ signal: AbortSignal.timeout(TIMEOUT_MS),
77
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
78
+ });
79
+ if (!res.ok)
80
+ throw new Error(`HTTP ${String(res.status)} reading ${ORIGIN_UPDATES}`);
81
+ return await res.json();
82
+ };
83
+ // Two independent sources, each tried twice — the same retry economics as
84
+ // the catalog loader, for the same transient-loss reasons.
85
+ let lastError = null;
86
+ for (const attemptFn of [attempt, attemptOrigin]) {
87
+ for (let i = 0; i < 2; i++) {
88
+ try {
89
+ const data = await attemptFn();
90
+ notesCache = { at: Date.now(), data };
91
+ return data;
92
+ }
93
+ catch (error) {
94
+ lastError = error;
95
+ }
96
+ }
97
+ }
98
+ throw lastError instanceof Error ? lastError : new Error('update notes unavailable');
99
+ }
100
+ /** Drop the cached payload (nothing currently invalidates it mid-process). */
101
+ export function invalidateUpdateNotes() {
102
+ notesCache = null;
103
+ }
104
+ /**
105
+ * Slice the commit tail at the installed sha.
106
+ *
107
+ * @returns the commits newer than `installed`, and whether the boundary was
108
+ * actually found — `found === false` means the range is wider than the tail
109
+ * (or history diverged), so callers must label the result "recent" rather
110
+ * than exact.
111
+ */
112
+ export function sliceCommitsAt(items, installed) {
113
+ if (installed === null)
114
+ return { items, found: false };
115
+ const out = [];
116
+ for (const commit of items) {
117
+ if (commit.sha === installed)
118
+ return { items: out, found: true };
119
+ out.push(commit);
120
+ }
121
+ return { items: out, found: false };
122
+ }
123
+ /**
124
+ * The version a release tag names, when it names one.
125
+ *
126
+ * Tags come as `v1.2.3`, `1.2.3`, `@scope/pkg@1.2.3` or `pkg-v1.2.3`; the
127
+ * FIRST semver-shaped run is the version in all of them. A tag that names no
128
+ * version (`nightly`) returns null, and callers must treat "unknown" as "do
129
+ * not judge" rather than "older".
130
+ */
131
+ export function releaseVersionOf(tag) {
132
+ if (tag === null)
133
+ return null;
134
+ const match = /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(tag);
135
+ return match?.[1] ?? null;
136
+ }
137
+ /** The repo url key an entry's update notes live under, or null. */
138
+ export function repoKeyOf(spec) {
139
+ const repo = githubIdentityOf(spec)?.split('#')[0] ?? null;
140
+ return repo === null ? null : `https://github.com/${repo}`;
141
+ }
142
+ /**
143
+ * `owner/repo[#path:/sub]`, lowercased, for a spec that installs from GitHub.
144
+ *
145
+ * `repoOfTarget` reads the `github:` and codeload spellings. pnpm writes a
146
+ * GitHub install back into the manifest as `git+https://github.com/…` (#803),
147
+ * so that spelling is read here too, subpath selector included (#819).
148
+ */
149
+ function githubIdentityOf(spec) {
150
+ const direct = repoOfTarget(spec);
151
+ if (direct !== null)
152
+ return direct;
153
+ const repo = githubRepoOfRemote(spec);
154
+ if (repo === null)
155
+ return null;
156
+ const hash = spec.indexOf('#');
157
+ const subpath = hash === -1
158
+ ? undefined
159
+ : /(?:^|&)path:\/*([^&]*?)\/*(?:&|$)/.exec(spec.slice(hash + 1))?.[1];
160
+ const root = repo.toLowerCase();
161
+ return subpath === undefined || subpath === '' ? root : `${root}#path:/${subpath.toLowerCase()}`;
162
+ }
163
+ /**
164
+ * The npm package an install spec resolves through the registry, or null when
165
+ * it names another source — a git remote, a tarball URL, a workspace link.
166
+ *
167
+ * Only these may be answered with npm publish times. Asking npm about any
168
+ * other install by its dependency name finds whatever unrelated package holds
169
+ * that name there (#819, the same fall-through #525 closed for updates).
170
+ */
171
+ function npmPackageOf(name, spec) {
172
+ const s = spec.trim();
173
+ const alias = /^npm:((?:@[^/@\s]+\/)?[^@\s]+)(?:@.*)?$/i.exec(s);
174
+ if (alias !== null)
175
+ return alias[1];
176
+ if (isGitHostedSpec(s))
177
+ return null;
178
+ if (/^catalog:/i.test(s))
179
+ return name;
180
+ if (/^[a-z][a-z0-9+.-]*:/i.test(s))
181
+ return null;
182
+ return name;
183
+ }
184
+ /**
185
+ * The web page of the repository a git spec installs from, or null.
186
+ *
187
+ * What the dialog can point at when the market cannot read a source's notes
188
+ * itself. The owner/repo casing is kept: not every host matches paths
189
+ * case-insensitively the way GitHub does.
190
+ */
191
+ export function sourceWebUrl(spec) {
192
+ if (!isGitHostedSpec(spec))
193
+ return null;
194
+ const shorthand = parseHostShorthand(spec);
195
+ if (shorthand !== null)
196
+ return `https://${shorthand.host}/${shorthand.path}`;
197
+ const github = repoOfTarget(spec);
198
+ if (github !== null)
199
+ return `https://github.com/${github.split('#')[0]}`;
200
+ let remote = spec.trim().replace(/^git\+/i, '');
201
+ const scp = /^git@([^/\s:]+):(.+)$/.exec(remote);
202
+ if (scp !== null)
203
+ remote = `https://${scp[1]}/${scp[2].replace(/^\/+/, '')}`;
204
+ // npm also accepts the scp colon inside an ssh URL (`ssh://git@host:org/repo`),
205
+ // which `URL` rejects as a non-numeric port.
206
+ const sshScp = /^ssh:\/\/(?:[^@/\s]+@)?([^/\s:]+):(?!\d+(?:\/|$))(.+)$/i.exec(remote);
207
+ if (sshScp !== null)
208
+ remote = `https://${sshScp[1]}/${sshScp[2].replace(/^\/+/, '')}`;
209
+ let url;
210
+ try {
211
+ url = new URL(remote.split('#')[0]);
212
+ }
213
+ catch {
214
+ return null;
215
+ }
216
+ const path = url.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
217
+ // A leading `~` is a user namespace on hosts such as sourcehut.
218
+ if (path === '' || !path.split('/').every((seg, i) => /^[A-Za-z0-9_.-]+$/.test(i === 0 ? seg.replace(/^~/, '') : seg) && seg !== '.' && seg !== '..'))
219
+ return null;
220
+ // An ssh/git port is the transport's, not the web server's.
221
+ if (/^https?:$/i.test(url.protocol))
222
+ return `${url.protocol}//${url.host}/${path}`;
223
+ if (/^(?:ssh|git):$/i.test(url.protocol))
224
+ return `https://${url.hostname}/${path}`;
225
+ return null;
226
+ }
227
+ /**
228
+ * Look an entry up by its catalog url.
229
+ *
230
+ * The catalog keys entries by the url as listed (author's casing preserved);
231
+ * the market resolves repos to lowercase (as every other consumer of
232
+ * `repoOfTarget` sees them). Match case-insensitively so the two sides never
233
+ * disagree over a capital letter.
234
+ */
235
+ export function entryForRepo(payload, key) {
236
+ const direct = payload.updates?.[key];
237
+ if (direct !== undefined)
238
+ return direct;
239
+ const lower = key.toLowerCase();
240
+ for (const [k, v] of Object.entries(payload.updates ?? {})) {
241
+ if (k.toLowerCase() === lower)
242
+ return v;
243
+ }
244
+ return undefined;
245
+ }
246
+ /**
247
+ * Publish times for an npm package's recent versions, newest first.
248
+ *
249
+ * The last resort before "no notes": authors who ship neither releases nor
250
+ * informative commits still usually tag versions, and "0.4.0 landed three
251
+ * days ago" beats nothing. Reads the full packument once and caches it —
252
+ * the doc is heavy, and a user may open the dialog twice.
253
+ */
254
+ const timesCache = new Map();
255
+ const TIMES_TTL_MS = 30 * 60 * 1000;
256
+ export async function npmPublishTimes(name) {
257
+ const hit = timesCache.get(name);
258
+ if (hit !== undefined && Date.now() - hit.at < TIMES_TTL_MS)
259
+ return hit.data;
260
+ const registry = routesFor(activeRegion()).npmRegistry;
261
+ const res = await marketFetch(`${registry}/${encodeURIComponent(name)}`, {
262
+ signal: AbortSignal.timeout(TIMEOUT_MS),
263
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crate' },
264
+ });
265
+ if (!res.ok)
266
+ throw new Error(`HTTP ${String(res.status)} reading ${name}`);
267
+ const doc = await res.json();
268
+ const time = doc.time ?? {};
269
+ const data = Object.entries(time)
270
+ .filter(([version]) => version !== 'created' && version !== 'modified')
271
+ .sort(([, a], [, b]) => Date.parse(b) - Date.parse(a))
272
+ .slice(0, 5)
273
+ .map(([version, date]) => ({ version, date }));
274
+ timesCache.set(name, { at: Date.now(), data });
275
+ return data;
276
+ }
277
+ /** A probe entry the dialog can actually render — an empty object is a miss. */
278
+ function usableNotes(entry) {
279
+ if (entry === undefined)
280
+ return false;
281
+ if (entry.release != null && (entry.release.body !== '' || entry.release.tag !== null))
282
+ return true;
283
+ return (entry.commits?.length ?? 0) > 0;
284
+ }
285
+ /**
286
+ * The catalog row for an npm install.
287
+ *
288
+ * The profile dependency key is the npm package name. The catalog `name`
289
+ * often is not: a monorepo entry is `repo#subpath`, and a scoped package's
290
+ * catalog name drops the scope (#746). `npm` is the identity the install
291
+ * used, so it wins; a bare `name` match remains for entries that publish
292
+ * under their catalog name. Several hits are disambiguated by the installed
293
+ * repository, and an ambiguous set is left unresolved (#598).
294
+ */
295
+ function catalogEntryForNpmInstall(plugins, name, evidence) {
296
+ const byNpm = plugins.filter(p => p.npm === name);
297
+ const candidates = byNpm.length > 0 ? byNpm : plugins.filter(p => p.name === name);
298
+ if (candidates.length <= 1)
299
+ return candidates[0];
300
+ const identities = evidence().identities;
301
+ const matches = candidates.filter(p => identities.some(id => repoOf(p.url)?.toLowerCase() === id.split('#')[0].toLowerCase()));
302
+ return matches.length === 1 ? matches[0] : undefined;
303
+ }
304
+ /**
305
+ * The catalog row for a `github:…#path:` install.
306
+ *
307
+ * `repoKeyOf` keeps only the repository root, while a monorepo entry's notes
308
+ * are stored under its `/tree/<ref>/<subpath>` url (#746). The spec's subpath
309
+ * selects the row. Two rows with one subpath are not guessed between.
310
+ */
311
+ function catalogEntryForGitSubpath(plugins, spec) {
312
+ const identity = githubIdentityOf(spec);
313
+ const marker = identity?.indexOf('#path:/') ?? -1;
314
+ if (identity === null || marker === -1)
315
+ return undefined;
316
+ const repo = identity.slice(0, marker);
317
+ const subpath = identity.slice(marker + '#path:/'.length);
318
+ const matches = plugins.filter(p => {
319
+ const source = parseSourceUrl(p.url);
320
+ return source?.subpath != null
321
+ && source.repo.toLowerCase() === repo
322
+ && source.subpath.toLowerCase() === subpath;
323
+ });
324
+ return matches.length === 1 ? matches[0] : undefined;
325
+ }
326
+ /**
327
+ * The catalog row for a git install from a host other than GitHub.
328
+ *
329
+ * Matched by repository, never by package name: the name is the one thing a
330
+ * git install shares with unrelated packages, and a same-named row from
331
+ * another repository would show that plugin's notes as this one's (#819).
332
+ */
333
+ function catalogEntryForGitSource(plugins, spec) {
334
+ const repo = hostedRepoKey(spec);
335
+ if (repo === null)
336
+ return undefined;
337
+ const matches = plugins.filter(p => hostedRepoKey(p.url) === repo);
338
+ return matches.length === 1 ? matches[0] : undefined;
339
+ }
340
+ /**
341
+ * Resolve the notes for one installed plugin, or `{ kind: 'none' }`.
342
+ *
343
+ * Never throws: every failure along the way degrades to the next tier, the
344
+ * same contract the issue promised — a dialog that cannot load its data shows
345
+ * a neutral statement, not an error.
346
+ */
347
+ export async function updateNotesFor(profile, explicitDir, name) {
348
+ const activeProfileDir = profileDir(profile, explicitDir);
349
+ const spec = readInstalled(profile, activeProfileDir)[name];
350
+ if (spec === undefined || spec.startsWith('link:') || spec.startsWith('file:')) {
351
+ return { kind: 'none' };
352
+ }
353
+ const npmName = npmPackageOf(name, spec);
354
+ // A Release-asset spec carries the repo in the URL itself. An npm
355
+ // version range carries nothing, so `specKey` stays null and the catalog
356
+ // lookup below is what finds the repository.
357
+ const specKey = repoKeyOf(spec) ?? lookupRepoFromUrl(spec);
358
+ // The market holds no notes for this install, but its history is still
359
+ // readable where it came from: say which, and point there.
360
+ //
361
+ // Notes come from the catalog's own release feed, which is built from
362
+ // GitHub, so a gitee or self-hosted git install has no feed to find:
363
+ // "the market has not collected this one yet" would promise something that
364
+ // cannot happen, and the reader waits for it (#819). Those say the source
365
+ // cannot be read instead. The url is the same either way — the repository
366
+ // is where the answer actually is.
367
+ const unreadableSource = githubIdentityOf(spec) === null && isGitHostedSpec(spec);
368
+ const fromSource = (reason) => ({
369
+ kind: 'source',
370
+ reason: unreadableSource ? 'unreadable' : reason,
371
+ sourceUrl: sourceWebUrl(spec) ?? specKey,
372
+ });
373
+ try {
374
+ const payload = await loadUpdateNotes();
375
+ let key = specKey;
376
+ let entry = key === null ? undefined : entryForRepo(payload, key);
377
+ // The catalog is how an npm install, a git install off GitHub, or a
378
+ // `#path:` install whose notes live under a /tree/ url finds a key the
379
+ // spec itself does not name. A root github spec already is that key.
380
+ // Loading the catalog on a root miss would wait out its timeout to
381
+ // answer "no notes".
382
+ const offGithub = specKey === null && npmName === null && isGitHostedSpec(spec);
383
+ const needsCatalog = (specKey === null && (npmName !== null || offGithub))
384
+ || (githubIdentityOf(spec)?.includes('#path:/') ?? false);
385
+ if (!usableNotes(entry) && needsCatalog) {
386
+ try {
387
+ const registry = await loadRegistry();
388
+ const plugin = specKey !== null
389
+ ? catalogEntryForGitSubpath(registry.plugins, spec)
390
+ : npmName !== null
391
+ ? catalogEntryForNpmInstall(registry.plugins, npmName, () => readInstalledRepoEvidence(profile, name, spec, explicitDir))
392
+ : catalogEntryForGitSource(registry.plugins, spec);
393
+ if (plugin !== undefined) {
394
+ const catalogEntry = entryForRepo(payload, plugin.url);
395
+ // An empty row does not become the key. Publish times for an npm
396
+ // install follow from `specKey` staying null, and a subpath install
397
+ // keeps the root key so a sibling's notes are not borrowed.
398
+ if (usableNotes(catalogEntry)) {
399
+ key = plugin.url;
400
+ entry = catalogEntry;
401
+ }
402
+ }
403
+ }
404
+ catch {
405
+ // Catalog unavailable; the tiers below still answer.
406
+ }
407
+ }
408
+ // Both tiers below need the installed sha for github-kind installs.
409
+ // For Release asset URLs and catalog lookups, checkUpdates doesn't
410
+ // recognize the spec, so we read the lockfile directly using the repo key.
411
+ // `repoOf` drops a `/tree/<ref>/<subpath>` suffix; slicing the url at `#`
412
+ // would look the commit up under `owner/repo/tree/...` and miss it.
413
+ // A `git+https://github.com/…` install pnpm cloned rather than downloaded
414
+ // is a `type: git` lock entry, not an archive URL.
415
+ let current = null;
416
+ if (key !== null && key.startsWith('https://github.com/')) {
417
+ const repo = (repoOf(key) ?? key.slice('https://github.com/'.length).split('#')[0]).toLowerCase();
418
+ current = readLockCommits(profile, activeProfileDir).get(`github.com/${repo}`)
419
+ ?? readGitResolutionCommit(profile, spec, explicitDir);
420
+ }
421
+ else {
422
+ const statuses = await checkUpdates(profile, false, explicitDir).catch(() => null);
423
+ current = statuses?.[name]?.current ?? null;
424
+ }
425
+ if (entry?.release !== undefined && entry.release !== null && (entry.release.body !== '' || entry.release.tag !== null)) {
426
+ // The release feed is a DAILY snapshot while the update target is read
427
+ // live from npm, so the snapshot's newest release is often the version
428
+ // already installed (or older). Showing it next to "1.66.39 → 1.66.40"
429
+ // describes a change the user already has (#925). When the release
430
+ // names a version no newer than the installed one AND a better tier
431
+ // exists, take the better tier: the commit tail is sliced at this
432
+ // install's sha, and npm publish times are newer than the install by
433
+ // construction. With nothing better, the stale release still beats an
434
+ // empty dialog.
435
+ const installed = readInstalledVersion(profile, name, activeProfileDir);
436
+ const released = releaseVersionOf(entry.release.tag);
437
+ const behind = installed !== null && released !== null
438
+ && (compareVersions(released, installed) ?? 0) <= 0;
439
+ const hasCommits = (entry.commits?.length ?? 0) > 0;
440
+ if (!(behind && (hasCommits || (specKey === null && npmName !== null)))) {
441
+ return { kind: 'release', release: entry.release };
442
+ }
443
+ }
444
+ if (entry?.commits !== undefined && entry.commits.length > 0) {
445
+ return { kind: 'commits', commits: sliceCommitsAt(entry.commits, current) };
446
+ }
447
+ if (specKey === null && npmName !== null) {
448
+ // An npm install whose catalog row is missing or its probe has no
449
+ // notes: publish times remain.
450
+ return { kind: 'npm', npmTimes: await npmPublishTimes(npmName) };
451
+ }
452
+ // Every other source has its history where it came from. Only a probe
453
+ // that ran and found nothing — releases 404 AND an empty log — means the
454
+ // plugin really publishes nothing.
455
+ if (entry === undefined)
456
+ return fromSource('missing');
457
+ return { kind: 'none' };
458
+ }
459
+ catch {
460
+ return npmName === null ? fromSource('unavailable') : { kind: 'none' };
461
+ }
462
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The market's release channels: which build of ITSELF it offers.
3
+ *
4
+ * Only the market follows this. Other plugins are never pulled from a
5
+ * prerelease on the strength of a setting the user made about the market —
6
+ * opting into early builds is volunteering to try THIS plugin early, not to
7
+ * be handed every other author's unreleased work.
8
+ *
9
+ * The model lives in its own module because it is the part with rules
10
+ * rather than plumbing: three channels, one of them hidden, a mapping to
11
+ * npm dist-tags, and a resolution order that has already been got wrong
12
+ * once (see `resolveChannel`).
13
+ */
14
+ /**
15
+ * The npm dist-tag each channel installs from.
16
+ *
17
+ * `dev` is published straight from a branch with no git tag behind it, so a
18
+ * version carries a timestamp and a short SHA (`1.15.0-dev.20260818-3f1432e`)
19
+ * and is never reused. That is what makes a dev build disposable: nothing in
20
+ * the repository's history refers to it.
21
+ */
22
+ export const DIST_TAG = {
23
+ stable: 'latest',
24
+ beta: 'beta',
25
+ dev: 'dev',
26
+ };
27
+ /**
28
+ * Every channel a user may pick. All three, always.
29
+ *
30
+ * `dev` was behind a developer-mode switch for one version, on the reasoning
31
+ * that a build published straight off a branch should not sit beside
32
+ * "stable" looking like a third degree of caution. The switch cost more than
33
+ * it bought: a stored mode, a route to change it, a rule for what happens to
34
+ * a dev choice when it is turned off, and a control whose own purpose needed
35
+ * explaining. A plainly labelled option a user can read is simpler than a
36
+ * hidden one plus the machinery that hides it — the label does the work the
37
+ * gate was doing.
38
+ */
39
+ export const CHANNELS = ['stable', 'beta', 'dev'];
40
+ /** Narrow an untrusted value to a Channel, or null. */
41
+ export function asChannel(value) {
42
+ return value === 'stable' || value === 'beta' || value === 'dev' ? value : null;
43
+ }
44
+ /**
45
+ * Which channel applies right now.
46
+ *
47
+ * A choice on record always wins — including "stable" while a prerelease is
48
+ * running, which is the only way back off a channel. Only the ABSENCE of a
49
+ * choice is derived, and then from what is actually running: installing
50
+ * `dsh-crate@beta` by hand IS the subscription, and treating that as
51
+ * "stable" costs updates rather than just clarity — on the stable channel
52
+ * `latest` (1.13.1) is not newer than an installed 1.14.0-beta.1, so the
53
+ * market answers "up to date" and the next beta is never offered.
54
+ *
55
+ * Which makes `undefined` load-bearing: it has to survive both the settings
56
+ * schema (no `.default`) and state.json (field omitted) or "never chose"
57
+ * silently becomes "chose stable".
58
+ *
59
+ */
60
+ export function resolveChannel(setting, version) {
61
+ if (setting !== undefined)
62
+ return setting;
63
+ return version.includes('-') ? 'beta' : 'stable';
64
+ }