@flowscripter/dynamic-cli-framework 9.0.2 → 9.0.4

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 (27) hide show
  1. package/dist/src/service/upgrade/DefaultUpgradeService.d.ts.map +1 -1
  2. package/dist/src/service/upgrade/DefaultUpgradeService.js +18 -330
  3. package/dist/src/service/upgrade/method/githubRelease.d.ts +6 -0
  4. package/dist/src/service/upgrade/method/githubRelease.d.ts.map +1 -0
  5. package/dist/src/service/upgrade/method/githubRelease.js +132 -0
  6. package/dist/src/service/upgrade/method/homebrew.d.ts +11 -0
  7. package/dist/src/service/upgrade/method/homebrew.d.ts.map +1 -0
  8. package/dist/src/service/upgrade/method/homebrew.js +132 -0
  9. package/dist/src/service/upgrade/method/linuxScript.d.ts +5 -0
  10. package/dist/src/service/upgrade/method/linuxScript.d.ts.map +1 -0
  11. package/dist/src/service/upgrade/method/linuxScript.js +15 -0
  12. package/dist/src/service/upgrade/method/shared.d.ts +13 -0
  13. package/dist/src/service/upgrade/method/shared.d.ts.map +1 -0
  14. package/dist/src/service/upgrade/method/shared.js +33 -0
  15. package/dist/src/service/upgrade/method/winget.d.ts +7 -0
  16. package/dist/src/service/upgrade/method/winget.d.ts.map +1 -0
  17. package/dist/src/service/upgrade/method/winget.js +49 -0
  18. package/dist/src/util/helpHelper.d.ts.map +1 -1
  19. package/dist/src/util/helpHelper.js +28 -7
  20. package/package.json +1 -1
  21. package/src/service/upgrade/DefaultUpgradeService.ts +38 -377
  22. package/src/service/upgrade/method/githubRelease.ts +163 -0
  23. package/src/service/upgrade/method/homebrew.ts +165 -0
  24. package/src/service/upgrade/method/linuxScript.ts +23 -0
  25. package/src/service/upgrade/method/shared.ts +51 -0
  26. package/src/service/upgrade/method/winget.ts +64 -0
  27. package/src/util/helpHelper.ts +31 -8
