dsh-ntr 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/update.js ADDED
@@ -0,0 +1,696 @@
1
+ /**
2
+ * Host-side built-in update for dsh-ntr.
3
+ *
4
+ * The plugin NEVER downloads a package, swaps files, or restarts itself. The
5
+ * harness plugin manager owns installation (profile bookkeeping, npm, the
6
+ * restart contract); this module only asks it what is installed, asks an npm
7
+ * registry what is published, and delegates the install back to the manager.
8
+ * Every method therefore reports a {@link PluginUpdateState} instead of
9
+ * throwing; version syntax is validated at the RPC boundary (`impl.ts`).
10
+ */
11
+ /** The npm package this plugin is published as, and the bundle name to look for. */
12
+ export const UPDATE_PACKAGE = 'dsh-ntr';
13
+ /** One npm registry request must answer within this window before the next is tried. */
14
+ const REGISTRY_TIMEOUT_MS = 8_000;
15
+ /** A successful packument answer is reused for this long (per registry base). */
16
+ const CACHE_TTL_MS = 10 * 60 * 1000;
17
+ /** Only stable releases are offered for install. */
18
+ const STABLE_VERSION = /^\d+\.\d+\.\d+$/;
19
+ /** npm's public registry; the only base a private `resolved` may be widened to. */
20
+ export const NPM_PUBLIC_REGISTRY = 'https://registry.npmjs.org';
21
+ /** A version spec that resolves through a registry (as opposed to a link/tarball/git). */
22
+ const REGISTRY_VERSION_SPEC = /^(?:[\^~]|>=|<=|>|<|=)?\s*v?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
23
+ /** Dist-tags that name a published release line rather than a local path. */
24
+ const REGISTRY_TAGS = new Set(['latest', 'next', 'beta', 'alpha', 'rc', 'stable']);
25
+ function messageOf(error) {
26
+ if (error instanceof Error)
27
+ return error.message;
28
+ if (typeof error === 'string')
29
+ return error;
30
+ if (typeof error === 'object' && error !== null) {
31
+ const message = error.message;
32
+ if (typeof message === 'string')
33
+ return message;
34
+ }
35
+ return String(error);
36
+ }
37
+ /**
38
+ * The host's ChangeResult carries the human-readable cause in `diagnostic`
39
+ * (a `message` field is not always populated). Prefer it, then `message`, and
40
+ * keep the code prefix because the UI shows this verbatim.
41
+ */
42
+ function describeFieldError(error) {
43
+ const text = [error.diagnostic, error.message]
44
+ .find((part) => typeof part === 'string' && part !== '');
45
+ const parts = [error.code, text]
46
+ .filter((part) => typeof part === 'string' && part !== '');
47
+ return parts.length > 0 ? parts.join(': ') : 'the host reported a bundle error';
48
+ }
49
+ /** The version-spec half of a registry source: a range, wildcard, or dist-tag. */
50
+ function isRegistryRange(value) {
51
+ if (value === '')
52
+ return false;
53
+ const lowered = value.toLowerCase();
54
+ if (lowered === '*' || lowered === 'x')
55
+ return true;
56
+ if (REGISTRY_TAGS.has(lowered))
57
+ return true;
58
+ return REGISTRY_VERSION_SPEC.test(value);
59
+ }
60
+ /**
61
+ * Whether a `listBundles().source` value names a registry-resolvable version
62
+ * spec — the only install shape this updater may replace. The harness records
63
+ * a registry dependency as `<package>@<spec>` (`dependencySpec` in the plugin
64
+ * manager), so the spec half after the last `@` is what gets judged. The test
65
+ * is positive on purpose: link/file/git/workspace/URL/tarball/relative forms
66
+ * all carry a `:` / `/` / `\` or start with `.`, so they fall out without an
67
+ * ever-growing blacklist (a new source scheme must not become silently
68
+ * updatable).
69
+ */
70
+ export function isRegistrySpec(source) {
71
+ const value = typeof source === 'string' ? source.trim() : '';
72
+ if (value === '')
73
+ return false;
74
+ if (value.startsWith('.'))
75
+ return false;
76
+ if (value.includes(':') || value.includes('/') || value.includes('\\'))
77
+ return false;
78
+ const at = value.lastIndexOf('@');
79
+ if (at === -1)
80
+ return isRegistryRange(value);
81
+ const name = value.slice(0, at);
82
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name))
83
+ return false;
84
+ return isRegistryRange(value.slice(at + 1));
85
+ }
86
+ /**
87
+ * Compare two semver strings (build metadata ignored, prerelease precedence per
88
+ * semver §11). Malformed segments count as `0`, so the function never throws on
89
+ * a value read off a registry.
90
+ */
91
+ export function compareVersions(a, b) {
92
+ const parse = (raw) => {
93
+ let value = raw.trim();
94
+ if (value.startsWith('v') || value.startsWith('V'))
95
+ value = value.slice(1);
96
+ const plus = value.indexOf('+');
97
+ if (plus >= 0)
98
+ value = value.slice(0, plus);
99
+ const dash = value.indexOf('-');
100
+ const corePart = dash >= 0 ? value.slice(0, dash) : value;
101
+ const prePart = dash >= 0 ? value.slice(dash + 1) : undefined;
102
+ const core = corePart.split('.').map(segment => {
103
+ const parsed = Number.parseInt(segment, 10);
104
+ return Number.isFinite(parsed) ? parsed : 0;
105
+ });
106
+ return { core, pre: prePart === undefined || prePart === '' ? undefined : prePart.split('.') };
107
+ };
108
+ const left = parse(a);
109
+ const right = parse(b);
110
+ const length = Math.max(left.core.length, right.core.length, 3);
111
+ for (let i = 0; i < length; i += 1) {
112
+ const l = left.core[i] ?? 0;
113
+ const r = right.core[i] ?? 0;
114
+ if (l !== r)
115
+ return l < r ? -1 : 1;
116
+ }
117
+ if (left.pre === undefined && right.pre === undefined)
118
+ return 0;
119
+ if (left.pre === undefined)
120
+ return 1;
121
+ if (right.pre === undefined)
122
+ return -1;
123
+ const preLength = Math.max(left.pre.length, right.pre.length);
124
+ for (let i = 0; i < preLength; i += 1) {
125
+ const l = left.pre[i];
126
+ const r = right.pre[i];
127
+ if (l === undefined)
128
+ return -1;
129
+ if (r === undefined)
130
+ return 1;
131
+ const lNumeric = /^\d+$/.test(l);
132
+ const rNumeric = /^\d+$/.test(r);
133
+ if (lNumeric && rNumeric) {
134
+ const lNum = Number(l);
135
+ const rNum = Number(r);
136
+ if (lNum !== rNum)
137
+ return lNum < rNum ? -1 : 1;
138
+ continue;
139
+ }
140
+ if (lNumeric !== rNumeric)
141
+ return lNumeric ? -1 : 1;
142
+ if (l !== r)
143
+ return l < r ? -1 : 1;
144
+ }
145
+ return 0;
146
+ }
147
+ /**
148
+ * Turn the manager's registry plan into the ordered list this service will
149
+ * actually query, following the host's privacy rule: a *private* `resolved`
150
+ * registry must not be widened with the shared fallback chain.
151
+ *
152
+ * - No configured registry: query `resolved`; append fallbacks only when it is
153
+ * npm's public registry or one of the fallbacks themselves.
154
+ * - Configured registry: query it first, then `resolved` under the same
155
+ * condition, then the fallbacks.
156
+ *
157
+ * http(s) only (a private http registry is legitimate), trailing slashes
158
+ * normalized, duplicates dropped. A base that carries credentials in its URL is
159
+ * skipped: a bare GET cannot replay `.npmrc` auth, so it could only fail with a
160
+ * 401 that reads as "unreachable".
161
+ */
162
+ export function registryPlan(plan) {
163
+ const normalize = (value) => {
164
+ if (typeof value !== 'string')
165
+ return undefined;
166
+ const trimmed = value.trim().replace(/\/+$/, '');
167
+ if (!/^https?:\/\//i.test(trimmed))
168
+ return undefined;
169
+ // Credentials in the URL cannot be replayed here: a bare GET would need the
170
+ // `.npmrc` auth the host keeps to itself, so such a base is never queried.
171
+ if (/^https?:\/\/[^/]*@/i.test(trimmed))
172
+ return undefined;
173
+ return trimmed;
174
+ };
175
+ const fallbacks = [];
176
+ for (const fallback of plan.fallbackRegistries ?? []) {
177
+ const normalized = normalize(fallback);
178
+ if (normalized !== undefined && !fallbacks.includes(normalized))
179
+ fallbacks.push(normalized);
180
+ }
181
+ const resolved = normalize(plan.resolved);
182
+ const configured = normalize(plan.registry);
183
+ const shared = resolved !== undefined
184
+ && (resolved.toLowerCase() === NPM_PUBLIC_REGISTRY || fallbacks.includes(resolved));
185
+ const out = [];
186
+ const add = (value) => {
187
+ if (value === undefined || out.includes(value))
188
+ return;
189
+ out.push(value);
190
+ };
191
+ if (configured !== undefined) {
192
+ add(configured);
193
+ if (shared)
194
+ add(resolved);
195
+ for (const fallback of fallbacks)
196
+ add(fallback);
197
+ }
198
+ else if (resolved !== undefined) {
199
+ add(resolved);
200
+ if (shared)
201
+ for (const fallback of fallbacks)
202
+ add(fallback);
203
+ }
204
+ return out;
205
+ }
206
+ /**
207
+ * Pick the version an update should offer.
208
+ *
209
+ * `dist-tags.latest` leads when it is a stable release newer than `current`
210
+ * (that is the line npm itself blesses). Otherwise the highest stable,
211
+ * non-deprecated published version wins — a lagging `latest` tag must not hide
212
+ * a newer release. When nothing is newer, the stable `latest` tag is still
213
+ * returned so the UI can say "you are on the latest release".
214
+ */
215
+ export function pickUpdateTarget(packument, current) {
216
+ const row = typeof packument === 'object' && packument !== null ? packument : {};
217
+ const time = typeof row.time === 'object' && row.time !== null ? row.time : {};
218
+ const publishedAt = (version) => {
219
+ const value = time[version];
220
+ return typeof value === 'string' ? value : undefined;
221
+ };
222
+ const tags = typeof row['dist-tags'] === 'object' && row['dist-tags'] !== null
223
+ ? row['dist-tags']
224
+ : undefined;
225
+ const versions = typeof row.versions === 'object' && row.versions !== null
226
+ ? row.versions
227
+ : undefined;
228
+ // A string `deprecated` is npm's tombstone; never offer that release.
229
+ const deprecated = (version) => {
230
+ const meta = versions?.[version];
231
+ return typeof meta === 'object' && meta !== null
232
+ && typeof meta.deprecated === 'string';
233
+ };
234
+ // `latest` only leads when the registry did not tombstone that very release.
235
+ const latest = typeof tags?.latest === 'string' && STABLE_VERSION.test(tags.latest) && !deprecated(tags.latest)
236
+ ? tags.latest
237
+ : undefined;
238
+ if (latest !== undefined && compareVersions(latest, current) > 0) {
239
+ return { version: latest, publishedAt: publishedAt(latest) };
240
+ }
241
+ let best;
242
+ for (const [version, meta] of Object.entries(versions ?? {})) {
243
+ if (!STABLE_VERSION.test(version))
244
+ continue;
245
+ if (typeof meta === 'object' && meta !== null && typeof meta.deprecated === 'string')
246
+ continue;
247
+ if (best === undefined || compareVersions(version, best) > 0)
248
+ best = version;
249
+ }
250
+ if (best !== undefined && compareVersions(best, current) > 0) {
251
+ return { version: best, publishedAt: publishedAt(best) };
252
+ }
253
+ if (latest !== undefined)
254
+ return { version: latest, publishedAt: publishedAt(latest) };
255
+ return {};
256
+ }
257
+ /**
258
+ * Pure eligibility matrix, shared by check and apply.
259
+ *
260
+ * `undefined` means the manager (or one of its methods) is unavailable; an
261
+ * empty list means the manager answered but does not carry this plugin.
262
+ */
263
+ export function bundleEligibility(bundles, currentVersion) {
264
+ if (bundles === undefined) {
265
+ return {
266
+ ok: false,
267
+ state: {
268
+ status: 'unsupported',
269
+ current: currentVersion,
270
+ message: 'host does not expose the plugin manager',
271
+ },
272
+ };
273
+ }
274
+ const bundle = bundles.find(entry => entry.name === UPDATE_PACKAGE);
275
+ if (bundle === undefined || bundle.installed !== true) {
276
+ return { ok: false, state: { status: 'not-installed', current: currentVersion } };
277
+ }
278
+ const source = typeof bundle.source === 'string' ? bundle.source.trim() : '';
279
+ if (source === '') {
280
+ return {
281
+ ok: false,
282
+ state: {
283
+ status: 'unsupported',
284
+ current: currentVersion,
285
+ message: 'the host does not report where this plugin was installed from',
286
+ },
287
+ };
288
+ }
289
+ if (!isRegistrySpec(source)) {
290
+ // link: / file: / git+ / git@ / github: / workspace: / https tarball /
291
+ // relative path — the disk payload is not what the registry publishes.
292
+ return { ok: false, state: { status: 'source-install', current: currentVersion } };
293
+ }
294
+ if (bundle.removable === false) {
295
+ // The host refuses to unload it, so the remove-then-install path can only fail.
296
+ return {
297
+ ok: false,
298
+ state: {
299
+ status: 'managed',
300
+ current: currentVersion,
301
+ message: 'the host marks this bundle as not removable',
302
+ },
303
+ };
304
+ }
305
+ const readOnlyReason = typeof bundle.readOnlyReason === 'string' ? bundle.readOnlyReason.trim() : '';
306
+ if (readOnlyReason !== '') {
307
+ return {
308
+ ok: false,
309
+ state: { status: 'managed', current: currentVersion, message: readOnlyReason },
310
+ };
311
+ }
312
+ if (bundle.error !== undefined) {
313
+ return {
314
+ ok: false,
315
+ state: { status: 'failed', current: currentVersion, message: describeFieldError(bundle.error) },
316
+ };
317
+ }
318
+ const diskVersion = typeof bundle.version === 'string' && bundle.version.trim() !== ''
319
+ ? bundle.version.trim()
320
+ : undefined;
321
+ if (diskVersion !== undefined && compareVersions(diskVersion, currentVersion) !== 0) {
322
+ // Installed on disk but the running host still has the old code loaded.
323
+ // Compare semantically: `v1.1.0` / `1.1.0+build` are the same release.
324
+ return {
325
+ ok: false,
326
+ state: {
327
+ status: 'restart-required',
328
+ current: currentVersion,
329
+ installed: diskVersion,
330
+ },
331
+ };
332
+ }
333
+ return { ok: true, ...(diskVersion === undefined ? {} : { installed: diskVersion }) };
334
+ }
335
+ /** Unwrap the manager's ChangeResult from the remote `{ok, value}` envelope. */
336
+ function unwrapInstallResult(raw) {
337
+ if (raw === undefined || raw === null || typeof raw !== 'object')
338
+ return undefined;
339
+ const row = raw;
340
+ if (typeof row.ok === 'boolean') {
341
+ if (!row.ok) {
342
+ const error = row.error;
343
+ const shaped = typeof error === 'object' && error !== null ? error : {};
344
+ const message = typeof shaped.message === 'string'
345
+ ? shaped.message
346
+ : typeof error === 'string' ? error : undefined;
347
+ return {
348
+ error: {
349
+ ...(typeof shaped.code === 'string' ? { code: shaped.code } : {}),
350
+ ...(typeof shaped.diagnostic === 'string' ? { diagnostic: shaped.diagnostic } : {}),
351
+ ...(message === undefined ? {} : { message }),
352
+ },
353
+ };
354
+ }
355
+ return unwrapInstallResult(row.value);
356
+ }
357
+ return row;
358
+ }
359
+ /** Whether a ChangeResult means the requested tree is installed (restart or hot). */
360
+ function isInstallSuccess(result) {
361
+ return result !== undefined && result.error === undefined
362
+ && (result.application === 'applied' || result.application === 'restart-required');
363
+ }
364
+ /**
365
+ * Whether a `removeBundle` ChangeResult really unloaded the tree. Only "no
366
+ * error and nothing contradicting the removal" counts: a `cancelled` /
367
+ * `overridden` / `failed` application without an `error` still leaves the
368
+ * bundle on disk, so retrying the install would hit `already-installed` again.
369
+ */
370
+ function isRemoveSuccess(result) {
371
+ if (result === undefined)
372
+ return true;
373
+ if (result.error !== undefined)
374
+ return false;
375
+ return result.application === undefined
376
+ || result.application === 'applied'
377
+ || result.application === 'restart-required';
378
+ }
379
+ /** A registry URL fit for a message: credentials stripped, no trailing slash. */
380
+ function displayRegistry(base) {
381
+ try {
382
+ const url = new URL(base);
383
+ url.username = '';
384
+ url.password = '';
385
+ return url.toString().replace(/\/+$/, '');
386
+ }
387
+ catch {
388
+ return base.replace(/\/\/[^/@]*@/, '//');
389
+ }
390
+ }
391
+ /**
392
+ * Update checks and installs, memoized per registry base.
393
+ *
394
+ * Caching exists because the settings page polls: a 10-minute window keeps the
395
+ * check honest without turning every mount into a registry round trip. Apply
396
+ * clears the cache so the next check sees the freshly installed version.
397
+ */
398
+ export class UpdateService {
399
+ resolveManager;
400
+ currentVersion;
401
+ isBusy;
402
+ fetchImpl;
403
+ now;
404
+ cache = new Map();
405
+ applying = false;
406
+ /** Registry that answered the last `available` check, passed through to apply. */
407
+ lastTarget;
408
+ constructor(options) {
409
+ this.resolveManager = options.resolveManager;
410
+ this.currentVersion = options.currentVersion;
411
+ this.isBusy = options.isBusy;
412
+ this.fetchImpl = options.fetchImpl ?? fetch;
413
+ this.now = options.now ?? Date.now;
414
+ }
415
+ /** The manager surface plus the disk-version verdict, or a ready-to-return failure state. */
416
+ async eligibility() {
417
+ const manager = this.resolveManager();
418
+ if (manager === undefined
419
+ || typeof manager.listBundles !== 'function'
420
+ || typeof manager.registries !== 'function'
421
+ || typeof manager.installBundle !== 'function') {
422
+ return bundleEligibility(undefined, this.currentVersion);
423
+ }
424
+ try {
425
+ return bundleEligibility(await manager.listBundles(), this.currentVersion);
426
+ }
427
+ catch (error) {
428
+ return { ok: false, state: { status: 'failed', current: this.currentVersion, message: messageOf(error) } };
429
+ }
430
+ }
431
+ async fetchTarget(base) {
432
+ const response = await this.fetchImpl(`${base}/${UPDATE_PACKAGE}`, {
433
+ headers: { accept: 'application/json' },
434
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
435
+ });
436
+ if (!response.ok)
437
+ throw new Error(`registry ${base} answered ${String(response.status)}`);
438
+ return pickUpdateTarget(await response.json(), this.currentVersion);
439
+ }
440
+ /** One registry's packument, via the 10-minute cache. Throws when unreachable. */
441
+ async targetFor(base) {
442
+ const cached = this.cache.get(base);
443
+ if (cached !== undefined && this.now() - cached.at < CACHE_TTL_MS)
444
+ return cached.target;
445
+ const target = await this.fetchTarget(base);
446
+ this.cache.set(base, { at: this.now(), target });
447
+ return target;
448
+ }
449
+ /**
450
+ * Ask the manager's registry chain what is published; never installs.
451
+ *
452
+ * A mirror may lag behind the rest of the chain, so a base that only knows
453
+ * the running (or an older) release does not end the walk — the next base
454
+ * gets its turn. `busy` is deliberately not checked here: reading a registry
455
+ * costs no ACP work, and the settings card should still be able to say what
456
+ * is out there while a turn runs.
457
+ */
458
+ async check() {
459
+ const current = this.currentVersion;
460
+ if (this.applying)
461
+ return { status: 'applying', current };
462
+ this.lastTarget = undefined;
463
+ const eligible = await this.eligibility();
464
+ if (!eligible.ok)
465
+ return eligible.state;
466
+ const installed = eligible.installed === undefined ? {} : { installed: eligible.installed };
467
+ const manager = this.resolveManager();
468
+ let plan;
469
+ try {
470
+ plan = (await manager?.registries?.()) ?? {};
471
+ }
472
+ catch (error) {
473
+ return { status: 'failed', current, message: messageOf(error), ...installed };
474
+ }
475
+ const bases = registryPlan(plan);
476
+ const tried = [];
477
+ let best;
478
+ let reached = 0;
479
+ for (const base of bases) {
480
+ tried.push(base);
481
+ let target;
482
+ try {
483
+ target = await this.targetFor(base);
484
+ }
485
+ catch {
486
+ // Unreachable registry: the next one in the chain gets its turn.
487
+ continue;
488
+ }
489
+ reached += 1;
490
+ const latest = target.version;
491
+ if (latest === undefined)
492
+ continue;
493
+ if (best === undefined || compareVersions(latest, best.version) > 0) {
494
+ best = { version: latest, ...(target.publishedAt === undefined ? {} : { publishedAt: target.publishedAt }) };
495
+ }
496
+ if (compareVersions(latest, current) > 0) {
497
+ if (this.applying)
498
+ return { status: 'applying', current };
499
+ this.lastTarget = { version: latest, registry: base };
500
+ return {
501
+ status: 'available',
502
+ current,
503
+ latest,
504
+ ...(target.publishedAt === undefined ? {} : { publishedAt: target.publishedAt }),
505
+ registries: tried.map(displayRegistry),
506
+ ...installed,
507
+ };
508
+ }
509
+ }
510
+ // An install may have started while the registry walk was in flight; a late
511
+ // `available` must never reach the client after that.
512
+ if (this.applying)
513
+ return { status: 'applying', current };
514
+ if (reached === 0) {
515
+ return {
516
+ status: 'failed',
517
+ current,
518
+ message: tried.length === 0
519
+ ? 'no npm registry is configured'
520
+ : `could not reach an npm registry (tried ${tried.map(displayRegistry).join(', ')})`,
521
+ ...(tried.length === 0 ? {} : { registries: tried.map(displayRegistry) }),
522
+ ...installed,
523
+ };
524
+ }
525
+ return {
526
+ status: 'current',
527
+ current,
528
+ ...(best === undefined
529
+ ? {}
530
+ : { latest: best.version, ...(best.publishedAt === undefined ? {} : { publishedAt: best.publishedAt }) }),
531
+ registries: tried.map(displayRegistry),
532
+ ...installed,
533
+ };
534
+ }
535
+ /**
536
+ * Install one exact version through the harness plugin manager.
537
+ *
538
+ * Re-entry while an install is running answers `applying` instead of
539
+ * stacking a second npm operation; the install itself is the host's job.
540
+ *
541
+ * With HMR alive the manager refuses to replace a bundle already in the
542
+ * profile (`already-installed`), so the host's own update semantics are
543
+ * remove-then-install. That is NOT self-replacement: a human gesture started
544
+ * it, the manager still performs every file operation, and it unloads the
545
+ * live module first — exactly what the host does for any bundle update. If
546
+ * the reinstall fails, the previous version is put back through the same
547
+ * `installBundle` path.
548
+ */
549
+ async apply(version) {
550
+ const current = this.currentVersion;
551
+ if (compareVersions(version, current) <= 0) {
552
+ // A downgrade (or the running version) is never an update. Version
553
+ // syntax is already enforced at the RPC boundary; answer instead of
554
+ // throwing so a stale UI click cannot surface as an RPC fault.
555
+ return {
556
+ status: 'failed',
557
+ current,
558
+ message: 'the requested version is not newer than the running plugin',
559
+ };
560
+ }
561
+ if (this.applying)
562
+ return { status: 'applying', current };
563
+ this.applying = true;
564
+ try {
565
+ const eligible = await this.eligibility();
566
+ if (!eligible.ok)
567
+ return eligible.state;
568
+ const installed = eligible.installed === undefined ? {} : { installed: eligible.installed };
569
+ if (this.isBusy())
570
+ return { status: 'busy', current, ...installed };
571
+ const manager = this.resolveManager();
572
+ const installBundle = manager?.installBundle;
573
+ if (manager === undefined || installBundle === undefined) {
574
+ return { status: 'unsupported', current, message: 'host does not expose the plugin manager' };
575
+ }
576
+ const removeBundle = typeof manager.removeBundle === 'function' ? manager.removeBundle : undefined;
577
+ const registry = this.lastTarget?.version === version ? this.lastTarget.registry : undefined;
578
+ const options = {
579
+ enabled: true,
580
+ ...(registry === undefined ? {} : { registry }),
581
+ };
582
+ const install = async (target, extra) => unwrapInstallResult(await installBundle.call(manager, `${UPDATE_PACKAGE}@${target}`, extra));
583
+ const rollback = async () => {
584
+ // The failed install may already have written the target version into
585
+ // the profile, in which case reinstalling the running version answers
586
+ // `already-installed`. Native update semantics: unload first, ignore
587
+ // failures (the target may never have landed), then install through the
588
+ // host's default chain — the target's registry is not ours to reuse.
589
+ if (removeBundle !== undefined) {
590
+ try {
591
+ await removeBundle.call(manager, UPDATE_PACKAGE);
592
+ }
593
+ catch {
594
+ // Best effort: a bundle that was never installed cannot be removed.
595
+ }
596
+ }
597
+ try {
598
+ return isInstallSuccess(await install(current, { enabled: true }));
599
+ }
600
+ catch {
601
+ return false;
602
+ }
603
+ };
604
+ let result;
605
+ try {
606
+ result = await install(version, options);
607
+ }
608
+ catch (error) {
609
+ return { status: 'failed', current, ...installed, message: messageOf(error) };
610
+ }
611
+ if (result?.error?.code === 'already-installed' && removeBundle !== undefined) {
612
+ let removed;
613
+ try {
614
+ removed = unwrapInstallResult(await removeBundle.call(manager, UPDATE_PACKAGE));
615
+ }
616
+ catch (error) {
617
+ return {
618
+ status: 'failed',
619
+ current,
620
+ ...installed,
621
+ message: `could not remove the running version: ${messageOf(error)}`,
622
+ };
623
+ }
624
+ if (!isRemoveSuccess(removed)) {
625
+ return {
626
+ status: 'failed',
627
+ current,
628
+ ...installed,
629
+ message: `could not remove the running version: ${removed?.error !== undefined
630
+ ? describeFieldError(removed.error)
631
+ : `the plugin manager answered ${removed?.application ?? 'no result'}`}`,
632
+ };
633
+ }
634
+ let retried;
635
+ let retryFailure;
636
+ try {
637
+ retried = await install(version, options);
638
+ }
639
+ catch (error) {
640
+ retryFailure = messageOf(error);
641
+ }
642
+ if (retryFailure === undefined && isInstallSuccess(retried)) {
643
+ result = retried;
644
+ }
645
+ else {
646
+ const reason = retryFailure
647
+ ?? (retried?.error === undefined
648
+ ? retried?.application === undefined
649
+ ? 'the plugin manager returned no install result'
650
+ : `the plugin manager answered ${retried.application}`
651
+ : describeFieldError(retried.error));
652
+ const rolledBack = await rollback();
653
+ return {
654
+ status: 'failed',
655
+ current,
656
+ ...(rolledBack ? { installed: current } : {}),
657
+ message: `installing ${version} failed: ${reason}; ${rolledBack ? `rolled back to ${current}` : `rolling back to ${current} also failed`}`,
658
+ };
659
+ }
660
+ }
661
+ if (result !== undefined && result.error !== undefined) {
662
+ // Never report the target as installed here: the disk still holds the
663
+ // previous version.
664
+ return { status: 'failed', current, ...installed, message: describeFieldError(result.error) };
665
+ }
666
+ const application = result?.application;
667
+ if (application === 'applied' || application === 'restart-required') {
668
+ this.cache.clear();
669
+ this.lastTarget = undefined;
670
+ return { status: application, current, installed: result?.version ?? version };
671
+ }
672
+ if (application === 'overridden') {
673
+ return {
674
+ status: 'failed',
675
+ current,
676
+ ...installed,
677
+ message: 'the installation was overridden by a higher-level configuration',
678
+ };
679
+ }
680
+ if (application === 'cancelled') {
681
+ return { status: 'failed', current, ...installed, message: 'installation was cancelled' };
682
+ }
683
+ return {
684
+ status: 'failed',
685
+ current,
686
+ ...installed,
687
+ message: application === undefined
688
+ ? 'the plugin manager returned no install result'
689
+ : `the plugin manager returned an unexpected application state: ${application}`,
690
+ };
691
+ }
692
+ finally {
693
+ this.applying = false;
694
+ }
695
+ }
696
+ }