looply-cli 0.5.50 → 0.5.51

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.
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REINSTALL_HINT = exports.LAUNCHD_LABEL = exports.SYSTEMD_UNIT = exports.SelfUpdater = exports.ROLLBACK_RETRY_MAX_MS = exports.ROLLBACK_RETRY_BASE_MS = exports.SLIP_WAIT_MAX_MS = exports.CRASH_WINDOW_MS = exports.CRASH_STARTS = exports.HEALTHY_AFTER_MS = exports.AUTO_UPDATE_DEFAULT_ON = exports.EXIT_RESTART = exports.STATE_FILE = exports.RETRY_FAILED_AFTER_MS = exports.DAEMON_STOP_GRACE_MS = exports.STALE_RUN_MS = exports.DRAIN_WAIT_MAX_MS = exports.DRAIN_AFTER_MS = exports.CHECK_EVERY_MS = exports.SELF_UPDATE_TICK_MS = exports.PACKAGE = void 0;
3
+ exports.REINSTALL_HINT = exports.LAUNCHD_LABEL = exports.SYSTEMD_UNIT = exports.SelfUpdater = exports.ROLLBACK_RETRY_MAX_MS = exports.ROLLBACK_RETRY_BASE_MS = exports.SLIP_WAIT_MAX_MS = exports.CRASH_WINDOW_MS = exports.CRASH_STARTS = exports.HEALTHY_AFTER_MS = exports.AUTO_UPDATE_DEFAULT_ON = exports.EXIT_RESTART = exports.STATE_FILE = exports.SNAPSHOT_DIR = exports.VERSION_RETRY_TIMEOUT_MS = exports.VERSION_TIMEOUT_MS = exports.BROKEN_KEEP = exports.LOCKED_RETRY_MS = exports.LOCKED_TRIES = exports.NOT_DOWNLOADABLE_RECHECK_MS = exports.RETRY_MAX_MS = exports.REGISTRY_LAG_RETRY_MS = exports.TRANSIENT_RETRY_MS = exports.RETRY_FAILED_AFTER_MS = exports.DAEMON_STOP_GRACE_MS = exports.STALE_RUN_MS = exports.DRAIN_WAIT_MAX_MS = exports.DRAIN_AFTER_MS = exports.CHECK_EVERY_MS = exports.SELF_UPDATE_TICK_MS = exports.PACKAGE = void 0;
4
4
  exports.autoUpdateOff = autoUpdateOff;
5
5
  exports.globalInstallOf = globalInstallOf;
6
+ exports.classifyInstallFailure = classifyInstallFailure;
7
+ exports.failedAttempt = failedAttempt;
8
+ exports.unpin = unpin;
9
+ exports.pinsAbove = pinsAbove;
10
+ exports.markBroken = markBroken;
6
11
  exports.isNewer = isNewer;
7
12
  exports.decideUpdate = decideUpdate;
8
13
  exports.isLooplyRunCommand = isLooplyRunCommand;
@@ -23,11 +28,19 @@ exports.updateRegistry = updateRegistry;
23
28
  exports.nodeSelfUpdateTask = nodeSelfUpdateTask;
24
29
  exports.binaryVersion = binaryVersion;
25
30
  exports.npmInstall = npmInstall;
31
+ exports.registryServes = registryServes;
32
+ exports.shimPaths = shimPaths;
33
+ exports.swapIn = swapIn;
34
+ exports.treeSize = treeSize;
35
+ exports.snapshotInstall = snapshotInstall;
36
+ exports.restoreInstall = restoreInstall;
37
+ exports.nodeSelfUpdatePins = nodeSelfUpdatePins;
26
38
  exports.nodeRecordStart = nodeRecordStart;
27
39
  exports.nodeStartupCheck = nodeStartupCheck;
28
40
  exports.relaunchServe = relaunchServe;
29
41
  const node_child_process_1 = require("node:child_process");
30
42
  const node_fs_1 = require("node:fs");
43
+ const node_fs_2 = require("node:fs");
31
44
  const node_path_1 = require("node:path");
32
45
  const core_1 = require("@looply/core");
33
46
  const machine_settings_1 = require("./machine-settings");
@@ -89,6 +102,24 @@ exports.STALE_RUN_MS = 12 * 60 * 60_000;
89
102
  exports.DAEMON_STOP_GRACE_MS = 10 * 60_000;
90
103
  /** A version whose install failed is not tried again for this long. */
91
104
  exports.RETRY_FAILED_AFTER_MS = 6 * 60 * 60_000;
105
+ /** An install that failed for a passing reason (network, a locked file) is tried again after this… */
106
+ exports.TRANSIENT_RETRY_MS = 60 * 60_000;
107
+ /** …and one npm could not find yet (the registry still settling after a publish) after this. */
108
+ exports.REGISTRY_LAG_RETRY_MS = 10 * 60_000;
109
+ /** Each failure of the same version in a row doubles its wait, up to this — so nothing loops. */
110
+ exports.RETRY_MAX_MS = 24 * 60 * 60_000;
111
+ /** On `latest` but not downloadable yet: looked at again this soon, not in 30 minutes. */
112
+ exports.NOT_DOWNLOADABLE_RECHECK_MS = 10 * 60_000;
113
+ /** A Windows file lock (EBUSY/EPERM) during the install: npm is tried this many times, this far apart. */
114
+ exports.LOCKED_TRIES = 3;
115
+ exports.LOCKED_RETRY_MS = 30_000;
116
+ /** How many versions proven broken on this PC are remembered. */
117
+ exports.BROKEN_KEEP = 20;
118
+ /** How long `looply --version` gets, and how long the one second try gets before a release is pinned broken. */
119
+ exports.VERSION_TIMEOUT_MS = 60_000;
120
+ exports.VERSION_RETRY_TIMEOUT_MS = 5 * 60_000;
121
+ /** Where the installed package is copied before an update, so it can be put back without the network. */
122
+ exports.SNAPSHOT_DIR = 'self-update-previous';
92
123
  exports.STATE_FILE = 'self-update.json';
