-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathpackage-update-steps.ts
More file actions
767 lines (720 loc) · 22.8 KB
/
Copy pathpackage-update-steps.ts
File metadata and controls
767 lines (720 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
// Runs package update move, inventory, and cleanup steps.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { pathExists } from "./fs-safe.js";
import { readPackageVersion } from "./package-json.js";
import { movePathWithCopyFallback } from "./replace-file.js";
import { trimLogTail } from "./restart-sentinel.js";
import {
PACKAGE_POST_INSTALL_DOCTOR_ADVISORY,
UPDATE_POST_INSTALL_DOCTOR_ADVISORY_EXIT_CODE,
type PackageUpdateStepAdvisory,
type UpdatePostInstallDoctorResult,
} from "./update-doctor-result.js";
export type { PackageUpdateStepAdvisory } from "./update-doctor-result.js";
import {
collectInstalledGlobalPackageErrors,
globalInstallArgs,
globalInstallFallbackArgs,
resolveNpmGlobalPrefixLayoutFromGlobalRoot,
resolveNpmGlobalPrefixLayoutFromPrefix,
resolvePnpmGlobalDirFromGlobalRoot,
resolveExpectedInstalledVersionFromSpec,
resolveGlobalInstallTarget,
type CommandRunner,
type NpmGlobalPrefixLayout,
type ResolvedGlobalInstallTarget,
} from "./update-global.js";
const PACKAGE_MANAGER_SWAP_SOURCE_HARDLINKS = "allow" as const;
/**
* Captures one package-manager or filesystem step from the global update flow.
* Callers surface these records directly in update diagnostics.
*/
export type PackageUpdateStepResult = {
name: string;
command: string;
cwd: string;
durationMs: number;
exitCode: number | null;
stdoutTail?: string | null;
stderrTail?: string | null;
signal?: NodeJS.Signals | null;
killed?: boolean;
termination?: "exit" | "timeout" | "no-output-timeout" | "signal";
advisory?: PackageUpdateStepAdvisory;
};
type PackageUpdateStepRunner = (params: {
name: string;
argv: string[];
cwd?: string;
timeoutMs: number;
env?: NodeJS.ProcessEnv;
}) => Promise<PackageUpdateStepResult>;
type StagedNpmInstall = {
prefix: string;
layout: NpmGlobalPrefixLayout;
packageRoot: string;
installTarget: ResolvedGlobalInstallTarget;
};
type NpmBinShimBackup = {
backupDir: string;
targetBinDir: string;
entries: Array<{
name: string;
hadExisting: boolean;
}>;
};
const NPM_PACK_QUIET_FLAGS = ["--json", "--loglevel=error"] as const;
function formatError(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
function isBlockingPackageUpdateStep(step: PackageUpdateStepResult): boolean {
return step.exitCode !== 0 && step.advisory === undefined;
}
function isNormalProcessExit(step: {
signal?: NodeJS.Signals | null;
killed?: boolean;
termination?: "exit" | "timeout" | "no-output-timeout" | "signal";
}): boolean {
return (
step.termination !== "timeout" &&
step.termination !== "no-output-timeout" &&
step.termination !== "signal" &&
step.killed !== true &&
(step.signal === undefined || step.signal === null)
);
}
export function markPackagePostInstallDoctorAdvisory<
T extends {
exitCode: number | null;
stderrTail?: string | null;
signal?: NodeJS.Signals | null;
killed?: boolean;
termination?: "exit" | "timeout" | "no-output-timeout" | "signal";
advisory?: PackageUpdateStepAdvisory;
},
>(
step: T,
result: UpdatePostInstallDoctorResult | null,
): T & {
advisory?: PackageUpdateStepAdvisory;
} {
if (
step.exitCode !== UPDATE_POST_INSTALL_DOCTOR_ADVISORY_EXIT_CODE ||
result?.status !== "advisory" ||
!isNormalProcessExit(step)
) {
return step;
}
const advisoryTail = [
step.stderrTail,
...result.advisory.details,
PACKAGE_POST_INSTALL_DOCTOR_ADVISORY.message,
]
.filter((line): line is string => Boolean(line?.trim()))
.join("\n");
return {
...step,
advisory: PACKAGE_POST_INSTALL_DOCTOR_ADVISORY,
stderrTail: trimLogTail(advisoryTail) ?? step.stderrTail,
};
}
async function removePathBestEffort(targetPath: string): Promise<boolean> {
try {
await fs.rm(targetPath, {
recursive: true,
force: true,
maxRetries: process.platform === "win32" ? 5 : 2,
retryDelay: 100,
});
return true;
} catch {
return false;
}
}
async function readPackageVersionIfPresent(packageRoot: string | null): Promise<string | null> {
if (!packageRoot) {
return null;
}
try {
return await readPackageVersion(packageRoot);
} catch {
return null;
}
}
function isUnambiguousNpmPrefixGlobalRoot(globalRoot: string | null): boolean {
const trimmed = globalRoot?.trim();
if (!trimmed) {
return false;
}
const normalized = path.resolve(trimmed);
if (path.basename(normalized) !== "node_modules") {
return false;
}
const parentDir = path.dirname(normalized);
if (path.basename(parentDir) === "lib") {
return true;
}
return process.platform === "win32" && path.basename(parentDir).toLowerCase() === "npm";
}
function resolveStagedNpmTargetLayout(
installTarget: ResolvedGlobalInstallTarget,
): NpmGlobalPrefixLayout | null {
const targetLayout = resolveNpmGlobalPrefixLayoutFromGlobalRoot(installTarget.globalRoot, {
allowDirectNodeModulesRoot: installTarget.directNodeModulesRoot === true,
});
if (!targetLayout) {
return null;
}
if (
installTarget.manager === "npm" ||
isUnambiguousNpmPrefixGlobalRoot(installTarget.globalRoot)
) {
return targetLayout;
}
return null;
}
function stripPackageAlias(spec: string, packageName: string): string {
const trimmed = spec.trim();
const prefix = `${packageName.trim()}@`;
return trimmed.toLowerCase().startsWith(prefix.toLowerCase())
? trimmed.slice(prefix.length).trim()
: trimmed;
}
function isHttpGitUrlSpec(spec: string): boolean {
try {
const url = new URL(spec);
if (url.protocol !== "https:" && url.protocol !== "http:") {
return false;
}
const pathname = url.pathname.replace(/\/+$/u, "");
if (pathname.endsWith(".git")) {
return true;
}
const parts = pathname.split("/").filter(Boolean);
return url.hostname.toLowerCase() === "github.com" && parts.length === 2;
} catch {
return false;
}
}
function isGitHubShorthandSpec(spec: string): boolean {
const [repo] = spec.split("#", 1);
if (!repo || repo.startsWith(".") || repo.startsWith("/") || repo.startsWith("@")) {
return false;
}
const parts = repo.split("/");
return parts.length === 2 && parts.every((part) => /^[^\s/:@]+$/u.test(part));
}
function isNpmGitSourceInstallSpec(spec: string, packageName: string): boolean {
const target = stripPackageAlias(spec, packageName);
return (
/^github:/i.test(target) ||
/^git\+(?:ssh|https|http|file):/i.test(target) ||
/^git:/i.test(target) ||
/^ssh:\/\//i.test(target) ||
/^[^@\s]+@[^:\s]+:[^#\s]+(?:#.*)?$/u.test(target) ||
isHttpGitUrlSpec(target) ||
isGitHubShorthandSpec(target)
);
}
async function createStagedNpmInstall(
installTarget: ResolvedGlobalInstallTarget,
packageName: string,
): Promise<StagedNpmInstall | null> {
const targetLayout = resolveStagedNpmTargetLayout(installTarget);
if (!targetLayout) {
return null;
}
await fs.mkdir(targetLayout.globalRoot, { recursive: true });
const prefix = await fs.mkdtemp(path.join(targetLayout.globalRoot, ".openclaw-update-stage-"));
const layout = resolveNpmGlobalPrefixLayoutFromPrefix(prefix);
const command = installTarget.manager === "npm" ? installTarget.command : "npm";
return {
prefix,
layout,
packageRoot: path.join(layout.globalRoot, packageName),
installTarget: {
manager: "npm",
command,
globalRoot: layout.globalRoot,
packageRoot: path.join(layout.globalRoot, packageName),
},
};
}
async function findPackedTarball(packDir: string): Promise<string | null> {
const entries = await fs.readdir(packDir).catch((): string[] => []);
const tarballs = entries.filter((entry) => entry.endsWith(".tgz"));
if (tarballs.length !== 1) {
return null;
}
return path.join(packDir, tarballs[0] ?? "");
}
async function prepareNpmGitSourceInstallSpec(params: {
installTarget: ResolvedGlobalInstallTarget;
installSpec: string;
packageName: string;
runStep: PackageUpdateStepRunner;
timeoutMs: number;
env?: NodeJS.ProcessEnv;
installCwd?: string;
}): Promise<{
installSpec: string;
packDir: string | null;
steps: PackageUpdateStepResult[];
failedStep: PackageUpdateStepResult | null;
}> {
if (
params.installTarget.manager !== "npm" ||
!isNpmGitSourceInstallSpec(params.installSpec, params.packageName)
) {
return { installSpec: params.installSpec, packDir: null, steps: [], failedStep: null };
}
const packDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-update-pack-"));
const packStep = await params.runStep({
name: "global update pack",
argv: [
params.installTarget.command,
"pack",
params.installSpec,
"--pack-destination",
packDir,
...NPM_PACK_QUIET_FLAGS,
],
cwd: params.installCwd,
env: params.env,
timeoutMs: params.timeoutMs,
});
if (packStep.exitCode !== 0) {
return {
installSpec: params.installSpec,
packDir,
steps: [packStep],
failedStep: packStep,
};
}
const tarball = await findPackedTarball(packDir);
if (!tarball) {
const failedStep: PackageUpdateStepResult = {
name: "global update pack verify",
command: `find packed tarball in ${packDir}`,
cwd: packDir,
durationMs: 0,
exitCode: 1,
stdoutTail: null,
stderrTail: `expected exactly one .tgz from npm pack ${params.installSpec}`,
};
return {
installSpec: params.installSpec,
packDir,
steps: [packStep, failedStep],
failedStep,
};
}
return {
installSpec: tarball,
packDir,
steps: [packStep],
failedStep: null,
};
}
async function prepareStagedNpmInstall(
installTarget: ResolvedGlobalInstallTarget,
packageName: string,
): Promise<{
stagedInstall: StagedNpmInstall | null;
failedStep: PackageUpdateStepResult | null;
}> {
const startedAt = Date.now();
try {
return {
stagedInstall: await createStagedNpmInstall(installTarget, packageName),
failedStep: null,
};
} catch (err) {
const targetLayout =
installTarget.manager === "npm"
? resolveNpmGlobalPrefixLayoutFromGlobalRoot(installTarget.globalRoot, {
allowDirectNodeModulesRoot: installTarget.directNodeModulesRoot === true,
})
: null;
return {
stagedInstall: null,
failedStep: {
name: "global install stage",
command: "prepare staged npm install",
cwd: targetLayout?.prefix ?? installTarget.globalRoot ?? process.cwd(),
durationMs: Date.now() - startedAt,
exitCode: 1,
stdoutTail: null,
stderrTail: formatError(err),
},
};
}
}
async function cleanupStagedNpmInstall(stage: StagedNpmInstall | null): Promise<void> {
if (!stage) {
return;
}
await removePathBestEffort(stage.prefix);
}
async function copyPathEntry(source: string, destination: string): Promise<void> {
const stat = await fs.lstat(source);
await removePathBestEffort(destination);
if (stat.isSymbolicLink()) {
await fs.symlink(await fs.readlink(source), destination);
return;
}
if (stat.isDirectory()) {
await fs.cp(source, destination, {
recursive: true,
force: true,
preserveTimestamps: false,
});
return;
}
await fs.copyFile(source, destination);
await fs.chmod(destination, stat.mode).catch(() => undefined);
}
async function replaceNpmBinShims(params: {
stageLayout: NpmGlobalPrefixLayout;
targetLayout: NpmGlobalPrefixLayout;
packageName: string;
}): Promise<void> {
let entries: string[];
try {
entries = await fs.readdir(params.stageLayout.binDir);
} catch {
return;
}
const names = new Set([params.packageName, "openclaw"]);
const shimEntries = entries.filter((entry) => {
const parsed = path.parse(entry);
return names.has(entry) || names.has(parsed.name);
});
if (shimEntries.length === 0) {
return;
}
const backup: NpmBinShimBackup = {
backupDir: await fs.mkdtemp(
path.join(params.targetLayout.globalRoot, ".openclaw-shim-backup-"),
),
targetBinDir: params.targetLayout.binDir,
entries: [],
};
try {
await fs.mkdir(params.targetLayout.binDir, { recursive: true });
for (const entry of shimEntries) {
const destination = path.join(params.targetLayout.binDir, entry);
const hadExisting = await pathExists(destination);
backup.entries.push({ name: entry, hadExisting });
if (hadExisting) {
await copyPathEntry(destination, path.join(backup.backupDir, entry));
}
}
for (const entry of shimEntries) {
await copyPathEntry(
path.join(params.stageLayout.binDir, entry),
path.join(params.targetLayout.binDir, entry),
);
}
} catch (err) {
await restoreNpmBinShimBackup(backup);
throw err;
} finally {
await removePathBestEffort(backup.backupDir);
}
}
async function restoreNpmBinShimBackup(backup: NpmBinShimBackup): Promise<void> {
await fs.mkdir(backup.targetBinDir, { recursive: true });
for (const entry of backup.entries) {
const destination = path.join(backup.targetBinDir, entry.name);
await removePathBestEffort(destination);
if (entry.hadExisting) {
await copyPathEntry(path.join(backup.backupDir, entry.name), destination);
}
}
}
async function swapStagedNpmInstall(params: {
stage: StagedNpmInstall;
installTarget: ResolvedGlobalInstallTarget;
packageName: string;
}): Promise<PackageUpdateStepResult> {
const startedAt = Date.now();
const targetLayout = resolveNpmGlobalPrefixLayoutFromGlobalRoot(params.installTarget.globalRoot, {
allowDirectNodeModulesRoot: params.installTarget.directNodeModulesRoot === true,
});
const targetPackageRoot = params.installTarget.packageRoot;
if (!targetLayout || !targetPackageRoot) {
return {
name: "global install swap",
command: "swap staged npm install",
cwd: params.stage.prefix,
durationMs: Date.now() - startedAt,
exitCode: 1,
stdoutTail: null,
stderrTail: "cannot resolve npm global prefix layout",
};
}
const backupRoot = path.join(targetLayout.globalRoot, `.openclaw-${process.pid}-${Date.now()}`);
let movedExisting = false;
let movedStaged = false;
let removedBackup = true;
try {
await fs.mkdir(targetLayout.globalRoot, { recursive: true });
if (await pathExists(targetPackageRoot)) {
await movePathWithCopyFallback({
from: targetPackageRoot,
sourceHardlinks: PACKAGE_MANAGER_SWAP_SOURCE_HARDLINKS,
to: backupRoot,
});
movedExisting = true;
}
await movePathWithCopyFallback({
from: params.stage.packageRoot,
sourceHardlinks: PACKAGE_MANAGER_SWAP_SOURCE_HARDLINKS,
to: targetPackageRoot,
});
movedStaged = true;
if (params.installTarget.directNodeModulesRoot !== true) {
await replaceNpmBinShims({
stageLayout: params.stage.layout,
targetLayout,
packageName: params.packageName,
});
}
if (movedExisting) {
removedBackup = await removePathBestEffort(backupRoot);
}
return {
name: "global install swap",
command: `swap ${params.stage.packageRoot} -> ${targetPackageRoot}`,
cwd: targetLayout.globalRoot,
durationMs: Date.now() - startedAt,
exitCode: 0,
stdoutTail: movedExisting
? removedBackup
? `replaced ${params.packageName}`
: `replaced ${params.packageName}; preserved old package at ${backupRoot} for delayed cleanup`
: `installed ${params.packageName}`,
stderrTail: null,
};
} catch (err) {
if (movedStaged) {
await removePathBestEffort(targetPackageRoot);
}
if (movedExisting) {
await movePathWithCopyFallback({
from: backupRoot,
sourceHardlinks: PACKAGE_MANAGER_SWAP_SOURCE_HARDLINKS,
to: targetPackageRoot,
}).catch(() => undefined);
}
return {
name: "global install swap",
command: `swap ${params.stage.packageRoot} -> ${targetPackageRoot}`,
cwd: targetLayout.globalRoot,
durationMs: Date.now() - startedAt,
exitCode: 1,
stdoutTail: null,
stderrTail: formatError(err),
};
}
}
/**
* Runs the global package update flow, including npm staging when possible,
* package verification, optional post-verification, and cleanup.
*/
export async function runGlobalPackageUpdateSteps(params: {
installTarget: ResolvedGlobalInstallTarget;
installSpec: string;
packageName: string;
packageRoot?: string | null;
runCommand: CommandRunner;
runStep: PackageUpdateStepRunner;
timeoutMs: number;
env?: NodeJS.ProcessEnv;
installCwd?: string;
postVerifyStep?: (packageRoot: string) => Promise<PackageUpdateStepResult | null>;
}): Promise<{
steps: PackageUpdateStepResult[];
verifiedPackageRoot: string | null;
afterVersion: string | null;
failedStep: PackageUpdateStepResult | null;
}> {
const installCwd = params.installCwd === undefined ? {} : { cwd: params.installCwd };
const installEnv = params.env === undefined ? {} : { env: params.env };
let stagedInstall: StagedNpmInstall | null | undefined;
let packedInstallDir: string | null = null;
try {
const preparedInstall = await prepareStagedNpmInstall(params.installTarget, params.packageName);
stagedInstall = preparedInstall.stagedInstall;
if (preparedInstall.failedStep) {
return {
steps: [preparedInstall.failedStep],
verifiedPackageRoot: params.packageRoot ?? null,
afterVersion: null,
failedStep: preparedInstall.failedStep,
};
}
const steps: PackageUpdateStepResult[] = [];
const installCommandTarget = stagedInstall?.installTarget ?? params.installTarget;
const preparedSpec = await prepareNpmGitSourceInstallSpec({
installTarget: installCommandTarget,
installSpec: params.installSpec,
packageName: params.packageName,
runStep: params.runStep,
timeoutMs: params.timeoutMs,
env: params.env,
installCwd: params.installCwd,
});
packedInstallDir = preparedSpec.packDir;
steps.push(...preparedSpec.steps);
if (preparedSpec.failedStep) {
return {
steps,
verifiedPackageRoot: params.packageRoot ?? null,
afterVersion: null,
failedStep: preparedSpec.failedStep,
};
}
const installLocation =
stagedInstall?.prefix ??
(installCommandTarget.manager === "pnpm"
? resolvePnpmGlobalDirFromGlobalRoot(installCommandTarget.globalRoot)
: null);
const updateStep = await params.runStep({
name: "global update",
argv: globalInstallArgs(
installCommandTarget,
preparedSpec.installSpec,
undefined,
installLocation,
),
...installCwd,
...installEnv,
timeoutMs: params.timeoutMs,
});
steps.push(updateStep);
let finalInstallStep = updateStep;
if (updateStep.exitCode !== 0) {
await cleanupStagedNpmInstall(stagedInstall);
stagedInstall = null;
const preparedFallbackInstall = await prepareStagedNpmInstall(
params.installTarget,
params.packageName,
);
stagedInstall = preparedFallbackInstall.stagedInstall;
if (preparedFallbackInstall.failedStep) {
steps.push(preparedFallbackInstall.failedStep);
return {
steps,
verifiedPackageRoot: params.packageRoot ?? null,
afterVersion: null,
failedStep: preparedFallbackInstall.failedStep,
};
}
const fallbackArgv = globalInstallFallbackArgs(
stagedInstall?.installTarget ?? params.installTarget,
preparedSpec.installSpec,
undefined,
stagedInstall?.prefix,
);
if (fallbackArgv) {
const fallbackStep = await params.runStep({
name: "global update (omit optional)",
argv: fallbackArgv,
...installCwd,
...installEnv,
timeoutMs: params.timeoutMs,
});
steps.push(fallbackStep);
finalInstallStep = fallbackStep;
} else {
await cleanupStagedNpmInstall(stagedInstall);
stagedInstall = null;
}
}
const livePackageRoot =
params.installTarget.packageRoot ??
params.packageRoot ??
(
await resolveGlobalInstallTarget({
manager: params.installTarget,
runCommand: params.runCommand,
timeoutMs: params.timeoutMs,
})
).packageRoot ??
null;
const verificationPackageRoot = stagedInstall?.packageRoot ?? livePackageRoot;
let verifiedPackageRoot = livePackageRoot ?? verificationPackageRoot;
let afterVersion: string | null = null;
if (finalInstallStep.exitCode === 0 && verificationPackageRoot) {
const candidateVersion = await readPackageVersion(verificationPackageRoot);
if (!stagedInstall) {
afterVersion = candidateVersion;
}
const expectedVersion = resolveExpectedInstalledVersionFromSpec(
params.packageName,
params.installSpec,
);
const verificationErrors = await collectInstalledGlobalPackageErrors({
packageRoot: verificationPackageRoot,
expectedVersion,
});
if (verificationErrors.length > 0) {
steps.push({
name: "global install verify",
command: `verify ${verificationPackageRoot}`,
cwd: verificationPackageRoot,
durationMs: 0,
exitCode: 1,
stderrTail: verificationErrors.join("\n"),
stdoutTail: null,
});
}
if (stagedInstall && verificationErrors.length === 0) {
const swapStep = await swapStagedNpmInstall({
stage: stagedInstall,
installTarget: params.installTarget,
packageName: params.packageName,
});
steps.push(swapStep);
if (swapStep.exitCode === 0) {
verifiedPackageRoot = params.installTarget.packageRoot ?? verifiedPackageRoot;
afterVersion = candidateVersion;
}
}
const failedVerifyOrSwap = steps.find(
(step) =>
(step.name === "global install verify" || step.name === "global install swap") &&
step.exitCode !== 0,
);
const postVerifyStep = failedVerifyOrSwap
? null
: verifiedPackageRoot
? await params.postVerifyStep?.(verifiedPackageRoot)
: null;
if (postVerifyStep) {
steps.push(postVerifyStep);
}
if (failedVerifyOrSwap && stagedInstall) {
afterVersion = await readPackageVersionIfPresent(livePackageRoot);
}
}
const failedStep = isBlockingPackageUpdateStep(finalInstallStep)
? finalInstallStep
: (steps.find((step) => step !== updateStep && isBlockingPackageUpdateStep(step)) ?? null);
return {
steps,
verifiedPackageRoot,
afterVersion,
failedStep,
};
} finally {
await cleanupStagedNpmInstall(stagedInstall ?? null);
if (packedInstallDir) {
await removePathBestEffort(packedInstallDir);
}
}
}