@@ -1 +1 @@
1
- {"version":3,"file":"DefaultUpgradeService.d.ts","sourceRoot":"","sources":["../../../../src/service/upgrade/Defa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,IAAI,OAAO,CAAC,kBAAkB,GAAG,SAAS,CAAC,CAWlF;IAED;;;;;OAKG;IACI,yBAAyB,CAAC,aAAa,EAAE,aAAa,GAAG,MAAM,GAAG,SAAS,CAUjF;IAED;;;;;;;OAOG;IACU,OAAO,CAClB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,GAC1B,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAY/B;IAEM,QAAQ,IAAI,WAAW,GAAG,SAAS,CAWzC;IAEM,UAAU,IAAI,aAAa,GAAG,SAAS,CAQ7C;IAEY,mBAAmB,CAAC,EAAE,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAoDpF;IA2CY,eAAe,CAAC,qBAAqB,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAsC/F;IAEY,OAAO,CAAC,qBAAqB,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAgElF;CA2CF"}
@@ -1,10 +1,10 @@
1
1
  import process from "node:process";
2
- import { existsSync, realpathSync } from "node:fs";
3
- import { mkdtemp, rename, rm } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { basename, dirname, join } from "node:path";
6
2
  import { FETCH_SERVICE_ID, InstallMethod, KEY_VALUE_SERVICE_ID, PRINTER_SERVICE_ID, RunState, SPAWN_SERVICE_ID, SupportedArch, SupportedOs, } from "@flowscripter/dynamic-cli-framework-api";
7
3
  import semver from "semver";
4
+ import { getLatestGithubReleaseVersion, upgradeViaGithubRelease } from "./method/githubRelease.js";
5
+ import { getLatestHomebrewVersion, isHomebrewInstalled, isRunningFromHomebrewCellar, resolveHomebrewOptExecutable, upgradeViaHomebrew, } from "./method/homebrew.js";
6
+ import { isLinuxScriptInstall, upgradeViaLinuxScript } from "./method/linuxScript.js";
7
+ import { getLatestWingetVersion, isWingetInstalled, upgradeViaWinget } from "./method/winget.js";
8
8
  import getLogger from "../../util/logger.js";
9
9
  const logger = getLogger("DefaultUpgradeService");
10
10
  // KeyValueService key caching the resolved InstallMethod (see detectInstallMethod()). Stored
@@ -28,11 +28,6 @@ const CACHE_TTL_MILLIS = 24 * 60 * 60 * 1000;
28
28
  // scoped KeyValueService. The banner never calls checkForUpgrade()/getUpgradeCheckResult() live,
29
29
  // since checking live would stall startup on the network/spawn calls checkForUpgrade() makes.
30
30
  export const UPGRADE_CHECK_CACHE_KEY = "upgrade-check-result";
31
- function describeSpawnFailure(result) {
32
- return "timedOut" in result
33
- ? "timed out"
34
- : (result.error?.message ?? `exit code ${result.exitCode}`);
35
- }
36
31
  export function describeUpgradeCheckResult(result) {
37
32
  return result.status === "failed"
38
33
  ? `Upgrade check result: failed - ${result.error.message}`
@@ -72,11 +67,6 @@ export function toRunState(result) {
72
67
  }
73
68
  return RunState.RUNTIME_ERROR;
74
69
  }
75
- const OS_LABELS = {
76
- [SupportedOs.LINUX]: "Linux",
77
- [SupportedOs.MACOS]: "MacOS",
78
- [SupportedOs.WINDOWS]: "Windows",
79
- };
80
70
  export default class DefaultUpgradeService {
81
71
  #context;
82
72
  #upgradeCheckPromise;
@@ -111,36 +101,6 @@ export default class DefaultUpgradeService {
111
101
  ? this.#context.getServiceById(KEY_VALUE_SERVICE_ID)
112
102
  : undefined;
113
103
  }
114
- // Mirrors SpawnInterfaceAdapter's plugin:add/plugin:remove pattern: wrap a spawned command's
115
- // output in a quoted, marked block that's cleared on success (so a clean install stays quiet)
116
- // but left on screen on failure (so the diagnostic output remains visible).
117
- async #spawnQuoted(command) {
118
- const spawnService = this.#spawnService;
119
- const printerService = this.#printerService;
120
- if (!printerService) {
121
- return spawnService.spawn(command, { mode: "ignore" });
122
- }
123
- printerService.startQuote();
124
- printerService.startMark();
125
- // onOutput is synchronous and may be called concurrently for stdout/stderr lines, but
126
- // printerService.info() is async and must not be invoked concurrently with itself - queue
127
- // writes so they're applied one at a time, in call order.
128
- let writeQueue = Promise.resolve();
129
- const onOutput = (line) => {
130
- writeQueue = writeQueue.then(() => printerService.info(`${line}\n`));
131
- };
132
- const result = await spawnService.spawn(command, { mode: "wrapped", onOutput });
133
- await writeQueue;
134
- printerService.endQuote();
135
- printerService.endMark();
136
- if (result.ok) {
137
- await printerService.clearMarked();
138
- }
139
- else {
140
- printerService.discardMark();
141
- }
142
- return result;
143
- }
144
104
  getUpgradeCheckResult() {
145
105
  if (!this.#upgradeCheckPromise) {
146
106
  logger.debug(() => "Starting upgrade check");
@@ -198,28 +158,11 @@ export default class DefaultUpgradeService {
198
158
  case InstallMethod.LINUX_SCRIPT:
199
159
  return process.execPath;
200
160
  case InstallMethod.HOMEBREW:
201
- return this.#resolveHomebrewOptExecutable();
161
+ return resolveHomebrewOptExecutable(this.#config.homebrew);
202
162
  case InstallMethod.WINGET:
203
163
  return undefined;
204
164
  }
205
165
  }
206
- // The running executable lives in a version-specific Cellar directory, e.g.
207
- // "<prefix>/Cellar/<formula>/<version>/bin/<exe>", while "<prefix>/opt/<formula>" links to the
208
- // installed version, so the upgraded executable is "<prefix>/opt/<formula>/bin/<exe>".
209
- #resolveHomebrewOptExecutable() {
210
- if (!this.#config.homebrew) {
211
- return undefined;
212
- }
213
- const { formula } = this.#config.homebrew;
214
- const realExecutable = this.#resolveRealExecutable();
215
- const cellarIndex = realExecutable.indexOf(`/Cellar/${formula}/`);
216
- if (cellarIndex === -1) {
217
- return undefined;
218
- }
219
- const prefix = realExecutable.slice(0, cellarIndex);
220
- const executable = join(prefix, "opt", formula, "bin", basename(realExecutable));
221
- return existsSync(executable) ? executable : undefined;
222
- }
223
166
  /**
224
167
  * Run `executable` with `args` in place of this process, with terminal input and output
225
168
  * inherited, and wait for it to exit. The child process sees the current version as its
@@ -270,13 +213,13 @@ export default class DefaultUpgradeService {
270
213
  if (process.platform === "darwin" &&
271
214
  os === SupportedOs.MACOS &&
272
215
  this.#config.homebrew &&
273
- this.#isRunningFromHomebrewCellar(this.#config.homebrew.formula)) {
216
+ isRunningFromHomebrewCellar(this.#config.homebrew.formula)) {
274
217
  return InstallMethod.HOMEBREW;
275
218
  }
276
219
  if (process.platform === "linux" &&
277
220
  os === SupportedOs.LINUX &&
278
221
  this.#config.linuxScript &&
279
- this.#isLinuxScriptInstall()) {
222
+ isLinuxScriptInstall()) {
280
223
  return InstallMethod.LINUX_SCRIPT;
281
224
  }
282
225
  // Everything else needs an external process spawn (`brew list`, `winget list`) to confirm -
@@ -289,13 +232,13 @@ export default class DefaultUpgradeService {
289
232
  if (process.platform === "darwin" &&
290
233
  os === SupportedOs.MACOS &&
291
234
  this.#config.homebrew &&
292
- (await this.#isHomebrewInstalled())) {
235
+ (await isHomebrewInstalled(this.#spawnService, this.#config.homebrew))) {
293
236
  detected = InstallMethod.HOMEBREW;
294
237
  }
295
238
  else if (process.platform === "win32" &&
296
239
  os === SupportedOs.WINDOWS &&
297
240
  this.#config.winget &&
298
- (await this.#isWingetInstalled())) {
241
+ (await isWingetInstalled(this.#spawnService, this.#config.winget))) {
299
242
  detected = InstallMethod.WINGET;
300
243
  }
301
244
  else if (this.#config.githubRelease) {
@@ -402,18 +345,20 @@ export default class DefaultUpgradeService {
402
345
  if (this.#printerService) {
403
346
  await this.#printerService.hideSpinner();
404
347
  }
348
+ const spawnService = this.#spawnService;
349
+ const printerService = this.#printerService;
405
350
  switch (checkResult.installMethod) {
406
351
  case InstallMethod.LINUX_SCRIPT:
407
- await this.#upgradeViaLinuxScript();
352
+ await upgradeViaLinuxScript(spawnService, printerService, this.#config.linuxScript);
408
353
  break;
409
354
  case InstallMethod.HOMEBREW:
410
- await this.#upgradeViaHomebrew(checkResult.latestVersion);
355
+ await upgradeViaHomebrew(spawnService, printerService, this.#config.homebrew, checkResult.latestVersion);
411
356
  break;
412
357
  case InstallMethod.WINGET:
413
- await this.#upgradeViaWinget();
358
+ await upgradeViaWinget(spawnService, printerService, this.#config.winget);
414
359
  break;
415
360
  case InstallMethod.GITHUB_RELEASE:
416
- await this.#upgradeViaGithubRelease(checkResult.os, checkResult.arch);
361
+ await upgradeViaGithubRelease(spawnService, this.#fetchService, printerService, this.#config.githubRelease, this.#cliConfig.name, checkResult.os, checkResult.arch);
417
362
  break;
418
363
  }
419
364
  return { ok: true, oldVersion, newVersion: checkResult.latestVersion };
@@ -425,40 +370,6 @@ export default class DefaultUpgradeService {
425
370
  #isPlatformSupported(os, arch) {
426
371
  return this.#config.supportedPlatforms.some((platform) => platform.os === os && platform.arch === arch);
427
372
  }
428
- // Homebrew relinks a formula's installed binary from its Cellar directory into a `bin/` symlink,
429
- // so resolving the running executable's real path confirms a homebrew install without spawning
430
- // `brew`, which has a slow cold start - avoiding it keeps the background upgrade-check
431
- // StartupTask (see UpgradeServiceProvider) fast even though it runs to completion.
432
- #isRunningFromHomebrewCellar(formula) {
433
- return this.#resolveRealExecutable().includes(`/Cellar/${formula}/`);
434
- }
435
- #resolveRealExecutable() {
436
- try {
437
- return realpathSync(process.execPath);
438
- }
439
- catch {
440
- // process.execPath may not resolve on disk (e.g. a fabricated path in tests) - fall back to
441
- // the unresolved path rather than treating that as "not installed".
442
- return process.execPath;
443
- }
444
- }
445
- async #isHomebrewInstalled() {
446
- if (!this.#spawnService || !this.#config.homebrew) {
447
- return false;
448
- }
449
- const result = await this.#spawnService.spawn(["brew", "list", "--versions", this.#config.homebrew.formula], { mode: "ignore", longRunning: false });
450
- return result.ok;
451
- }
452
- async #isWingetInstalled() {
453
- if (!this.#spawnService || !this.#config.winget) {
454
- return false;
455
- }
456
- const result = await this.#spawnService.spawn(["winget", "list", "--id", this.#config.winget.packageId], { mode: "ignore", longRunning: false });
457
- return result.ok;
458
- }
459
- #isLinuxScriptInstall() {
460
- return process.execPath.startsWith("/usr/local/bin/");
461
- }
462
373
  async #getLatestVersion(installMethod) {
463
374
  const cacheKey = `${LATEST_VERSION_CACHE_KEY_PREFIX}${installMethod}`;
464
375
  const keyValueService = this.#keyValueService;
@@ -481,234 +392,11 @@ export default class DefaultUpgradeService {
481
392
  switch (installMethod) {
482
393
  case InstallMethod.GITHUB_RELEASE:
483
394
  case InstallMethod.LINUX_SCRIPT:
484
- return this.#getLatestGithubReleaseVersion();
395
+ return getLatestGithubReleaseVersion(this.#fetchService, this.#config.githubRelease);
485
396
  case InstallMethod.HOMEBREW:
486
- return this.#getLatestHomebrewVersion();
397
+ return getLatestHomebrewVersion(this.#fetchService, this.#config.homebrew);
487
398
  case InstallMethod.WINGET:
488
- return this.#getLatestWingetVersion();
489
- }
490
- }
491
- async #getLatestGithubReleaseVersion() {
492
- if (!this.#config.githubRelease) {
493
- return { ok: false, error: new Error("No githubRelease location configured") };
494
- }
495
- if (!this.#fetchService) {
496
- return { ok: false, error: new Error("FetchService is not available") };
497
- }
498
- const { owner, repo } = this.#config.githubRelease;
499
- try {
500
- // Uses the plain web redirect rather than the api.github.com REST endpoint, since the
501
- // latter's unauthenticated rate limit (60 requests/hour/IP) is easily exhausted, e.g. by
502
- // CI runners sharing an IP pool.
503
- const response = await this.#fetchService.fetch(`https://github.com/${owner}/${repo}/releases/latest`, { redirect: "manual" });
504
- const location = response.headers.get("location");
505
- const version = location ? /\/releases\/tag\/v?([^/]+)$/.exec(location)?.[1] : undefined;
506
- if (!version) {
507
- return {
508
- ok: false,
509
- error: new Error(`Unexpected response resolving latest release for ${owner}/${repo}: HTTP ${response.status}`),
510
- };
511
- }
512
- return { ok: true, version };
513
- }
514
- catch (error) {
515
- return {
516
- ok: false,
517
- error: new Error(`Failed to fetch latest GitHub release for ${owner}/${repo}: ${error}`),
518
- };
519
- }
520
- }
521
- async #getLatestHomebrewVersion() {
522
- if (!this.#config.homebrew) {
523
- return { ok: false, error: new Error("No homebrew location configured") };
524
- }
525
- if (!this.#fetchService) {
526
- return { ok: false, error: new Error("FetchService is not available") };
527
- }
528
- const { tap, formula } = this.#config.homebrew;
529
- const [tapOwner, tapName] = tap.split("/");
530
- if (!tapOwner || !tapName) {
531
- return { ok: false, error: new Error(`Invalid homebrew tap '${tap}'`) };
532
- }
533
- try {
534
- const response = await this.#fetchService.fetch(`https://raw.githubusercontent.com/${tapOwner}/homebrew-${tapName}/main/${formula}.rb`);
535
- if (!response.ok) {
536
- return {
537
- ok: false,
538
- error: new Error(`Failed to fetch homebrew formula for ${tap}/${formula}: HTTP ${response.status}`),
539
- };
540
- }
541
- const text = await response.text();
542
- const version = /version\s+"v?([^"]+)"/.exec(text)?.[1];
543
- if (!version) {
544
- return {
545
- ok: false,
546
- error: new Error(`Could not parse version from homebrew formula ${tap}/${formula}`),
547
- };
548
- }
549
- return { ok: true, version };
550
- }
551
- catch (error) {
552
- return {
553
- ok: false,
554
- error: new Error(`Failed to fetch homebrew formula for ${tap}/${formula}: ${error}`),
555
- };
556
- }
557
- }
558
- async #getLatestWingetVersion() {
559
- if (!this.#config.winget) {
560
- return { ok: false, error: new Error("No winget location configured") };
561
- }
562
- if (!this.#spawnService) {
563
- return { ok: false, error: new Error("SpawnService is not available") };
564
- }
565
- const lines = [];
566
- const result = await this.#spawnService.spawn(["winget", "show", "--id", this.#config.winget.packageId], {
567
- mode: "wrapped",
568
- longRunning: false,
569
- onOutput: (line) => lines.push(line),
570
- });
571
- if (!result.ok) {
572
- return { ok: false, error: new Error(`winget show failed: ${describeSpawnFailure(result)}`) };
573
- }
574
- for (const line of lines) {
575
- const match = /Version:\s*(\S+)/.exec(line);
576
- if (match?.[1]) {
577
- return { ok: true, version: match[1] };
578
- }
579
- }
580
- return { ok: false, error: new Error("Could not parse version from winget output") };
581
- }
582
- async #upgradeViaLinuxScript() {
583
- const { scriptUrl } = this.#config.linuxScript;
584
- const result = await this.#spawnQuoted(["sh", "-c", `curl -fsSL ${scriptUrl} | sh`]);
585
- if (!result.ok) {
586
- throw new Error(`Install script failed: ${describeSpawnFailure(result)}`);
587
- }
588
- }
589
- // The latest version is read from the tap's formula on GitHub, but `brew upgrade` only sees the
590
- // local tap clone, which is stale until `brew update` runs. A stale tap makes `brew upgrade`
591
- // exit 0 with "already installed", so update first and then confirm the installed version.
592
- async #upgradeViaHomebrew(expectedVersion) {
593
- const { tap, formula } = this.#config.homebrew;
594
- const updateResult = await this.#spawnQuoted(["brew", "update"]);
595
- if (!updateResult.ok) {
596
- throw new Error(`brew update failed: ${describeSpawnFailure(updateResult)}`);
597
- }
598
- const result = await this.#spawnQuoted(["brew", "upgrade", `${tap}/${formula}`]);
599
- if (!result.ok) {
600
- throw new Error(`brew upgrade failed: ${describeSpawnFailure(result)}`);
601
- }
602
- const lines = [];
603
- const listResult = await this.#spawnService.spawn(["brew", "list", "--versions", formula], {
604
- mode: "wrapped",
605
- longRunning: false,
606
- onOutput: (line) => lines.push(line),
607
- });
608
- const installed = lines.join(" ").trim();
609
- const installedVersions = installed.split(/\s+/).slice(1);
610
- if (!listResult.ok || !installedVersions.includes(expectedVersion)) {
611
- throw new Error(`brew upgrade completed but version ${expectedVersion} is not installed (installed: ${installed || "unknown"})`);
612
- }
613
- }
614
- async #upgradeViaWinget() {
615
- const { packageId } = this.#config.winget;
616
- const result = await this.#spawnQuoted([
617
- "winget",
618
- "upgrade",
619
- "--id",
620
- packageId,
621
- "--silent",
622
- "--accept-package-agreements",
623
- "--accept-source-agreements",
624
- ]);
625
- if (!result.ok) {
626
- throw new Error(`winget upgrade failed: ${describeSpawnFailure(result)}`);
627
- }
628
- }
629
- async #upgradeViaGithubRelease(os, arch) {
630
- const { owner, repo, assetPattern } = this.#config.githubRelease;
631
- // macOS release assets use "aarch64" rather than "arm64" for the arm64 build; x64 (including
632
- // Intel Macs) always uses "x64" regardless of os.
633
- const archLabel = arch === SupportedArch.X64 ? "x64" : os === SupportedOs.MACOS ? "aarch64" : "arm64";
634
- const assetName = assetPattern.replace("{os}", OS_LABELS[os]).replace("{arch}", archLabel);
635
- const url = `https://github.com/${owner}/${repo}/releases/latest/download/${assetName}`;
636
- // longRunning: true gets cooperative Ctrl-C handling during what can be the slowest step of
637
- // the upgrade.
638
- const response = await this.#fetchService.fetch(url, { longRunning: true });
639
- if (!response.ok) {
640
- throw new Error(`Failed to download release asset '${assetName}': HTTP ${response.status}`);
641
- }
642
- const archiveData = await response.arrayBuffer();
643
- const tmpDir = await mkdtemp(join(tmpdir(), "upgrade-"));
644
- const archivePath = join(tmpDir, assetName);
645
- await Bun.write(archivePath, archiveData);
646
- const currentExecutable = process.execPath;
647
- if (os === SupportedOs.WINDOWS) {
648
- const extractResult = await this.#spawnQuoted([
649
- "powershell",
650
- "-Command",
651
- `Expand-Archive -Path '${archivePath}' -DestinationPath '${tmpDir}' -Force`,
652
- ]);
653
- if (!extractResult.ok) {
654
- throw new Error("Failed to extract release archive");
655
- }
656
- const extractedBinary = join(tmpDir, `${this.#cliConfig.name}.exe`);
657
- const oldPath = `${currentExecutable}.old.exe`;
658
- // Best-effort cleanup of a stale "<exe>.old.exe" left behind by a *previous* upgrade run.
659
- // Windows won't let us delete the just-renamed-aside exe while this process still has it
660
- // open/mapped - that can only happen once we're no longer holding it, i.e. at the start of
661
- // the NEXT invocation, before we move today's running exe aside. Ignore failures: the file
662
- // may not exist, or may still be locked (e.g. another instance still running). Not quoted -
663
- // this is expected to fail silently, there's nothing worth showing the user.
664
- await this.#spawnService.spawn(["cmd", "/c", "del", "/f", "/q", oldPath], {
665
- mode: "ignore",
666
- });
667
- const moveResult = await this.#spawnQuoted([
668
- "cmd",
669
- "/c",
670
- "move",
671
- "/y",
672
- currentExecutable,
673
- oldPath,
674
- ]);
675
- if (!moveResult.ok) {
676
- throw new Error("Failed to move current executable aside");
677
- }
678
- const copyResult = await this.#spawnQuoted([
679
- "cmd",
680
- "/c",
681
- "copy",
682
- "/y",
683
- extractedBinary,
684
- currentExecutable,
685
- ]);
686
- if (!copyResult.ok) {
687
- throw new Error("Failed to copy new executable into place");
688
- }
689
- }
690
- else {
691
- const extractResult = await this.#spawnQuoted(["unzip", "-o", archivePath, "-d", tmpDir]);
692
- if (!extractResult.ok) {
693
- throw new Error("Failed to extract release archive");
694
- }
695
- const extractedBinary = join(tmpDir, this.#cliConfig.name);
696
- // Extract into a staging file in the SAME directory as the running executable (not
697
- // os.tmpdir(), which may be a different filesystem/mount), then atomically rename it over
698
- // currentExecutable. This avoids ETXTBSY: the kernel refuses to open-for-write the inode
699
- // mapped as a running process's text segment, but rename() only swaps the directory entry
700
- // to point at a different inode - the running process keeps executing from its original,
701
- // now-unlinked-but-still-open inode until it next execs/restarts.
702
- const stagingDir = await mkdtemp(join(dirname(currentExecutable), ".upgrade-"));
703
- try {
704
- const stagingBinary = join(stagingDir, this.#cliConfig.name);
705
- await Bun.write(stagingBinary, Bun.file(extractedBinary));
706
- await this.#spawnService.spawn(["chmod", "+x", stagingBinary], { mode: "ignore" });
707
- await rename(stagingBinary, currentExecutable);
708
- }
709
- finally {
710
- await rm(stagingDir, { recursive: true, force: true });
711
- }
399
+ return getLatestWingetVersion(this.#spawnService, this.#config.winget);
712
400
  }
713
401
  }
714
402
  }
@@ -0,0 +1,6 @@
1
+ import { type FetchService, type PrinterService, type SpawnService, SupportedArch, SupportedOs } from "@flowscripter/dynamic-cli-framework-api";
2
+ import type { GithubReleaseLocation } from "../UpgradeLocationsConfig.ts";
3
+ import { type VersionLookupResult } from "./shared.ts";
4
+ export declare function getLatestGithubReleaseVersion(fetchService: FetchService | undefined, location: GithubReleaseLocation | undefined): Promise<VersionLookupResult>;
5
+ export declare function upgradeViaGithubRelease(spawnService: SpawnService, fetchService: FetchService, printerService: PrinterService | undefined, location: GithubReleaseLocation, cliName: string, os: SupportedOs, arch: SupportedArch): Promise<void>;
6
+ //# sourceMappingURL=githubRelease.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"githubRelease.d.ts","sourceRoot":"","sources":["../../../../../src/service/upgrade/method/githubRelease.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,aAAa,EACb,WAAW,EACZ,MAAM,yCAAyC,CAAC;AACjD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAe,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAQpE,wBAAsB,6BAA6B,CACjD,YAAY,EAAE,YAAY,GAAG,SAAS,EACtC,QAAQ,EAAE,qBAAqB,GAAG,SAAS,GAC1C,OAAO,CAAC,mBAAmB,CAAC,CAiC9B;AAED,wBAAsB,uBAAuB,CAC3C,YAAY,EAAE,YAAY,EAC1B,YAAY,EAAE,YAAY,EAC1B,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,QAAQ,EAAE,qBAAqB,EAC/B,OAAO,EAAE,MAAM,EACf,EAAE,EAAE,WAAW,EACf,IAAI,EAAE,aAAa,GAClB,OAAO,CAAC,IAAI,CAAC,CAgGf"}
@@ -0,0 +1,132 @@
1
+ import process from "node:process";
2
+ import { mkdtemp, rename, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { SupportedArch, SupportedOs, } from "@flowscripter/dynamic-cli-framework-api";
6
+ import { spawnQuoted } from "./shared.js";
7
+ const OS_LABELS = {
8
+ [SupportedOs.LINUX]: "Linux",
9
+ [SupportedOs.MACOS]: "MacOS",
10
+ [SupportedOs.WINDOWS]: "Windows",
11
+ };
12
+ export async function getLatestGithubReleaseVersion(fetchService, location) {
13
+ if (!location) {
14
+ return { ok: false, error: new Error("No githubRelease location configured") };
15
+ }
16
+ if (!fetchService) {
17
+ return { ok: false, error: new Error("FetchService is not available") };
18
+ }
19
+ const { owner, repo } = location;
20
+ try {
21
+ // Uses the plain web redirect rather than the api.github.com REST endpoint, since the
22
+ // latter's unauthenticated rate limit (60 requests/hour/IP) is easily exhausted, e.g. by
23
+ // CI runners sharing an IP pool.
24
+ const response = await fetchService.fetch(`https://github.com/${owner}/${repo}/releases/latest`, { redirect: "manual" });
25
+ const redirect = response.headers.get("location");
26
+ const version = redirect ? /\/releases\/tag\/v?([^/]+)$/.exec(redirect)?.[1] : undefined;
27
+ if (!version) {
28
+ return {
29
+ ok: false,
30
+ error: new Error(`Unexpected response resolving latest release for ${owner}/${repo}: HTTP ${response.status}`),
31
+ };
32
+ }
33
+ return { ok: true, version };
34
+ }
35
+ catch (error) {
36
+ return {
37
+ ok: false,
38
+ error: new Error(`Failed to fetch latest GitHub release for ${owner}/${repo}: ${error}`),
39
+ };
40
+ }
41
+ }
42
+ export async function upgradeViaGithubRelease(spawnService, fetchService, printerService, location, cliName, os, arch) {
43
+ const { owner, repo, assetPattern } = location;
44
+ // macOS release assets use "aarch64" rather than "arm64" for the arm64 build; x64 (including
45
+ // Intel Macs) always uses "x64" regardless of os.
46
+ const archLabel = arch === SupportedArch.X64 ? "x64" : os === SupportedOs.MACOS ? "aarch64" : "arm64";
47
+ const assetName = assetPattern.replace("{os}", OS_LABELS[os]).replace("{arch}", archLabel);
48
+ const url = `https://github.com/${owner}/${repo}/releases/latest/download/${assetName}`;
49
+ // longRunning: true gets cooperative Ctrl-C handling during what can be the slowest step of
50
+ // the upgrade.
51
+ const response = await fetchService.fetch(url, { longRunning: true });
52
+ if (!response.ok) {
53
+ throw new Error(`Failed to download release asset '${assetName}': HTTP ${response.status}`);
54
+ }
55
+ const archiveData = await response.arrayBuffer();
56
+ const tmpDir = await mkdtemp(join(tmpdir(), "upgrade-"));
57
+ const archivePath = join(tmpDir, assetName);
58
+ await Bun.write(archivePath, archiveData);
59
+ const currentExecutable = process.execPath;
60
+ if (os === SupportedOs.WINDOWS) {
61
+ const extractResult = await spawnQuoted(spawnService, printerService, [
62
+ "powershell",
63
+ "-Command",
64
+ `Expand-Archive -Path '${archivePath}' -DestinationPath '${tmpDir}' -Force`,
65
+ ]);
66
+ if (!extractResult.ok) {
67
+ throw new Error("Failed to extract release archive");
68
+ }
69
+ const extractedBinary = join(tmpDir, `${cliName}.exe`);
70
+ const oldPath = `${currentExecutable}.old.exe`;
71
+ // Best-effort cleanup of a stale "<exe>.old.exe" left behind by a *previous* upgrade run.
72
+ // Windows won't let us delete the just-renamed-aside exe while this process still has it
73
+ // open/mapped - that can only happen once we're no longer holding it, i.e. at the start of
74
+ // the NEXT invocation, before we move today's running exe aside. Ignore failures: the file
75
+ // may not exist, or may still be locked (e.g. another instance still running). Not quoted -
76
+ // this is expected to fail silently, there's nothing worth showing the user.
77
+ await spawnService.spawn(["cmd", "/c", "del", "/f", "/q", oldPath], {
78
+ mode: "ignore",
79
+ });
80
+ const moveResult = await spawnQuoted(spawnService, printerService, [
81
+ "cmd",
82
+ "/c",
83
+ "move",
84
+ "/y",
85
+ currentExecutable,
86
+ oldPath,
87
+ ]);
88
+ if (!moveResult.ok) {
89
+ throw new Error("Failed to move current executable aside");
90
+ }
91
+ const copyResult = await spawnQuoted(spawnService, printerService, [
92
+ "cmd",
93
+ "/c",
94
+ "copy",
95
+ "/y",
96
+ extractedBinary,
97
+ currentExecutable,
98
+ ]);
99
+ if (!copyResult.ok) {
100
+ throw new Error("Failed to copy new executable into place");
101
+ }
102
+ }
103
+ else {
104
+ const extractResult = await spawnQuoted(spawnService, printerService, [
105
+ "unzip",
106
+ "-o",
107
+ archivePath,
108
+ "-d",
109
+ tmpDir,
110
+ ]);
111
+ if (!extractResult.ok) {
112
+ throw new Error("Failed to extract release archive");
113
+ }
114
+ const extractedBinary = join(tmpDir, cliName);
115
+ // Extract into a staging file in the SAME directory as the running executable (not
116
+ // os.tmpdir(), which may be a different filesystem/mount), then atomically rename it over
117
+ // currentExecutable. This avoids ETXTBSY: the kernel refuses to open-for-write the inode
118
+ // mapped as a running process's text segment, but rename() only swaps the directory entry
119
+ // to point at a different inode - the running process keeps executing from its original,
120
+ // now-unlinked-but-still-open inode until it next execs/restarts.
121
+ const stagingDir = await mkdtemp(join(dirname(currentExecutable), ".upgrade-"));
122
+ try {
123
+ const stagingBinary = join(stagingDir, cliName);
124
+ await Bun.write(stagingBinary, Bun.file(extractedBinary));
125
+ await spawnService.spawn(["chmod", "+x", stagingBinary], { mode: "ignore" });
126
+ await rename(stagingBinary, currentExecutable);
127
+ }
128
+ finally {
129
+ await rm(stagingDir, { recursive: true, force: true });
130
+ }
131
+ }
132
+ }
@@ -0,0 +1,11 @@
1
+ import type { FetchService, PrinterService, SpawnService } from "@flowscripter/dynamic-cli-framework-api";
2
+ import { type SemVer } from "semver";
3
+ import type { HomebrewLocation } from "../UpgradeLocationsConfig.ts";
4
+ import { type VersionLookupResult } from "./shared.ts";
5
+ export declare function parseBrewInstalledVersions(output: string, formula: string): SemVer[];
6
+ export declare function isRunningFromHomebrewCellar(formula: string): boolean;
7
+ export declare function resolveHomebrewOptExecutable(location: HomebrewLocation | undefined): string | undefined;
8
+ export declare function isHomebrewInstalled(spawnService: SpawnService | undefined, location: HomebrewLocation | undefined): Promise<boolean>;
9
+ export declare function getLatestHomebrewVersion(fetchService: FetchService | undefined, location: HomebrewLocation | undefined): Promise<VersionLookupResult>;
10
+ export declare function upgradeViaHomebrew(spawnService: SpawnService, printerService: PrinterService | undefined, location: HomebrewLocation, expectedVersion: string): Promise<void>;
11
+ //# sourceMappingURL=homebrew.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"homebrew.d.ts","sourceRoot":"","sources":["../../../../../src/service/upgrade/method/homebrew.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,YAAY,EACb,MAAM,yCAAyC,CAAC;AACjD,OAAe,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAqC,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAI1F,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAapF;AAgBD,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEpE;AAKD,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,gBAAgB,GAAG,SAAS,GACrC,MAAM,GAAG,SAAS,CAapB;AAED,wBAAsB,mBAAmB,CACvC,YAAY,EAAE,YAAY,GAAG,SAAS,EACtC,QAAQ,EAAE,gBAAgB,GAAG,SAAS,GACrC,OAAO,CAAC,OAAO,CAAC,CASlB;AAED,wBAAsB,wBAAwB,CAC5C,YAAY,EAAE,YAAY,GAAG,SAAS,EACtC,QAAQ,EAAE,gBAAgB,GAAG,SAAS,GACrC,OAAO,CAAC,mBAAmB,CAAC,CAuC9B;AAKD,wBAAsB,kBAAkB,CACtC,YAAY,EAAE,YAAY,EAC1B,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,QAAQ,EAAE,gBAAgB,EAC1B,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CA+Bf"}