93
124
  /** `looply serve` under systemd/launchd exits with this after updating, so the manager starts the new one. */
94
125
  exports.EXIT_RESTART = 75;
@@ -152,6 +183,65 @@ function globalInstallOf(bin, platform, fileExists) {
152
183
  const prefix = path.dirname(parent);
153
184
  return fileExists(path.join(prefix, 'bin', 'looply')) ? { prefix, packageDir } : null;
154
185
  }
186
+ /**
187
+ * Sorts npm's error output. `locked`: Windows would not let a file go
188
+ * (antivirus, a shell sitting in the folder, a process with a native module
189
+ * loaded). `unavailable`: npm cannot find the version or its tarball yet —
190
+ * what a mirror or CDN says in the minutes after a publish.
191
+ */
192
+ function classifyInstallFailure(detail) {
193
+ if (/\bE(BUSY|PERM|ACCES)\b|resource busy|operation not permitted|being used by another process/i.test(detail))
194
+ return 'locked';
195
+ if (/\bE(TARGET|404)\b|notarget|No matching version|404 Not Found|is not in this registry/i.test(detail))
196
+ return 'unavailable';
197
+ if (/\bE(CONNRESET|CONNREFUSED|TIMEDOUT|NOTFOUND|AI_AGAIN|SOCKETTIMEOUT|INTEGRITY)\b|network|socket hang up|fetch failed/i.test(detail)) {
198
+ return 'network';
199
+ }
200
+ return 'other';
201
+ }
202
+ /**
203
+ * The record of a failed attempt, with when it may be tried again: the wait
204
+ * for its kind, doubled for each failure of the same version in a row, at
205
+ * most `RETRY_MAX_MS`. A lock or a permission that never clears therefore
206
+ * costs a few attempts a day at most, not one an hour forever.
207
+ */
208
+ function failedAttempt(version, now, detail, failure, previous) {
209
+ const again = previous !== null && previous !== undefined && !previous.ok && previous.version === version;
210
+ const failures = again ? (previous.failures ?? 1) + 1 : 1;
211
+ const base = failure === 'unavailable' ? exports.REGISTRY_LAG_RETRY_MS : failure === 'other' ? exports.RETRY_FAILED_AFTER_MS : exports.TRANSIENT_RETRY_MS;
212
+ const wait = Math.min(base * 2 ** (failures - 1), exports.RETRY_MAX_MS);
213
+ return { version, at: new Date(now).toISOString(), ok: false, detail, retryAfter: new Date(now + wait).toISOString(), failures };
214
+ }
215
+ /**
216
+ * The state with pins taken off: one version, or every pin when `version` is
217
+ * absent (`looply serve auto-update unpin [version]`), plus what came off.
218
+ * For a pin that came from a passing cause — a PC too loaded to answer
219
+ * `--version` even on the second, longer try.
220
+ */
221
+ function unpin(state, version) {
222
+ const all = state.broken ?? [];
223
+ const keep = all.filter((b) => version !== undefined && b.version !== version);
224
+ const removed = all.filter((b) => !keep.includes(b)).map((b) => b.version);
225
+ const { broken: _all, lastAttempt, ...rest } = state;
226
+ // The failed attempt that pinned it would otherwise still hold it back for hours.
227
+ const stale = lastAttempt !== undefined && !lastAttempt.ok && removed.includes(lastAttempt.version);
228
+ const next = { ...rest, ...(lastAttempt === undefined || stale ? {} : { lastAttempt }), ...(keep.length > 0 ? { broken: keep } : {}) };
229
+ return { state: next, removed };
230
+ }
231
+ /**
232
+ * Pins that no longer matter once `installed` is on the PC: every version at
233
+ * or below it. Only a newer `latest` is ever a target, so they would only sit
234
+ * in the file looking like a live problem.
235
+ */
236
+ function pinsAbove(broken, installed) {
237
+ const left = (broken ?? []).filter((b) => isNewer(b.version, installed));
238
+ return left.length > 0 ? left : undefined;
239
+ }
240
+ /** The state with `version` remembered as broken on this PC (the newest `BROKEN_KEEP` kept). */
241
+ function markBroken(state, version, now, why) {
242
+ const others = (state.broken ?? []).filter((b) => b.version !== version);
243
+ return { ...state, broken: [...others, { version, at: new Date(now).toISOString(), why }].slice(-exports.BROKEN_KEEP) };
244
+ }
155
245
  /** Whether the published version is newer than this one — the only reason to ask the server. */
