Repository navigation
Expand file tree
/
Copy pathupdate-check.ts
More file actions
204 lines (180 loc) · 7.1 KB
/
Copy pathupdate-check.ts
File metadata and controls
204 lines (180 loc) · 7.1 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
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { runCmdDetached } from '@agent-device/host-kit/command';
import { compareVersions } from '@agent-device/host-kit/version';
const PACKAGE_NAME = 'agent-device';
const UPDATE_CHECK_INTERVAL_MS = 14 * 24 * 60 * 60 * 1000;
const UPDATE_CHECK_TIMEOUT_MS = 3500;
const UPDATE_CHECK_ARG = '--agent-device-run-update-check';
const UPDATE_CHECK_CACHE_FILE = 'update-check.json';
type UpdateCheckCache = {
checkedAt?: string;
/** The dist-tag `latestVersion` was read from; a cache from before channels means `latest`. */
distTag?: string;
latestVersion?: string;
prompted?: boolean;
};
export type UpgradeNotifierOptions = {
command: string | null;
currentVersion: string;
stateDir: string;
flags: {
help?: boolean;
json?: boolean;
version?: boolean;
};
};
type UpdateCheckWorkerOptions = {
cachePath: string;
currentVersion: string;
};
export function maybeRunUpgradeNotifier(options: UpgradeNotifierOptions): void {
if (!shouldEnableUpgradeNotifier(options)) return;
const now = Date.now();
const cachePath = path.join(options.stateDir, UPDATE_CHECK_CACHE_FILE);
const cache = readUpdateCheckCache(cachePath);
if (shouldShowUpgradeNotice(cache, options.currentVersion)) {
process.stderr.write(
`Update available: ${PACKAGE_NAME} ${options.currentVersion} -> ${cache.latestVersion}. ` +
`Run \`npm install -g ${PACKAGE_NAME}@${distTagFor(options.currentVersion)}\` to upgrade the CLI.\n`,
);
writeUpdateCheckCache(cachePath, {
...cache,
prompted: true,
});
}
if (shouldStartBackgroundCheck(cache, options.currentVersion, now)) {
spawnBackgroundUpdateCheck(cachePath, options.currentVersion);
}
}
export async function runUpdateCheckWorker(options: UpdateCheckWorkerOptions): Promise<void> {
const now = Date.now();
const cache = readUpdateCheckCache(options.cachePath);
const distTag = distTagFor(options.currentVersion);
try {
const latestVersion = (await fetchLatestPackageVersion(distTag)) ?? undefined;
if (!latestVersion || compareVersions(latestVersion, options.currentVersion) <= 0) {
writeUpdateCheckCache(options.cachePath, { checkedAt: new Date(now).toISOString(), distTag });
return;
}
writeUpdateCheckCache(options.cachePath, {
checkedAt: new Date(now).toISOString(),
distTag,
latestVersion,
prompted: cache.latestVersion === latestVersion ? cache.prompted === true : false,
});
} catch {
// A failed check still records this channel, so a channel switch waits out the interval
// instead of retrying on every command, and never keeps the other channel's version.
const kept = cachedDistTag(cache) === distTag ? cache : {};
writeUpdateCheckCache(options.cachePath, {
...kept,
checkedAt: new Date(now).toISOString(),
distTag,
});
}
}
function shouldEnableUpgradeNotifier(options: UpgradeNotifierOptions): boolean {
if (!options.command) return false;
if (options.command === 'help' || options.command === 'test') return false;
if (options.flags.help || options.flags.version || options.flags.json) return false;
if (process.env.CI?.trim()) return false;
if (process.env.NODE_ENV === 'test') return false;
if (process.env.AGENT_DEVICE_NO_UPDATE_NOTIFIER?.trim()) return false;
return Boolean(process.stderr.isTTY);
}
function shouldShowUpgradeNotice(cache: UpdateCheckCache, currentVersion: string): boolean {
if (!cache.latestVersion) return false;
if (cachedDistTag(cache) !== distTagFor(currentVersion)) return false;
if (compareVersions(cache.latestVersion, currentVersion) <= 0) return false;
return cache.prompted !== true;
}
function shouldStartBackgroundCheck(
cache: UpdateCheckCache,
currentVersion: string,
now: number,
): boolean {
if (cachedDistTag(cache) !== distTagFor(currentVersion)) return true;
const checkedAt = parseTimestamp(cache.checkedAt);
return checkedAt === undefined || now - checkedAt >= UPDATE_CHECK_INTERVAL_MS;
}
function readUpdateCheckCache(cachePath: string): UpdateCheckCache {
try {
const raw = JSON.parse(fs.readFileSync(cachePath, 'utf8')) as UpdateCheckCache;
return {
checkedAt: typeof raw.checkedAt === 'string' ? raw.checkedAt : undefined,
distTag: typeof raw.distTag === 'string' ? raw.distTag : undefined,
latestVersion: typeof raw.latestVersion === 'string' ? raw.latestVersion : undefined,
prompted: raw.prompted === true,
};
} catch {
return {};
}
}
function writeUpdateCheckCache(cachePath: string, cache: UpdateCheckCache): void {
try {
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
fs.writeFileSync(cachePath, `${JSON.stringify(cache, null, 2)}\n`, 'utf8');
} catch {
// Best effort only.
}
}
function resolveUpdateCheckEntryModulePath(): string {
const currentModulePath = fileURLToPath(import.meta.url);
const extension = path.extname(currentModulePath) || '.js';
const entryPaths = [
path.join(path.dirname(currentModulePath), `update-check-entry${extension}`),
path.join(path.dirname(currentModulePath), 'internal', `update-check-entry${extension}`),
];
const entryPath = entryPaths.find((candidate) => fs.existsSync(candidate));
if (!entryPath) {
throw new Error(
'Update check entrypoint not found. Rebuild the package to include the update-check worker entry.',
);
}
return entryPath;
}
function spawnBackgroundUpdateCheck(cachePath: string, currentVersion: string): void {
const modulePath = resolveUpdateCheckEntryModulePath();
const execArgs = modulePath.endsWith('.ts') ? ['--experimental-strip-types'] : [];
runCmdDetached(process.execPath, [
...execArgs,
modulePath,
UPDATE_CHECK_ARG,
cachePath,
currentVersion,
]);
}
function cachedDistTag(cache: UpdateCheckCache): string {
return cache.distTag ?? 'latest';
}
/** A nightly build follows the `nightly` dist-tag; every other build follows `latest`. */
function distTagFor(version: string): 'latest' | 'nightly' {
return version.includes('-nightly.') ? 'nightly' : 'latest';
}
async function fetchLatestPackageVersion(distTag: string): Promise<string | undefined> {
const response = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/${distTag}`, {
signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS),
headers: { accept: 'application/json' },
});
if (!response.ok) return undefined;
const payload = (await response.json()) as { version?: unknown };
return typeof payload.version === 'string' && payload.version.trim().length > 0
? payload.version.trim()
: undefined;
}
function parseTimestamp(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? undefined : parsed;
}
export function readUpdateCheckWorkerArgs(
argv: string[],
): { cachePath: string; currentVersion: string } | null {
if (argv[0] !== UPDATE_CHECK_ARG) return null;
const cachePath = argv[1]?.trim();
const currentVersion = argv[2]?.trim();
if (!cachePath || !currentVersion) return null;
return { cachePath, currentVersion };
}