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,308 @@
1
+ /**
2
+ * Registry access: crate 的目录(dsh-crate.json)每次请求都重新拉取。
3
+ * 这里只负责抓取、重试、校验与 304 复用;字段映射见 src/crate-catalog.ts。
4
+ */
5
+ import { BODY_STALL_TIMEOUT_MS, HEADERS_TIMEOUT_MS, readBodyWhileProgressing } from './body-progress.js';
6
+ import { logEvent } from './log.js';
7
+ import { configuredProxy, marketFetch } from './net.js';
8
+ import { catalogFromPackage } from './catalog-npm.js';
9
+ import { activeRegion, catalogSourcesFor, routesFor } from './regions.js';
10
+ import { asCrateRegistry, isCrateCatalog } from './crate-catalog.js';
11
+ import { NPM_NAME_RE } from './sources.js';
12
+ /**
13
+ * Category ids for one catalog entry, de-duplicated in declaration order.
14
+ *
15
+ * Catalog JSON is an external input, so malformed array members are omitted
16
+ * here and an entry with no usable category is rejected by `asRegistry`.
17
+ */
18
+ export function pluginCategories(plugin) {
19
+ const values = Array.isArray(plugin.category) ? plugin.category : [plugin.category];
20
+ const categories = [];
21
+ const seen = new Set();
22
+ for (const value of values) {
23
+ if (typeof value !== 'string' || value === '' || seen.has(value))
24
+ continue;
25
+ seen.add(value);
26
+ categories.push(value);
27
+ }
28
+ return categories;
29
+ }
30
+ /**
31
+ * Former npm names for one catalog entry, normalized (#1012).
32
+ *
33
+ * Catalog JSON is external input, so a malformed declaration is dropped
34
+ * rather than trusted: only syntactically valid npm names survive, an entry
35
+ * may not list itself (its own `npm` or `name`), and duplicates collapse in
36
+ * declaration order. Cross-entry rules — a former name that is still live
37
+ * elsewhere, or two entries claiming one former name — cannot be judged per
38
+ * entry; the validator enforces them for the catalog, and
39
+ * `findCatalogRename` fails closed on ambiguity at runtime.
40
+ */
41
+ export function pluginPreviousNpm(plugin) {
42
+ const declared = plugin.previousNpm;
43
+ const values = Array.isArray(declared) ? declared : declared === undefined || declared === null ? [] : [declared];
44
+ const own = new Set([plugin.name.toLowerCase()]);
45
+ if (typeof plugin.npm === 'string' && plugin.npm !== '')
46
+ own.add(plugin.npm.toLowerCase());
47
+ const names = [];
48
+ const seen = new Set();
49
+ for (const value of values) {
50
+ if (typeof value !== 'string' || value === '' || !NPM_NAME_RE.test(value))
51
+ continue;
52
+ const key = value.toLowerCase();
53
+ if (own.has(key) || seen.has(key))
54
+ continue;
55
+ seen.add(key);
56
+ names.push(value);
57
+ }
58
+ return names;
59
+ }
60
+ /**
61
+ * Where the curated list comes from now lives in the region routing table
62
+ * (src/regions.ts), because it is one of several addresses that move
63
+ * together when a user changes download region.
64
+ *
65
+ * `DSHM_REGISTRY_URL` keeps its meaning there, unchanged: overridable
66
+ * through the process environment ONLY — the layer-3 e2e points it at a
67
+ * local fixture catalog so the install route can be driven end to end
68
+ * without publishing anything.
69
+ *
70
+ * This does not weaken the install route's registry check. That check exists
71
+ * to stop a malicious PAGE from POSTing an arbitrary source at the local
72
+ * server; a page cannot set environment variables, and anyone who can set
73
+ * this process's environment already controls the process. What the override
74
+ * changes is WHICH list is curated, never WHETHER the check runs.
75
+ */
76
+ /**
77
+ * The catalog we were last served, with the validator identifying it.
78
+ *
79
+ * This is NOT the cache that was removed, and the difference is the whole
80
+ * point. That cache SKIPPED the request for an hour and answered from
81
+ * memory — it asserted freshness without ever asking. This asks the origin
82
+ * every single time; the validator only lets the origin answer "still the
83
+ * same" (304) instead of resending a megabyte. Freshness is verified on
84
+ * every call either way, so `data` below is only ever returned when the
85
+ * server has just confirmed it is current.
86
+ *
87
+ * In memory rather than on disk: a restart is rare enough that paying one
88
+ * full download for it costs nothing, and a file would be one more thing
89
+ * that can be found on a machine and mistaken for the catalog itself.
90
+ *
91
+ * Measured against the live origin (GitHub Pages behind Fastly, which
92
+ * serves both `etag` and `last-modified`): 295 KB and 1.3s unconditional,
93
+ * 0 bytes and 0.5s for a 304. The reporter whose fetch took 9.9s was
94
+ * downloading the full 1.07 MB every time they opened the market.
95
+ */
96
+ let served = null;
97
+ /** Identity of a catalog source, for scoping the validator to its origin. */
98
+ function sourceKey(source) {
99
+ return source.kind === 'npm' ? `npm:${source.registry}/${source.pkg}` : `url:${source.url}`;
100
+ }
101
+ /**
102
+ * 目录载荷分派:按结构选适配器,而不是按地区或地址。
103
+ *
104
+ * crate 的载荷带 `entries`,旧的目录带 `plugins`;两套结构各自校验,夹具
105
+ * 与真实数据都不会误入对方的分支。
106
+ *
107
+ * @param value - 已经 `JSON.parse` 过的目录载荷。
108
+ * @throws 两个适配器都可能因为数据不可用而抛出,异常留给调用方重试。
109
+ */
110
+ function parseCatalog(value) {
111
+ return isCrateCatalog(value) ? asCrateRegistry(value) : asRegistry(value);
112
+ }
113
+ /** A parsed catalog, or a thrown explanation of why it is not one. */
114
+ function asRegistry(value) {
115
+ const data = value;
116
+ if (!Array.isArray(data.plugins) || data.plugins.length === 0)
117
+ throw new Error('the catalog came back empty');
118
+ const plugins = data.plugins.map((plugin, index) => {
119
+ const category = pluginCategories(plugin);
120
+ if (category.length === 0)
121
+ throw new Error(`catalog plugin ${String(index)} carries no usable category`);
122
+ const previousNpm = pluginPreviousNpm(plugin);
123
+ // An entry with nothing usable to declare looks exactly like one that
124
+ // declared nothing, so the field stays absent rather than becoming [].
125
+ if (previousNpm.length === 0) {
126
+ const { previousNpm: _declared, ...rest } = plugin;
127
+ return { ...rest, category };
128
+ }
129
+ return { ...plugin, category, previousNpm };
130
+ });
131
+ return { ...data, plugins };
132
+ }
133
+ /**
134
+ * Drop what we remember, so the next call is unconditional.
135
+ *
136
+ * Exists for tests: the memo is module state, and a spec that asserted a
137
+ * 304 would otherwise leak a validator into the next one.
138
+ */
139
+ export function forgetCatalog() {
140
+ served = null;
141
+ }
142
+ /**
143
+ * The catalog, revalidated every time it is asked for.
144
+ *
145
+ * There used to be three answers here — live, a one-hour in-memory cache,
146
+ * and a snapshot bundled into the npm package — and only the first was
147
+ * correct. The other two were indistinguishable from it on screen, so a
148
+ * machine that could not reach the registry browsed the publish-time file
149
+ * (839 entries against 1367 live, and frozen forever for anyone on an older
150
+ * release), while a machine that COULD reach it still saw an hour-old
151
+ * listing of a catalog that grows by ~250 entries a day.
152
+ *
153
+ * For a catalog, stale is not a degraded answer, it is a wrong one: a plugin
154
+ * published this morning reads as "does not exist". So there is one source
155
+ * now, and a failure is a failure — the caller reports it and offers a
156
+ * retry, which is a state the user can act on. In particular a network
157
+ * failure is NEVER answered from `served`: an origin that cannot be reached
158
+ * has not confirmed anything, and quietly handing back the last catalog
159
+ * would rebuild exactly the fallback this replaced.
160
+ * @throws when the catalog cannot be fetched or does not look like one.
161
+ */
162
+ export async function loadRegistry(region = activeRegion()) {
163
+ const started = Date.now();
164
+ let last;
165
+ let attempts = 0;
166
+ /**
167
+ * Every source that failed, in order (#750).
168
+ *
169
+ * Only the LAST failure used to be reported, so a primary source that was
170
+ * DNS-blocked, refused, or answering 404 disappeared from the message as
171
+ * soon as the fallback failed too: the user was told about the mirror they
172
+ * never chose (and can do nothing about) and not about the one that broke
173
+ * first. Which source said what IS the diagnosis here — the two fail for
174
+ * different reasons, and usually only one of them is worth acting on.
175
+ */
176
+ const failures = [];
177
+ // Sources in order, each a fallback for the one before it. The catalog is
178
+ // the FIRST request the market makes, so a mirror that has gone down must
179
+ // mean a slow market rather than an empty one — the list ends at the
180
+ // address that has always worked.
181
+ //
182
+ // The list runs one entry past the region's own sources on purpose (#891):
183
+ // the region probe measures the npm registry, so it cannot see a network
184
+ // where npm is fast and the catalog's host is blocked — and the region is
185
+ // decided once and persisted. The catalog's published package, on the
186
+ // registry the probe just proved reachable, is the repair that needs
187
+ // neither the probe nor the decision to change.
188
+ const ownSources = routesFor(region).catalog.length;
189
+ const catalogSources = catalogSourcesFor(region);
190
+ for (const [sourceIndex, source] of catalogSources.entries()) {
191
+ const key = sourceKey(source);
192
+ const servedBy = (data) => {
193
+ if (sourceIndex >= ownSources) {
194
+ logEvent('warn', 'registry', `catalog: the ${region} sources did not answer; read the catalog package from ${key} instead (#891)`);
195
+ }
196
+ return data;
197
+ };
198
+ // Two attempts each. A catalog fetch crossing a long, lossy path fails
199
+ // transiently often enough that one retry is worth more than the second
200
+ // or two it costs — and with nothing behind this call any more, a
201
+ // transient failure is a market with no plugins in it.
202
+ for (let attempt = 0; attempt < 2; attempt++) {
203
+ attempts += 1;
204
+ try {
205
+ // A validator only ever goes back to the source that issued it.
206
+ // Carried across a region switch it could earn a "not modified" from
207
+ // an origin whose body we have never seen.
208
+ const reusable = served?.key === key ? served : null;
209
+ if (source.kind === 'npm') {
210
+ const { version, data } = await catalogFromPackage(source.registry, source.pkg, reusable?.version ?? undefined);
211
+ // `data === null` means the published version is the one in hand.
212
+ if (data === null && reusable !== null)
213
+ return servedBy(reusable.data);
214
+ if (data === null)
215
+ throw new Error('the catalog package reported no change with nothing to reuse');
216
+ const parsed = asRegistry(data);
217
+ served = { key, etag: null, modified: null, version, data: parsed };
218
+ return servedBy(parsed);
219
+ }
220
+ // ETag first: it is exact, while a date has one-second resolution and
221
+ // a catalog republished twice within the same second would validate
222
+ // as unchanged. Only one is sent — an origin given both must satisfy
223
+ // both, which turns a weak ETag match into an unnecessary 200.
224
+ const headers = {};
225
+ if (reusable?.etag != null)
226
+ headers['if-none-match'] = reusable.etag;
227
+ else if (reusable?.modified != null)
228
+ headers['if-modified-since'] = reusable.modified;
229
+ // Headers and body run on different clocks. The fixed budget covers
230
+ // only the wait for the response to START; the body itself is read
231
+ // under a stall watchdog, because the catalog takes longer than any
232
+ // honest fixed budget on a slow link, and "bytes still moving" is the
233
+ // one signal that separates slow from stuck.
234
+ const controller = new AbortController();
235
+ const headersDeadline = setTimeout(() => {
236
+ controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
237
+ }, HEADERS_TIMEOUT_MS);
238
+ let res;
239
+ try {
240
+ res = await marketFetch(source.url, { signal: controller.signal, headers });
241
+ }
242
+ finally {
243
+ clearTimeout(headersDeadline);
244
+ }
245
+ if (res.status === 304) {
246
+ // Only reachable when we sent a validator, so `reusable` is present.
247
+ // Guarded anyway: answering a 304 with nothing to reuse would
248
+ // otherwise surface as a confusing parse error on an empty body.
249
+ if (reusable === null)
250
+ throw new Error('the catalog answered "not modified" with nothing to revalidate');
251
+ return servedBy(reusable.data);
252
+ }
253
+ if (!res.ok)
254
+ throw new Error(`HTTP ${String(res.status)}`);
255
+ const data = parseCatalog(JSON.parse(new TextDecoder().decode(await readBodyWhileProgressing(res, BODY_STALL_TIMEOUT_MS))));
256
+ served = {
257
+ key, etag: res.headers.get('etag'), modified: res.headers.get('last-modified'), version: null, data,
258
+ };
259
+ return servedBy(data);
260
+ }
261
+ catch (error) {
262
+ last = error;
263
+ failures.push({
264
+ source: sourceKey(source),
265
+ reason: error instanceof Error ? error.message : String(error),
266
+ });
267
+ }
268
+ }
269
+ // Every source here is a fallback for the one before it, so this failure
270
+ // may never reach the screen: the market reads the catalog from the next
271
+ // source and looks fine, while a mirror this person configured and cannot
272
+ // see failing stays broken (#1117). One line per source per load — the
273
+ // full list is still in the thrown message when everything fails.
274
+ const ownFailure = failures.findLast(failure => failure.source === key);
275
+ if (ownFailure !== undefined && sourceIndex + 1 < catalogSources.length) {
276
+ logEvent('warn', 'registry', `catalog: ${key} failed, reading from a later source — ${ownFailure.reason.slice(0, 200)}`);
277
+ }
278
+ }
279
+ throw new Error(describeFetchFailure(last, Date.now() - started, attempts, failures));
280
+ }
281
+ /**
282
+ * A catalog failure with the facts needed to classify it, in the message
283
+ * itself.
284
+ *
285
+ * The market shows this string and the log export carries it, so it is the
286
+ * whole of what a bug report will contain. "The operation was aborted due to
287
+ * timeout" alone cannot distinguish a slow link from a blocked one from a
288
+ * proxy this process cannot use — and Node's `fetch` ignores HTTP_PROXY
289
+ * entirely (measured on Node 25), so a machine whose only route out is a
290
+ * proxy fails here every time while every other tool on it works.
291
+ */
292
+ export function describeFetchFailure(error, elapsedMs, attempts = 2, failures = []) {
293
+ const reason = error instanceof Error ? error.message : String(error);
294
+ const proxy = configuredProxy();
295
+ const parts = [`${reason} (${String(Math.round(elapsedMs / 1000))}s, ${String(attempts)} attempts)`];
296
+ if (proxy !== null) {
297
+ parts.push(`tried through the configured proxy ${proxy.replace(/\/\/[^@]*@/u, '//***@')}`);
298
+ }
299
+ // The sources that failed BEFORE the last one, so the primary's own reason
300
+ // survives into the message instead of being replaced by the fallback's
301
+ // (#750). One entry per source, reasons clipped: this lands in a banner, and
302
+ // the first reason is usually the only actionable one.
303
+ const earlier = failures.slice(0, -1);
304
+ if (earlier.length > 0) {
305
+ parts.push(`earlier: ${earlier.map(entry => `${entry.source} — ${entry.reason.slice(0, 160)}`).join(' · ')}`);
306
+ }
307
+ return parts.join(' · ');
308
+ }
@@ -0,0 +1,115 @@
1
+ function semver(value) {
2
+ if (typeof value !== 'string')
3
+ return null;
4
+ const matched = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(value);
5
+ if (!matched)
6
+ return null;
7
+ const prerelease = matched[4]?.split('.') ?? [];
8
+ if (prerelease.some(part => /^\d+$/.test(part) && part.length > 1 && part.startsWith('0')))
9
+ return null;
10
+ return { core: [BigInt(matched[1]), BigInt(matched[2]), BigInt(matched[3])], prerelease };
11
+ }
12
+ /** Accept stable SemVer, including build metadata, at both API boundaries. */
13
+ export function isStableReleaseVersion(value) {
14
+ const parsed = semver(value);
15
+ return parsed !== null && parsed.prerelease.length === 0;
16
+ }
17
+ function compare(a, b) {
18
+ for (let i = 0; i < 3; i++) {
19
+ if (a.core[i] !== b.core[i])
20
+ return a.core[i] > b.core[i] ? 1 : -1;
21
+ }
22
+ if (a.prerelease.length === 0 || b.prerelease.length === 0)
23
+ return Math.sign(b.prerelease.length - a.prerelease.length);
24
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
25
+ const x = a.prerelease[i], y = b.prerelease[i];
26
+ if (x === undefined)
27
+ return -1;
28
+ if (y === undefined)
29
+ return 1;
30
+ if (x === y)
31
+ continue;
32
+ const xn = /^\d+$/.test(x), yn = /^\d+$/.test(y);
33
+ if (xn && yn)
34
+ return BigInt(x) > BigInt(y) ? 1 : -1;
35
+ if (xn !== yn)
36
+ return xn ? -1 : 1;
37
+ return x > y ? 1 : -1;
38
+ }
39
+ return 0;
40
+ }
41
+ export function strictPublishTime(value) {
42
+ if (typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/.test(value))
43
+ return null;
44
+ const timestamp = Date.parse(value);
45
+ if (!Number.isFinite(timestamp))
46
+ return null;
47
+ return new Date(timestamp).toISOString().slice(0, 19) === value.slice(0, 19) ? timestamp : null;
48
+ }
49
+ export function selectMatureUpdate(packument, installed, now, policy) {
50
+ const latest = typeof packument?.['dist-tags']?.latest === 'string' ? packument['dist-tags'].latest : null;
51
+ const empty = (reason) => ({ candidate: null, latest, held: null, reason, nextMaturityAt: null, latestMaturityAt: null });
52
+ const top = semver(latest);
53
+ if (!top || top.prerelease.length || !packument.versions || !packument.time ||
54
+ typeof packument.versions !== 'object' || typeof packument.time !== 'object' ||
55
+ !Object.hasOwn(packument.versions, latest) ||
56
+ (policy.latestFromEndpoint != null && policy.latestFromEndpoint !== latest))
57
+ return empty('inconsistent');
58
+ const ceiling = policy.maxVersion === undefined ? top : semver(policy.maxVersion);
59
+ if (!ceiling || ceiling.prerelease.length ||
60
+ (policy.maxVersion !== undefined && !Object.hasOwn(packument.versions, policy.maxVersion)))
61
+ return empty('inconsistent');
62
+ const current = semver(installed);
63
+ if (!current || current.prerelease.length)
64
+ return empty('invalid-installed');
65
+ const ageMs = policy.minimumReleaseAgeMs;
66
+ if (!Number.isSafeInteger(ageMs) || ageMs < 0 || !Number.isFinite(now))
67
+ return empty('policy-unknown');
68
+ let candidate = null;
69
+ let candidateSemver = null;
70
+ let nextMaturityAt = null;
71
+ for (const version of Object.keys(packument.versions)) {
72
+ const parsed = semver(version);
73
+ if (!parsed || parsed.prerelease.length || compare(parsed, current) <= 0 || compare(parsed, top) > 0 || compare(parsed, ceiling) > 0)
74
+ continue;
75
+ const published = strictPublishTime(packument.time[version]);
76
+ const exempt = policy.exemptPackage === true || policy.exemptVersions?.has(version) === true;
77
+ // A declared exemption is not evidence for a fabricated or absent timestamp.
78
+ if (published === null || published > now || (!exempt && published > now - ageMs)) {
79
+ if (published !== null && published <= now && Number.isFinite(published + ageMs)) {
80
+ const at = published + ageMs;
81
+ if (nextMaturityAt === null || at < nextMaturityAt)
82
+ nextMaturityAt = at;
83
+ }
84
+ continue;
85
+ }
86
+ if (candidateSemver === null || compare(parsed, candidateSemver) > 0) {
87
+ candidate = version;
88
+ candidateSemver = parsed;
89
+ }
90
+ }
91
+ const latestPublished = strictPublishTime(packument.time[latest]);
92
+ const latestExempt = policy.exemptPackage === true || policy.exemptVersions?.has(latest) === true;
93
+ const latestMature = latestPublished !== null && latestPublished <= now &&
94
+ (latestExempt || latestPublished <= now - ageMs);
95
+ return {
96
+ candidate, latest, held: latestMature ? null : latest,
97
+ reason: candidate ? 'eligible' : latestMature ? 'current' : latestPublished === null ? 'unknown-age' : 'held',
98
+ nextMaturityAt,
99
+ latestMaturityAt: latestPublished === null || latestExempt ? null : latestPublished + ageMs,
100
+ };
101
+ }
102
+ export function versionMaturity(packument, version, now, policy) {
103
+ const ageMs = policy.minimumReleaseAgeMs;
104
+ const policyKnown = Number.isSafeInteger(ageMs) && ageMs >= 0 && Number.isFinite(now);
105
+ const times = typeof packument?.time === 'object' && packument.time !== null ? packument.time : {};
106
+ const published = strictPublishTime(times[version]);
107
+ const exempt = policy.exemptPackage === true || policy.exemptVersions?.has(version) === true;
108
+ if (published === null)
109
+ return { publishedAt: null, matureAt: null, exempt, mature: false, policyKnown };
110
+ if (!policyKnown)
111
+ return { publishedAt: published, matureAt: null, exempt, mature: false, policyKnown };
112
+ const matureAt = exempt ? published : published + ageMs;
113
+ const mature = published <= now && (exempt || published <= now - ageMs);
114
+ return { publishedAt: published, matureAt: Number.isFinite(matureAt) ? matureAt : null, exempt, mature, policyKnown };
115
+ }
@@ -0,0 +1,70 @@
1
+ /** Published GitHub archives stay archive installs; never infer an npm identity. */
2
+ import { marketFetch } from './net.js';
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() || match[2] !== asset)
24
+ return null;
25
+ return { repo: source.repo, asset, manifest: source.subpath === null ? 'package.json' : `${source.subpath}/package.json` };
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ export async function publishedReleaseUpdate(source, name) {
32
+ try {
33
+ const init = { headers: { 'user-agent': 'dsh-crate' }, signal: AbortSignal.timeout(10_000) };
34
+ // The ordinary redirect has no REST API quota and cannot advertise an
35
+ // unpublished main-branch version. Keep the published tag in the add target.
36
+ const latest = await marketFetch(`https://github.com/${source.repo}/releases/latest`, { ...init, method: 'HEAD', redirect: 'manual' });
37
+ if (latest.status !== 302 && latest.status !== 301)
38
+ return null;
39
+ const location = new URL(latest.headers.get('location') ?? '', `https://github.com/${source.repo}/releases/latest`);
40
+ const prefix = `/${source.repo}/releases/tag/`;
41
+ if (location.origin !== 'https://github.com' || location.username !== '' || location.password !== '' || location.search !== '' || location.hash !== '' || !location.pathname.toLowerCase().startsWith(prefix.toLowerCase()))
42
+ return null;
43
+ const tag = location.pathname.slice(prefix.length);
44
+ if (!/^v?\d+\.\d+\.\d+$/.test(tag))
45
+ return null;
46
+ const version = tag.replace(/^v/, '');
47
+ const manifestUrl = `https://raw.githubusercontent.com/${source.repo}/${tag}/${source.manifest}`;
48
+ for (const route of githubRoutesFor('raw', activeRegion())) {
49
+ try {
50
+ const response = await marketFetch(throughProxy(route, manifestUrl), { headers: init.headers, signal: AbortSignal.timeout(10_000) });
51
+ if (!response.ok)
52
+ continue;
53
+ const manifest = await response.json();
54
+ if (manifest.name !== name || manifest.version !== version)
55
+ return null;
56
+ rememberGithubRoute('raw', route);
57
+ const target = `https://github.com/${source.repo}/releases/download/${tag}/${source.asset}`;
58
+ const archive = await marketFetch(target, { headers: init.headers, signal: AbortSignal.timeout(10_000), method: 'HEAD', redirect: 'manual' });
59
+ if (archive.status !== 200 && archive.status !== 302 && archive.status !== 301)
60
+ return null;
61
+ return { version, target };
62
+ }
63
+ catch { /* Another configured raw route may answer. */ }
64
+ }
65
+ return null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }