summaryrefslogtreecommitdiff
path: root/packages/cli/src/ui/utils/updateCheck.ts
blob: 2fe5df392298dce1ceaf58bbe2ac65ce0875070c (plain)
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import updateNotifier, { UpdateInfo } from 'update-notifier';
import semver from 'semver';
import { getPackageJson } from '../../utils/package.js';

export const FETCH_TIMEOUT_MS = 2000;

export interface UpdateObject {
  message: string;
  update: UpdateInfo;
}

export async function checkForUpdates(): Promise<UpdateObject | null> {
  try {
    // Skip update check when running from source (development mode)
    if (process.env.DEV === 'true') {
      return null;
    }

    const packageJson = await getPackageJson();
    if (!packageJson || !packageJson.name || !packageJson.version) {
      return null;
    }
    const notifier = updateNotifier({
      pkg: {
        name: packageJson.name,
        version: packageJson.version,
      },
      // check every time
      updateCheckInterval: 0,
      // allow notifier to run in scripts
      shouldNotifyInNpmScript: true,
    });
    // avoid blocking by waiting at most FETCH_TIMEOUT_MS for fetchInfo to resolve
    const timeout = new Promise<null>((resolve) =>
      setTimeout(resolve, FETCH_TIMEOUT_MS, null),
    );
    const updateInfo = await Promise.race([notifier.fetchInfo(), timeout]);

    if (updateInfo && semver.gt(updateInfo.latest, updateInfo.current)) {
      return {
        message: `Gemini CLI update available! ${updateInfo.current} → ${updateInfo.latest}`,
        update: updateInfo,
      };
    }

    return null;
  } catch (e) {
    console.warn('Failed to check for updates: ' + e);
    return null;
  }
}