1
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
3
+import { dirname, join } from 'node:path';
4
+import { tmpdir } from 'node:os';
5
+import { withHttpServer } from 'test/__utils__/http-server';
6
+import {
7
+ createUpdateChecker,
8
+ parseLatestVersionFromRefs,
9
+ type UpdateCheckConfig,
10
+ type UpdateCheckState,
11
+} from 'src/services/update-check';
12
+
13
+// ── Helpers ─────────────────────────────────────────────────────────────
14
+
15
+/** Create a temp directory that is cleaned up after each test. */
16
+let tempDir: string;
17
+beforeEach(() => {
18
+ tempDir = mkdtempSync(join(tmpdir(), 'update-check-test-'));
19
+});
20
+afterEach(() => {
21
+ rmSync(tempDir, { recursive: true, force: true });
22
+});
23
+
24
+/** Build a test config pointing at a temp directory with optional overrides. */
25
+function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
26
+ return {
27
+ stateFile: join(tempDir, '.composio', 'update-check.json'),
28
+ currentVersion: '0.2.0',
29
+ checkIntervalMs: 24 * 60 * 60 * 1000,
30
+ refsUrl: 'http://unused.test',
31
+ accessToken: undefined,
32
+ fetchFn: () => Promise.reject(new Error('fetch not configured')),
33
+ ...overrides,
34
+ };
35
+}
36
+
37
+/** Write a state file to the test config's stateFile path. */
38
+function writeState(config: UpdateCheckConfig, state: UpdateCheckState): void {
39
+ mkdirSync(dirname(config.stateFile), { recursive: true });
40
+ writeFileSync(config.stateFile, JSON.stringify(state));
41
+}
42
+
43
+/** Create a GitHub matching-refs response body. */
44
+function makeRefsPayload(versions: string[]) {
45
+ return versions.map(v => ({
46
+ ref: `refs/tags/@composio/cli@${v}`,
47
+ node_id: 'unused',
48
+ url: 'unused',
49
+ object: { sha: 'abc', type: 'tag', url: 'unused' },
50
+ }));
51
+}
52
+
53
+// ── parseLatestVersionFromRefs (pure) ───────────────────────────────────
54
+
55
+describe('parseLatestVersionFromRefs', () => {
56
+ it('returns undefined for non-array input', () => {
57
+ expect(parseLatestVersionFromRefs(null)).toBeUndefined();
58
+ expect(parseLatestVersionFromRefs('string')).toBeUndefined();
59
+ expect(parseLatestVersionFromRefs(42)).toBeUndefined();
60
+ });
61
+
62
+ it('returns undefined when no refs match the CLI pattern', () => {
63
+ const refs = [
64
+ { ref: 'refs/tags/@composio/core@1.0.0' },
65
+ { ref: 'refs/tags/v1.0.0' },
66
+ { ref: 'refs/heads/main' },
67
+ ];
68
+ expect(parseLatestVersionFromRefs(refs)).toBeUndefined();
69
+ });
70
+
71
+ it('returns the single matching version', () => {
72
+ const refs = makeRefsPayload(['0.2.1']);
73
+ expect(parseLatestVersionFromRefs(refs)).toBe('0.2.1');
74
+ });
75
+
76
+ it('returns the highest semver, not the last element', () => {
77
+ // GitHub returns refs sorted lexicographically — 0.10.0 < 0.9.0 lexically
78
+ // but 0.10.0 > 0.9.0 in semver.
79
+ const refs = makeRefsPayload(['0.1.0', '0.10.0', '0.9.0', '0.2.0']);
80
+ expect(parseLatestVersionFromRefs(refs)).toBe('0.10.0');
81
+ });
82
+
83
+ it('excludes prerelease tags', () => {
84
+ const refs = [
85
+ { ref: 'refs/tags/@composio/cli@0.2.0' },
86
+ { ref: 'refs/tags/@composio/cli@0.3.0-beta.1' },
87
+ ];
88
+ expect(parseLatestVersionFromRefs(refs)).toBe('0.2.0');
89
+ });
90
+
91
+ it('skips malformed ref objects', () => {
92
+ const refs = [
93
+ null,
94
+ 42,
95
+ { noRef: true },
96
+ { ref: 123 },
97
+ { ref: 'refs/tags/@composio/cli@0.5.0' },
98
+ ];
99
+ expect(parseLatestVersionFromRefs(refs)).toBe('0.5.0');
100
+ });
101
+});
102
+
103
+// ── showUpdateNotice ────────────────────────────────────────────────────
104
+
105
+describe('showUpdateNotice', () => {
106
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
107
+ let stderrSpy: any;
108
+
109
+ beforeEach(() => {
110
+ stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
111
+ });
112
+
113
+ afterEach(() => {
114
+ stderrSpy.mockRestore();
115
+ });
116
+
117
+ it('does nothing when no state file exists', () => {
118
+ const { showUpdateNotice } = createUpdateChecker(makeConfig());
119
+
120
+ showUpdateNotice();
121
+
122
+ expect(stderrSpy).not.toHaveBeenCalled();
123
+ });
124
+
125
+ it('does nothing when cached version equals current version', () => {
126
+ const config = makeConfig({ currentVersion: '0.2.0' });
127
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
128
+ const { showUpdateNotice } = createUpdateChecker(config);
129
+
130
+ showUpdateNotice();
131
+
132
+ expect(stderrSpy).not.toHaveBeenCalled();
133
+ });
134
+
135
+ it('does nothing when cached version is older than current', () => {
136
+ const config = makeConfig({ currentVersion: '0.3.0' });
137
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
138
+ const { showUpdateNotice } = createUpdateChecker(config);
139
+
140
+ showUpdateNotice();
141
+
142
+ expect(stderrSpy).not.toHaveBeenCalled();
143
+ });
144
+
145
+ it('prints upgrade hint when cached version is newer', () => {
146
+ const config = makeConfig({ currentVersion: '0.2.0' });
147
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
148
+ const { showUpdateNotice } = createUpdateChecker(config);
149
+
150
+ showUpdateNotice();
151
+
152
+ expect(stderrSpy).toHaveBeenCalledOnce();
153
+ const output = stderrSpy.mock.calls[0][0] as string;
154
+ expect(output).toContain('Update available');
155
+ expect(output).toContain('0.3.0');
156
+ expect(output).toContain('composio upgrade');
157
+ });
158
+
159
+ it('silently ignores corrupt state file', () => {
160
+ const config = makeConfig();
161
+ mkdirSync(dirname(config.stateFile), { recursive: true });
162
+ writeFileSync(config.stateFile, 'not-json!!!');
163
+ const { showUpdateNotice } = createUpdateChecker(config);
164
+
165
+ showUpdateNotice();
166
+
167
+ expect(stderrSpy).not.toHaveBeenCalled();
168
+ });
169
+
170
+ it('does nothing when cached version is not valid semver', () => {
171
+ const config = makeConfig({ currentVersion: '0.2.0' });
172
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' });
173
+ const { showUpdateNotice } = createUpdateChecker(config);
174
+
175
+ showUpdateNotice();
176
+
177
+ expect(stderrSpy).not.toHaveBeenCalled();
178
+ });
179
+});
180
+
181
+// ── checkForUpdate ──────────────────────────────────────────────────────
182
+
183
+describe('checkForUpdate', () => {
184
+ it('skips fetch when cache is fresh', () => {
185
+ const fetchFn = vi.fn();
186
+ const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
187
+ writeState(config, {
188
+ lastChecked: new Date().toISOString(),
189
+ latestVersion: '0.2.0',
190
+ });
191
+ const { checkForUpdate } = createUpdateChecker(config);
192
+
193
+ const result = checkForUpdate();
194
+
195
+ expect(result).toBeUndefined(); // returned early, no promise
196
+ expect(fetchFn).not.toHaveBeenCalled();
197
+ });
198
+
199
+ it('fetches when cache is stale', async () => {
200
+ const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(); // 25 hours ago
201
+ const config = makeConfig({
202
+ fetchFn: vi.fn().mockResolvedValue({
203
+ ok: true,
204
+ json: () => Promise.resolve(makeRefsPayload(['0.3.0'])),
205
+ }) as unknown as typeof fetch,
206
+ });
207
+ writeState(config, { lastChecked: stale, latestVersion: '0.2.0' });
208
+ const { checkForUpdate } = createUpdateChecker(config);
209
+
210
+ await checkForUpdate();
211
+
212
+ expect(config.fetchFn).toHaveBeenCalledOnce();
213
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
214
+ expect(state.latestVersion).toBe('0.3.0');
215
+ });
216
+
217
+ it('fetches when no cache exists', async () => {
218
+ const config = makeConfig({
219
+ fetchFn: vi.fn().mockResolvedValue({
220
+ ok: true,
221
+ json: () => Promise.resolve(makeRefsPayload(['0.4.0', '0.3.0'])),
222
+ }) as unknown as typeof fetch,
223
+ });
224
+ const { checkForUpdate } = createUpdateChecker(config);
225
+
226
+ await checkForUpdate();
227
+
228
+ expect(existsSync(config.stateFile)).toBe(true);
229
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
230
+ expect(state.latestVersion).toBe('0.4.0');
231
+ });
232
+
233
+ it('fetches when cache file is corrupt', async () => {
234
+ const config = makeConfig({
235
+ fetchFn: vi.fn().mockResolvedValue({
236
+ ok: true,
237
+ json: () => Promise.resolve(makeRefsPayload(['0.5.0'])),
238
+ }) as unknown as typeof fetch,
239
+ });
240
+ mkdirSync(dirname(config.stateFile), { recursive: true });
241
+ writeFileSync(config.stateFile, 'garbage');
242
+ const { checkForUpdate } = createUpdateChecker(config);
243
+
244
+ await checkForUpdate();
245
+
246
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
247
+ expect(state.latestVersion).toBe('0.5.0');
248
+ });
249
+
250
+ it('does not write state when no CLI tags are found', async () => {
251
+ const config = makeConfig({
252
+ fetchFn: vi.fn().mockResolvedValue({
253
+ ok: true,
254
+ json: () => Promise.resolve([{ ref: 'refs/tags/@composio/core@1.0.0' }]),
255
+ }) as unknown as typeof fetch,
256
+ });
257
+ const { checkForUpdate } = createUpdateChecker(config);
258
+
259
+ await checkForUpdate();
260
+
261
+ expect(existsSync(config.stateFile)).toBe(false);
262
+ });
263
+
264
+ it('silently ignores HTTP errors', async () => {
265
+ const config = makeConfig({
266
+ fetchFn: vi.fn().mockResolvedValue({
267
+ ok: false,
268
+ status: 500,
269
+ }) as unknown as typeof fetch,
270
+ });
271
+ const { checkForUpdate } = createUpdateChecker(config);
272
+
273
+ // Should not throw
274
+ await checkForUpdate();
275
+
276
+ expect(existsSync(config.stateFile)).toBe(false);
277
+ });
278
+
279
+ it('silently ignores network errors', async () => {
280
+ const config = makeConfig({
281
+ fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
282
+ });
283
+ const { checkForUpdate } = createUpdateChecker(config);
284
+
285
+ await checkForUpdate();
286
+
287
+ expect(existsSync(config.stateFile)).toBe(false);
288
+ });
289
+
290
+ it('sends Authorization header when accessToken is set', async () => {
291
+ const fetchFn = vi.fn().mockResolvedValue({
292
+ ok: true,
293
+ json: () => Promise.resolve(makeRefsPayload(['0.2.1'])),
294
+ });
295
+ const config = makeConfig({
296
+ accessToken: 'ghp_secret123',
297
+ fetchFn: fetchFn as unknown as typeof fetch,
298
+ });
299
+ const { checkForUpdate } = createUpdateChecker(config);
300
+
301
+ await checkForUpdate();
302
+
303
+ expect(fetchFn).toHaveBeenCalledOnce();
304
+ const [, init] = fetchFn.mock.calls[0];
305
+ expect(init.headers.Authorization).toBe('Bearer ghp_secret123');
306
+ });
307
+
308
+ it('does not send Authorization header when accessToken is undefined', async () => {
309
+ const fetchFn = vi.fn().mockResolvedValue({
310
+ ok: true,
311
+ json: () => Promise.resolve(makeRefsPayload(['0.2.1'])),
312
+ });
313
+ const config = makeConfig({
314
+ accessToken: undefined,
315
+ fetchFn: fetchFn as unknown as typeof fetch,
316
+ });
317
+ const { checkForUpdate } = createUpdateChecker(config);
318
+
319
+ await checkForUpdate();
320
+
321
+ const [, init] = fetchFn.mock.calls[0];
322
+ expect(init.headers.Authorization).toBeUndefined();
323
+ });
324
+});
325
+
326
+// ── Integration: real HTTP server ───────────────────────────────────────
327
+
328
+describe('checkForUpdate with real HTTP', () => {
329
+ it('fetches from a real server and writes state', async () => {
330
+ await withHttpServer(
331
+ (_req, res) => {
332
+ res.writeHead(200, { 'Content-Type': 'application/json' });
333
+ res.end(JSON.stringify(makeRefsPayload(['0.1.26', '0.2.0', '0.2.1'])));
334
+ },
335
+ async baseUrl => {
336
+ const config = makeConfig({ refsUrl: baseUrl, fetchFn: fetch });
337
+ const { checkForUpdate } = createUpdateChecker(config);
338
+
339
+ await checkForUpdate();
340
+
341
+ const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
342
+ expect(state.latestVersion).toBe('0.2.1');
343
+ }
344
+ );
345
+ });
346
+
347
+ it('passes Authorization header to the server', async () => {
348
+ let receivedAuth: string | undefined;
349
+
350
+ await withHttpServer(
351
+ (req, res) => {
352
+ receivedAuth = req.headers.authorization;
353
+ res.writeHead(200, { 'Content-Type': 'application/json' });
354
+ res.end(JSON.stringify(makeRefsPayload(['0.2.1'])));
355
+ },
356
+ async baseUrl => {
357
+ const config = makeConfig({
358
+ refsUrl: baseUrl,
359
+ accessToken: 'ghp_test_token',
360
+ fetchFn: fetch,
361
+ });
362
+ const { checkForUpdate } = createUpdateChecker(config);
363
+
364
+ await checkForUpdate();
365
+
366
+ expect(receivedAuth).toBe('Bearer ghp_test_token');
367
+ }
368
+ );
369
+ });
370
+});