156
246
  function isNewer(latest, current) {
157
247
  const a = (0, core_1.parseReleaseVersion)(latest);
@@ -179,13 +269,24 @@ function decideUpdate(i) {
179
269
  const problem = (0, core_1.cliCompatProblem)(i.compat.value, latest);
180
270
  if (problem !== null)
181
271
  return { kind: 'stay', why: `${latest} is published, but ${problem}` };
272
+ const broken = (i.broken ?? []).find((b) => b.version === latest);
273
+ if (broken !== undefined) {
274
+ return { kind: 'stay', why: `${latest} did not work on this PC (${broken.why}, ${broken.at}); staying on ${i.current} until a newer release is published` };
275
+ }
182
276
  if (i.last !== null && !i.last.ok && i.last.version === latest) {
183
- const at = Date.parse(i.last.at);
184
- if (Number.isFinite(at) && i.now - at < exports.RETRY_FAILED_AFTER_MS) {
185
- const again = new Date(at + exports.RETRY_FAILED_AFTER_MS).toISOString();
277
+ const retryAt = i.last.retryAfter !== undefined ? Date.parse(i.last.retryAfter) : Date.parse(i.last.at) + exports.RETRY_FAILED_AFTER_MS;
278
+ if (Number.isFinite(retryAt) && i.now < retryAt) {
279
+ const again = new Date(retryAt).toISOString();
186
280
  return { kind: 'stay', why: `installing ${latest} failed at ${i.last.at} (${i.last.detail}); trying again after ${again}` };
187
281
  }
188
282
  }
283
+ if (i.downloadable !== undefined && !i.downloadable.ok) {
284
+ return {
285
+ kind: 'stay',
286
+ why: `${latest} is npm's latest but cannot be downloaded yet (${i.downloadable.error}); looking again in ${exports.NOT_DOWNLOADABLE_RECHECK_MS / 60_000} minutes`,
287
+ recheckMs: exports.NOT_DOWNLOADABLE_RECHECK_MS,
288
+ };
289
+ }
189
290
  return { kind: 'update', to: latest };
190
291
  }
191
292
  /* ──────────────────────────────────────────────────────── runs in flight ── */
@@ -338,29 +439,33 @@ function startupGuard(state, current, now) {
338
439
  return { kind: 'rollback', to: p.previous, why };
339
440
  }
340
441
  /**
341
- * The state after a rollback attempt. Done: the update is over and recorded as
342
- * failed, so the version waits `RETRY_FAILED_AFTER_MS`. Not done: the update is
343
- * KEPT pending, with a backoff, so the next start tries again.
442
+ * The state after a rollback attempt. A crash loop proves the version broken
443
+ * whether or not the way back worked, so it is recorded BROKEN either way
444
+ * (`markBroken`). Done: the update is over. Not done: the update is KEPT
445
+ * pending, with a backoff, so the next start tries putting the previous one
446
+ * back again.
344
447
  */
345
448
  function afterRollback(state, current, now, done, why) {
346
449
  const at = new Date(now).toISOString();
347
450
  const lastAttempt = { version: current, at, ok: false, detail: why };
451
+ const pinned = markBroken(state, current, now, why);
348
452
  const p = state.pendingVerify;
349
453
  if (done || p === undefined) {
350
- const { pendingVerify: _done, ...rest } = state;
454
+ const { pendingVerify: _done, ...rest } = pinned;
351
455
  return { ...rest, lastAttempt };
352
456
  }
353
457
  const tries = (p.rollbackTries ?? 0) + 1;
354
458
  const wait = Math.min(exports.ROLLBACK_RETRY_BASE_MS * 2 ** (tries - 1), exports.ROLLBACK_RETRY_MAX_MS);
355
- return { ...state, lastAttempt, pendingVerify: { ...p, rollbackTries: tries, rollbackRetryAt: new Date(now + wait).toISOString() } };
459
+ return { ...pinned, lastAttempt, pendingVerify: { ...p, rollbackTries: tries, rollbackRetryAt: new Date(now + wait).toISOString() } };
356
460
  }
357
461
  /**
358
462
  * A relaunched serve that never came up: that version failed, whatever the
359
- * rollback managed. Recorded so it is not tried again for `RETRY_FAILED_AFTER_MS`
360
- * — without this, `lastAttempt` still said OK and the next check reinstalled it.
463
+ * rollback managed. Recorded BROKEN, so it is not installed again until a newer
464
+ * release — without this, `lastAttempt` still said OK and the next check
465
+ * reinstalled it.
361
466
  */
362
467
  function relaunchFailed(state, version, now, detail) {
363
- const { pendingVerify: _done, ...rest } = state;
468
+ const { pendingVerify: _done, ...rest } = markBroken(state, version, now, detail);
364
469
  return { ...rest, lastAttempt: { version, at: new Date(now).toISOString(), ok: false, detail } };
365
470
  }
366
471
  class SelfUpdater {
@@ -437,7 +542,7 @@ class SelfUpdater {
437
542
  this.staleSaid = runs.stale;
438
543
  return runs;
439
544
  }
440
- /** The full decision, asked afresh: npm, the server, the opt-out and the last attempt. */
545
+ /** The full decision, asked afresh: npm, the server, the opt-out, the last attempt, and whether it can be downloaded. */
441
546
  async ask(now) {
442
547
  const d = this.deps;
443
548
  const off = d.offReason();
@@ -462,11 +567,29 @@ class SelfUpdater {
462
567
  else {
463
568
  latest = { ok: false, error: 'not asked' };
464
569
  }
465
- return decideUpdate({ current: d.current, off, install: d.install, latest, compat, last: d.readState().lastAttempt ?? null, now });
570
+ const state = d.readState();
571
+ const input = { current: d.current, off, install: d.install, latest, compat, last: state.lastAttempt ?? null, broken: state.broken, now };
572
+ const decision = decideUpdate(input);
573
+ if (decision.kind !== 'update' || d.downloadable === undefined)
574
+ return decision;
575
+ // Asked last, and only for a version everything else says yes to.
576
+ let downloadable;
577
+ try {
578
+ await d.downloadable(decision.to);
579
+ downloadable = { ok: true };
580
+ }
581
+ catch (e) {
582
+ downloadable = { ok: false, error: e?.message ?? String(e) };
583
+ }
584
+ return decideUpdate({ ...input, downloadable });
466
585
  }
467
586
  async decide(now) {
468
587
  const d = this.deps;
469
588
  const decision = await this.ask(now);
589
+ if (decision.kind === 'stay' && decision.recheckMs !== undefined) {
590
+ // Looked at again in `recheckMs`, not at the next half-hourly check.
591
+ this.lastCheck = now - (d.checkEveryMs ?? exports.CHECK_EVERY_MS) + decision.recheckMs;
592
+ }
470
593
  if (decision.kind === 'update') {
471
594
  if (this.target !== decision.to) {
472
595
  this.target = decision.to;
@@ -490,6 +613,19 @@ class SelfUpdater {
490
613
  }
491
614
  async apply(to, drain) {
492
615
  const d = this.deps;
616
+ // 🔴 THE WAY BACK FIRST, while nothing is stopped yet: a copy of what is
617
+ // installed now, so a failed or half-done npm can be undone with no network.
618
+ // No copy, no update — it waits like any failed attempt, and serve carries on.
619
+ if (d.snapshot !== undefined) {
620
+ const snap = await d.snapshot().catch((e) => ({ ok: false, detail: e?.message ?? String(e) }));
621
+ if (!snap.ok) {
622
+ const detail = `could not keep a copy of ${d.current} to go back to (${snap.detail})`;
623
+ this.record({ lastAttempt: failedAttempt(to, d.now(), detail, 'other', d.readState().lastAttempt) });
624
+ d.log(say(`not updating to ${to}: ${detail}; nothing was stopped, and it is tried again later`));
625
+ this.target = null;
626
+ return;
627
+ }
628
+ }
493
629
  this.finished = true;
494
630
  const unchanged = { expect: d.current };
495
631
  if (drain) {
@@ -542,26 +678,71 @@ class SelfUpdater {
542
678
  d.log(say(`replacing the package under ${others.length} other live looply process(es) (${named}); they keep the code they loaded — restart them after the update`));
543
679
  }
544
680
  d.log(say(`installing ${exports.PACKAGE}@${to}`));
545
- const result = await this.installAndCheck(to);
681
+ let result = await this.installAndCheck(to);
682
+ // A file Windows will not let go of (EBUSY/EPERM) is usually let go of in
683
+ // seconds — antivirus, an indexer. Tried again a few times before giving up.
684
+ for (let tries = 1; !result.ok && !result.broken && classifyInstallFailure(result.detail) === 'locked' && tries < exports.LOCKED_TRIES; tries += 1) {
685
+ d.log(say(`a file is locked (${result.detail}); trying npm again in ${exports.LOCKED_RETRY_MS / 1000} seconds (${tries + 1} of ${exports.LOCKED_TRIES})`));
686
+ await d.sleep(exports.LOCKED_RETRY_MS);
687
+ if (d.cancelled?.())
688
+ break;
689
+ result = await this.installAndCheck(to);
690
+ }
546
691
  if (result.ok) {
547
692
  const at = new Date(d.now()).toISOString();
548
- this.record({
693
+ const before = d.readState();
694
+ const cleared = (before.broken ?? []).filter((b) => !isNewer(b.version, to)).map((b) => b.version);
695
+ const { broken: _pins, ...rest } = before;
696
+ const left = pinsAbove(before.broken, to);
697
+ d.writeState({
698
+ ...rest,
699
+ ...(left === undefined ? {} : { broken: left }),
549
700
  lastAttempt: { version: to, at, ok: true, detail: result.detail },
550
701
  pendingVerify: { version: to, previous: d.current, at, starts: [] },
551
702
  });
703
+ if (cleared.length > 0)
704
+ d.log(say(`${to} supersedes the release(s) pinned broken here (${cleared.join(', ')}); those pins are cleared`));
552
705
  d.log(say(`installed ${to}, and it answers \`--version\` with ${to}; restarting serve on it`));
553
706
  d.restart({ expect: to, rollbackTo: d.current });
554
707
  return;
555
708
  }
556
- this.record({ lastAttempt: { version: to, at: new Date(d.now()).toISOString(), ok: false, detail: result.detail } });
709
+ const before = d.readState();
710
+ const attempt = failedAttempt(to, d.now(), result.detail, result.broken ? 'other' : classifyInstallFailure(result.detail), before.lastAttempt);
711
+ this.record({ lastAttempt: attempt, ...(result.broken ? { broken: markBroken(before, to, d.now(), result.detail).broken } : {}) });
557
712
  d.log(say(`installing ${to} failed — ${result.detail}; putting ${d.current} back`));
558
- const back = await this.installAndCheck(d.current);
713
+ const back = await this.putBack();
714
+ const next = result.broken ? `not installing ${to} again; a newer release will be` : `trying ${to} again after ${attempt.retryAfter}`;
559
715
  d.log(back.ok
560
- ? say(`${d.current} is back; restarting serve on it, and trying ${to} again after ${exports.RETRY_FAILED_AFTER_MS / 3_600_000} hours`)
716
+ ? say(`${d.current} is back (${back.detail}); restarting serve on it, and ${next}`)
561
717
  : say(`🔴 could not put ${d.current} back either (${back.detail}); restarting serve on whatever is installed — this PC needs a look`));
562
718
  d.restart(unchanged);
563
719
  }
564
- /** Install, then ask the installed binary what it is: npm's exit code is not the proof. */
720
+ /**
721
+ * The previous version back in place: nothing to do if npm left it untouched
722
+ * (a lock usually stops npm before it changes anything), else the local copy,
723
+ * else npm as the last resort.
724
+ */
725
+ async putBack() {
726
+ const d = this.deps;
727
+ if ((await d.installedVersion().catch(() => null)) === d.current)
728
+ return { ok: true, detail: 'npm had left it in place' };
729
+ let why = 'no local copy';
730
+ if (d.restoreSnapshot !== undefined) {
731
+ const r = await d.restoreSnapshot().catch((e) => ({ ok: false, detail: e?.message ?? String(e) }));
732
+ const says = r.ok ? await d.installedVersion().catch(() => null) : null;
733
+ if (says === d.current)
734
+ return { ok: true, detail: 'from the local copy' };
735
+ why = r.ok ? `the local copy answers ${says ?? 'nothing'} to --version` : r.detail;
736
+ d.log(say(`the local copy did not bring ${d.current} back (${why}); asking npm for it`));
737
+ }
738
+ const viaNpm = await this.installAndCheck(d.current);
739
+ return viaNpm.ok ? { ok: true, detail: 'from npm' } : { ok: false, detail: `${why}; npm: ${viaNpm.detail}` };
740
+ }
741
+ /**
742
+ * Install, then ask the installed binary what it is: npm's exit code is not
743
+ * the proof. `broken`: npm finished, but the binary it left does not run at
744
+ * all — the release itself is at fault, not this PC's network or files.
745
+ */
565
746
  async installAndCheck(version) {
566
747
  const d = this.deps;
567
748
  let r;
@@ -573,9 +754,15 @@ class SelfUpdater {
573
754
  }
574
755
  if (!r.ok)
575
756
  return r;
576
- const says = await d.installedVersion().catch(() => null);
577
- if (says !== version)
578
- return { ok: false, detail: `npm finished, but the installed looply answers ${says ?? 'nothing'} to --version` };
757
+ let says = await d.installedVersion().catch(() => null);
758
+ // ⚠️ A binary that says nothing may only be slow — a loaded PC, antivirus
759
+ // scanning the fresh files. It is asked once more, with far longer, before
760
+ // the release is pinned broken for good.
761
+ if (says === null)
762
+ says = await d.installedVersion(exports.VERSION_RETRY_TIMEOUT_MS).catch(() => null);
763
+ if (says !== version) {
764
+ return { ok: false, detail: `npm finished, but the installed looply answers ${says ?? 'nothing'} to --version`, broken: says === null };
765
+ }
579
766
  return r;
580
767
  }
581
768
  }
@@ -699,6 +886,9 @@ function nodeSelfUpdateTask(o, ctl) {
699
886
  throw new Error('npm gave no version');
700
887
  return v;
701
888
  },
889
+ downloadable: (v) => registryServes(registry, v),
890
+ snapshot: async () => (install === null ? { ok: false, detail: 'not a global install' } : snapshotInstall(install, o.home, o.current, o.platform)),
891
+ restoreSnapshot: async () => install === null ? { ok: false, detail: 'not a global install' } : restoreInstall(install, o.home, o.current, o.platform),
702
892
  compat: async () => {
703
893
  const identity = new machine_store_1.MachineStore((0, machine_store_1.machineFilePath)(o.home)).load();
704
894
  if (identity === null)
@@ -724,7 +914,7 @@ function nodeSelfUpdateTask(o, ctl) {
724
914
  },
725
915
  stopDaemons: () => ctl.stopDaemons(),
726
916
  installVersion: (v) => npmInstall(install, v, registry, o.platform, o.log),
727
- installedVersion: () => binaryVersion(o.bin),
917
+ installedVersion: (timeoutMs) => binaryVersion(o.bin, timeoutMs),
728
918
  readState: () => {
729
919
  try {
730
920
  return JSON.parse((0, node_fs_1.readFileSync)(stateFile, 'utf8'));
@@ -775,11 +965,11 @@ function processListing(platform) {
775
965
  }
776
966
  /** `node <bin> --version`, from a fresh process — the code now on disk, not the code this serve loaded. */
777
967
  /* istanbul ignore next — real processes */
778
- function binaryVersion(bin) {
968
+ function binaryVersion(bin, timeoutMs = exports.VERSION_TIMEOUT_MS) {
779
969
  if (bin === null)
780
970
  return Promise.resolve(null);
781
971
  return new Promise((resolve) => {
782
- (0, node_child_process_1.execFile)(process.execPath, [bin, '--version'], { windowsHide: true, timeout: 60_000 }, (err, stdout) => {
972
+ (0, node_child_process_1.execFile)(process.execPath, [bin, '--version'], { windowsHide: true, timeout: timeoutMs }, (err, stdout) => {
783
973
  resolve(err ? null : stdout.trim() || null);
784
974
  });
785
975
  });
@@ -804,6 +994,8 @@ function npmInstall(install, version, registry, platform, log) {
804
994
  '--registry',
805
995
  `${registry}/`,
806
996
  `${exports.PACKAGE}@${version}`,
997
+ // npm's own cache may still hold the package list from before the publish.
998
+ '--prefer-online',
807
999
  '--no-fund',
808
1000
  '--no-audit',
809
1001
  '--loglevel=error',
@@ -834,13 +1026,241 @@ function npmInstall(install, version, registry, platform, log) {
834
1026
  clearTimeout(timer);
835
1027
  for (const l of tail)
836
1028
  log(say(`npm: ${l}`));
1029
+ // npm's own words go into the detail: they are what `classifyInstallFailure` reads.
1030
+ const said = tail.filter((l) => /\bE[A-Z0-9]{3,}\b|\berr(or)?\b/i.test(l)).slice(-2).join(' | ');
837
1031
  if (code === 0)
838
1032
  resolve({ ok: true, detail: `npm installed ${version}` });
839
1033
  else
840
- resolve({ ok: false, detail: `npm exited with code ${code}` });
1034
+ resolve({ ok: false, detail: `npm exited with code ${code}${said === '' ? '' : `: ${said}`}` });
841
1035
  });
842
1036
  });
843
1037
  }
1038
+ /**
1039
+ * Resolves when the registry serves `version`'s manifest and its tarball can
1040
+ * be fetched. In the minutes after a publish `latest` can already name a
1041
+ * version whose tarball a CDN edge or a mirror does not have yet; asking first
1042
+ * means no daemon is stopped for an install that would fail.
1043
+ */
1044
+ /* istanbul ignore next — real network */
1045
+ async function registryServes(registry, version) {
1046
+ const res = await fetch(`${registry}/${exports.PACKAGE}/${version}`, {
1047
+ headers: { accept: 'application/json' },
1048
+ signal: AbortSignal.timeout(20_000),
1049
+ });
1050
+ if (!res.ok)
1051
+ throw new Error(`the registry answers ${res.status} for ${exports.PACKAGE}@${version}`);
1052
+ const tarball = (await res.json()).dist?.tarball;
1053
+ if (typeof tarball !== 'string' || tarball === '')
1054
+ throw new Error(`the registry lists no tarball for ${exports.PACKAGE}@${version}`);
1055
+ const head = await fetch(tarball, { method: 'HEAD', signal: AbortSignal.timeout(20_000) });
1056
+ // 405: a registry that does not answer HEAD; npm will GET it anyway.
1057
+ if (!head.ok && head.status !== 405)
1058
+ throw new Error(`its tarball answers ${head.status}`);
1059
+ }
1060
+ /** The command shims npm writes for a global install, which a failed install can leave missing. */
1061
+ function shimPaths(install, platform) {
1062
+ if (platform === 'win32')
1063
+ return ['looply', 'looply.cmd', 'looply.ps1'].map((n) => node_path_1.win32.join(install.prefix, n));
1064
+ return [node_path_1.posix.join(install.prefix, 'bin', 'looply')];
1065
+ }
1066
+ /**
1067
+ * Put a COMPLETE staged copy in place of the live package with two renames:
1068
+ * live → `old`, staged → live, then `old` is removed.
1069
+ *
1070
+ * 🔴 THE LIVE FOLDER IS NEVER DELETED IN PLACE. Before this, a folder Windows
1071
+ * would not move was deleted file by file and the copy written over it; when
1072
+ * the copy hit the same lock the PC was left with half a package. Now: if the
1073
+ * live folder cannot be moved aside, nothing has changed and that is said; if
1074
+ * the staged copy cannot be moved in, the live one is moved straight back. The
1075
+ * only state with no package at `live` is the instant between two renames on
1076
+ * the same volume.
1077
+ */
1078
+ async function swapIn(fs, live, staged, old) {
1079
+ const msg = (e) => e?.message ?? String(e);
1080
+ const dropStaged = () => fs.remove(staged).catch(() => undefined);
1081
+ if (!(await fs.exists(staged)))
1082
+ return { ok: false, detail: 'there is no staged copy to put in place; the install is left as it was' };
1083
+ const had = await fs.exists(live);
1084
+ if (had) {
1085
+ try {
1086
+ await fs.rename(live, old);
1087
+ }
1088
+ catch (e) {
1089
+ await dropStaged();
1090
+ return { ok: false, detail: `the installed folder could not be moved aside (${msg(e)}); it is left as it was` };
1091
+ }
1092
+ }
1093
+ try {
1094
+ await fs.rename(staged, live);
1095
+ }
1096
+ catch (e) {
1097
+ if (had) {
1098
+ try {
1099
+ await fs.rename(old, live);
1100
+ }
1101
+ catch (back) {
1102
+ return { ok: false, detail: `🔴 the copy could not be moved in (${msg(e)}), nor the previous folder moved back (${msg(back)}); it is at ${old}` };
1103
+ }
1104
+ }
1105
+ await dropStaged();
1106
+ return { ok: false, detail: `the copy could not be moved in (${msg(e)}); the install is left as it was` };
1107
+ }
1108
+ if (had) {
1109
+ try {
1110
+ await fs.remove(old);
1111
+ }
1112
+ catch {
1113
+ return { ok: true, detail: `swapped in; the replaced folder is left at ${old} for the next install to clear` };
1114
+ }
1115
+ }
1116
+ return { ok: true, detail: 'swapped in' };
1117
+ }
1118
+ /* istanbul ignore next — real files */
1119
+ const nodeSwapFs = {
1120
+ exists: (p) => node_fs_2.promises.access(p).then(() => true, () => false),
1121
+ rename: (from, to) => node_fs_2.promises.rename(from, to),
1122
+ remove: (p) => node_fs_2.promises.rm(p, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 }),
1123
+ };
1124
+ /** Every file under `dir`, counted and summed — without blocking serve's event loop. */
1125
+ /* istanbul ignore next — real files */
1126
+ async function treeSize(dir) {
1127
+ let files = 0;
1128
+ let bytes = 0;
1129
+ const walk = async (d) => {
1130
+ for (const entry of await node_fs_2.promises.readdir(d, { withFileTypes: true })) {
1131
+ const p = (0, node_path_1.join)(d, entry.name);
1132
+ if (entry.isDirectory())
1133
+ await walk(p);
1134
+ else {
1135
+ files += 1;
1136
+ bytes += (await node_fs_2.promises.lstat(p)).size;
1137
+ }
1138
+ }
1139
+ };
1140
+ await walk(dir);
1141
+ return { files, bytes };
1142
+ }
1143
+ const sameTree = (a, b) => a !== undefined && a.files === b.files && a.bytes === b.bytes;
1144
+ const snapshotDir = (home) => (0, node_path_1.join)(home, '.looply', exports.SNAPSHOT_DIR);
1145
+ const samePath = (a, b, platform) => platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
1146
+ /* istanbul ignore next — real files */
1147
+ function readMark(home) {
1148
+ try {
1149
+ return JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(snapshotDir(home), 'snapshot.json'), 'utf8'));
1150
+ }
1151
+ catch {
1152
+ return null;
1153
+ }
1154
+ }
1155
+ /**
1156
+ * Copy the installed package and its shims to `~/.looply/self-update-previous`,
1157
+ * with `fs.promises` so serve's event loop keeps running. The mark
1158
+ * (`snapshot.json`, with the copy's file count and size) is written LAST, so a
1159
+ * copy cut short is never taken for a whole one. A kept copy of the same
1160
+ * version is reused only while it still matches its mark.
1161
+ */
1162
+ /* istanbul ignore next — real files */
1163
+ async function snapshotInstall(install, home, current, platform) {
1164
+ try {
1165
+ const onDisk = JSON.parse(await node_fs_2.promises.readFile((0, node_path_1.join)(install.packageDir, 'package.json'), 'utf8')).version;
1166
+ if (onDisk !== current)
1167
+ return { ok: false, detail: `the package on disk says ${String(onDisk)}, this serve is ${current}` };
1168
+ const dir = snapshotDir(home);
1169
+ const mark = readMark(home);
1170
+ if (mark !== null && mark.version === current && samePath(mark.packageDir, install.packageDir, platform)) {
1171
+ const kept = await treeSize((0, node_path_1.join)(dir, 'package')).catch(() => null);
1172
+ if (kept !== null && sameTree(mark.tree, kept))
1173
+ return { ok: true, detail: `a copy of ${current} is already kept` };
1174
+ }
1175
+ await node_fs_2.promises.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 });
1176
+ await node_fs_2.promises.mkdir((0, node_path_1.join)(dir, 'shims'), { recursive: true });
1177
+ await node_fs_2.promises.cp(install.packageDir, (0, node_path_1.join)(dir, 'package'), { recursive: true, verbatimSymlinks: true });
1178
+ const tree = await treeSize((0, node_path_1.join)(dir, 'package'));
1179
+ const live = await treeSize(install.packageDir);
1180
+ if (!sameTree(live, tree))
1181
+ return { ok: false, detail: `the copy holds ${tree.files} files, the install ${live.files}` };
1182
+ const shims = [];
1183
+ for (const shim of shimPaths(install, platform)) {
1184
+ if (!(await nodeSwapFs.exists(shim)))
1185
+ continue;
1186
+ const name = platform === 'win32' ? node_path_1.win32.basename(shim) : node_path_1.posix.basename(shim);
1187
+ await node_fs_2.promises.cp(shim, (0, node_path_1.join)(dir, 'shims', name), { verbatimSymlinks: true });
1188
+ shims.push(name);
1189
+ }
1190
+ const next = { version: current, packageDir: install.packageDir, shims, at: new Date().toISOString(), tree };
1191
+ await node_fs_2.promises.writeFile((0, node_path_1.join)(dir, 'snapshot.json'), JSON.stringify(next, null, 2) + '\n', 'utf8');
1192
+ return { ok: true, detail: `kept a copy of ${current} (${tree.files} files)` };
1193
+ }
1194
+ catch (e) {
1195
+ return { ok: false, detail: e.message };
1196
+ }
1197
+ }
1198
+ /**
1199
+ * Put the kept copy of `version` back in place of whatever npm left — no
1200
+ * network. The copy is first staged WHOLE beside the package (same volume) and
1201
+ * checked against its mark; only then is it swapped in by renames (`swapIn`).
1202
+ * Anything short of that leaves the install exactly as it was. Then any
1203
+ * missing shim comes back.
1204
+ */
1205
+ /* istanbul ignore next — real files; the swap is swapIn */
1206
+ async function restoreInstall(install, home, version, platform) {
1207
+ const mark = readMark(home);
1208
+ if (mark === null)
1209
+ return { ok: false, detail: 'no local copy was kept' };
1210
+ if (mark.version !== version || !samePath(mark.packageDir, install.packageDir, platform)) {
1211
+ return { ok: false, detail: `the local copy is ${mark.version} at ${mark.packageDir}, not ${version} here` };
1212
+ }
1213
+ const dir = snapshotDir(home);
1214
+ const modules = (0, node_path_1.dirname)(install.packageDir);
1215
+ // What an earlier restore cut short left behind (serve stopped mid-copy): a
1216
+ // staged copy, or a replaced folder that could not be removed yet.
1217
+ for (const name of await node_fs_2.promises.readdir(modules).catch(() => [])) {
1218
+ if (name.startsWith(`.${exports.PACKAGE}-restore-`) || name.startsWith(`.${exports.PACKAGE}-old-`))
1219
+ await nodeSwapFs.remove((0, node_path_1.join)(modules, name)).catch(() => undefined);
1220
+ }
1221
+ const stamp = `${process.pid}-${Date.now()}`;
1222
+ const staged = (0, node_path_1.join)(modules, `.${exports.PACKAGE}-restore-${stamp}`);
1223
+ const old = (0, node_path_1.join)(modules, `.${exports.PACKAGE}-old-${stamp}`);
1224
+ try {
1225
+ await node_fs_2.promises.cp((0, node_path_1.join)(dir, 'package'), staged, { recursive: true, verbatimSymlinks: true });
1226
+ const got = await treeSize(staged);
1227
+ if (mark.tree !== undefined && !sameTree(mark.tree, got)) {
1228
+ await nodeSwapFs.remove(staged).catch(() => undefined);
1229
+ return { ok: false, detail: `the local copy is not whole (${got.files} of ${mark.tree.files} files); the install is left as it was` };
1230
+ }
1231
+ }
1232
+ catch (e) {
1233
+ await nodeSwapFs.remove(staged).catch(() => undefined);
1234
+ return { ok: false, detail: `staging the local copy failed (${e.message}); the install is left as it was` };
1235
+ }
1236
+ const swapped = await swapIn(nodeSwapFs, install.packageDir, staged, old);
1237
+ if (!swapped.ok)
1238
+ return swapped;
1239
+ try {
1240
+ const prefixDir = platform === 'win32' ? install.prefix : node_path_1.posix.join(install.prefix, 'bin');
1241
+ for (const name of mark.shims)
1242
+ await node_fs_2.promises.cp((0, node_path_1.join)(dir, 'shims', name), (0, node_path_1.join)(prefixDir, name), { force: true, verbatimSymlinks: true });
1243
+ }
1244
+ catch (e) {
1245
+ return { ok: true, detail: `put ${version} back from the local copy, but a command shim could not be restored (${e.message})` };
1246
+ }
1247
+ return { ok: true, detail: `put ${version} back from the local copy` };
1248
+ }
1249
+ /** The previous version back: the local copy first, npm only when that does not answer `--version` with it. */
1250
+ /* istanbul ignore next — real files and npm */
1251
+ async function putBackNode(install, o, version, log) {
1252
+ if (install === null)
1253
+ return { ok: false, detail: 'not a global install' };
1254
+ const local = await restoreInstall(install, o.home, version, o.platform);
1255
+ if (local.ok && (await binaryVersion(o.bin)) === version)
1256
+ return local;
1257
+ log(say(`the local copy did not bring ${version} back (${local.ok ? 'it does not answer --version' : local.detail}); asking npm for it`));
1258
+ const viaNpm = await npmInstall(install, version, updateRegistry(o.env), o.platform, log);
1259
+ if (!viaNpm.ok)
1260
+ return viaNpm;
1261
+ const says = await binaryVersion(o.bin);
1262
+ return says === version ? viaNpm : { ok: false, detail: `the installed looply answers ${says ?? 'nothing'}` };
1263
+ }
844
1264
  /* istanbul ignore next — real files */
845
1265
  function readStateFile(home) {
846
1266
  try {
@@ -863,6 +1283,25 @@ function writeStateFile(home, state, log) {
863
1283
  log(say(`could not record in ${file} (${e.message})`));
864
1284
  }
865
1285
  }
1286
+ /** `looply serve auto-update unpin`: this PC's pins, read and taken off in `~/.looply/self-update.json`. */
1287
+ /* istanbul ignore next — real files; the decision is unpin */
1288
+ function nodeSelfUpdatePins(home) {
1289
+ return {
1290
+ list: () => readStateFile(home)?.broken ?? [],
1291
+ unpin: (version) => {
1292
+ const state = readStateFile(home);
1293
+ if (state === null)
1294
+ return [];
1295
+ const r = unpin(state, version);
1296
+ if (r.removed.length > 0) {
1297
+ writeStateFile(home, r.state, () => {
1298
+ throw new Error(`could not write ${(0, node_path_1.join)(home, '.looply', exports.STATE_FILE)}`);
1299
+ });
1300
+ }
1301
+ return r.removed;
1302
+ },
1303
+ };
1304
+ }
866
1305
  /** The first thing serve does: count this start if it is on an unproven update (`recordStart`). */
867
1306
  /* istanbul ignore next — real files; the decision is recordStart */
868
1307
  function nodeRecordStart(o) {
@@ -893,15 +1332,12 @@ async function nodeStartupCheck(o) {
893
1332
  }
894
1333
  o.log(say(`🔴 ${verdict.why}; putting ${verdict.to} back`));
895
1334
  const install = globalInstallOf(o.bin, o.platform, node_fs_1.existsSync);
896
- const back = install === null
897
- ? { ok: false, detail: 'not a global install' }
898
- : await npmInstall(install, verdict.to, updateRegistry(o.env), o.platform, o.log);
899
- const says = back.ok ? await binaryVersion(o.bin) : null;
900
- const done = says === verdict.to;
1335
+ const back = await putBackNode(install, o, verdict.to, o.log);
1336
+ const done = back.ok;
901
1337
  const after = afterRollback(state, o.current, Date.now(), done, verdict.why);
902
1338
  writeStateFile(o.home, after, o.log);
903
1339
  if (!done) {
904
- o.log(say(`🔴 could not put ${verdict.to} back (${back.ok ? `the installed looply answers ${says ?? 'nothing'}` : back.detail}); trying again at ${after.pendingVerify?.rollbackRetryAt ?? 'the next start'}`));
1340
+ o.log(say(`🔴 could not put ${verdict.to} back (${back.detail}); trying again at ${after.pendingVerify?.rollbackRetryAt ?? 'the next start'}`));
905
1341
  return null;
906
1342
  }
907
1343
  return { said: say(`${verdict.to} is back after ${verdict.why}; starting serve on it`), plan: { expect: verdict.to } };
@@ -994,12 +1430,12 @@ async function relaunchServe(o) {
994
1430
  // same broken version back every half hour.
995
1431
  const state = readStateFile(o.home) ?? {};
996
1432
  writeStateFile(o.home, relaunchFailed(state, o.plan.expect, Date.now(), `serve on ${o.plan.expect} did not come up after the update`), o.say);
997
- o.say(say(`🔴 serve on ${o.plan.expect} did not come up; putting ${o.plan.rollbackTo} back, and not trying ${o.plan.expect} again for ${exports.RETRY_FAILED_AFTER_MS / 3_600_000} hours`));
1433
+ o.say(say(`🔴 serve on ${o.plan.expect} did not come up; putting ${o.plan.rollbackTo} back, and not installing ${o.plan.expect} again — a newer release will be`));
998
1434
  const install = globalInstallOf(o.bin, o.platform, node_fs_1.existsSync);
999
- const back = install === null ? { ok: false, detail: 'not a global install' } : await npmInstall(install, o.plan.rollbackTo, updateRegistry(o.env), o.platform, o.say);
1435
+ const back = await putBackNode(install, o, o.plan.rollbackTo, o.say);
1000
1436
  const again = back.ok ? start() : null;
1001
1437
  if (again !== null && (await confirmServeStarted(again, checks))) {
1002
- return { exitCode: 0, said: `serve: ${o.plan.expect} did not start; ${o.plan.rollbackTo} is back and its supervisor is up (pid ${again})` };
1438
+ return { exitCode: 0, said: `serve: ${o.plan.expect} did not start; ${o.plan.rollbackTo} is back (${back.detail}) and its supervisor is up (pid ${again})` };
1003
1439
  }
1004
1440
  return { exitCode: 1, said: `serve: 🔴 neither ${o.plan.expect} nor ${o.plan.rollbackTo} came up (${back.detail}) — this PC needs a look` };
1005
1441
  }