|
| 1 | +/* |
| 2 | + * Copyright 2025 Adobe. All rights reserved. |
| 3 | + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | + * of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + * |
| 7 | + * Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | + * OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | + * governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | +import fs from 'fs/promises'; |
| 13 | +import path from 'path'; |
| 14 | +import os from 'os'; |
| 15 | +import semver from 'semver'; |
| 16 | +import chalk from 'chalk-template'; |
| 17 | +import { xdgCache } from 'xdg-basedir'; |
| 18 | +import { getFetch } from './fetch-utils.js'; |
| 19 | + |
| 20 | +/** |
| 21 | + * Gets the path to the update check cache file using XDG base directories. |
| 22 | + * @returns {string} Path to the cache file |
| 23 | + */ |
| 24 | +function getUpdateCheckCacheFile() { |
| 25 | + const cacheDir = xdgCache || path.join(os.homedir(), '.cache'); |
| 26 | + return path.join(cacheDir, 'aem-cli', 'last-update-check'); |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Checks if we should skip the update check based on the last check time. |
| 31 | + * @returns {Promise<boolean>} True if we should skip the check |
| 32 | + */ |
| 33 | +async function shouldSkipUpdateCheck() { |
| 34 | + try { |
| 35 | + const cacheFile = getUpdateCheckCacheFile(); |
| 36 | + const stats = await fs.stat(cacheFile); |
| 37 | + const lastCheck = stats.mtime.getTime(); |
| 38 | + const now = Date.now(); |
| 39 | + const oneDayInMs = 24 * 60 * 60 * 1000; |
| 40 | + |
| 41 | + return (now - lastCheck) < oneDayInMs; |
| 42 | + } catch (error) { |
| 43 | + // If file doesn't exist or any other error, we should check |
| 44 | + return false; |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Updates the last update check timestamp. |
| 50 | + */ |
| 51 | +async function updateLastCheckTime() { |
| 52 | + try { |
| 53 | + const cacheFile = getUpdateCheckCacheFile(); |
| 54 | + const cacheDir = path.dirname(cacheFile); |
| 55 | + |
| 56 | + // Ensure cache directory exists |
| 57 | + await fs.mkdir(cacheDir, { recursive: true }); |
| 58 | + |
| 59 | + // Touch the file to update its mtime |
| 60 | + await fs.writeFile(cacheFile, Date.now().toString()); |
| 61 | + } catch (error) { |
| 62 | + // Silently ignore errors - this is not critical |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Checks if a newer version of the package is available on npm. |
| 68 | + * @param {string} packageName - The npm package name to check |
| 69 | + * @param {string} currentVersion - The current version of the package |
| 70 | + * @param {object} logger - Logger instance for outputting messages |
| 71 | + * @returns {Promise<void>} |
| 72 | + */ |
| 73 | +export async function checkForUpdates(packageName, currentVersion, logger) { |
| 74 | + try { |
| 75 | + // Check if we should skip the update check (rate limiting) |
| 76 | + if (await shouldSkipUpdateCheck()) { |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + const fetch = getFetch(); |
| 81 | + const controller = new AbortController(); |
| 82 | + const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout |
| 83 | + |
| 84 | + const response = await fetch(`https://registry.npmjs.org/${packageName}`, { |
| 85 | + signal: controller.signal, |
| 86 | + }); |
| 87 | + clearTimeout(timeoutId); |
| 88 | + |
| 89 | + if (!response.ok) { |
| 90 | + // Silently fail if we can't check for updates |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + const data = await response.json(); |
| 95 | + const latestVersion = data['dist-tags']?.latest; |
| 96 | + |
| 97 | + if (latestVersion && semver.gt(latestVersion, currentVersion)) { |
| 98 | + const boxWidth = 61; |
| 99 | + const updateMsg = `Update available! ${currentVersion} → ${latestVersion}`; |
| 100 | + const installMsg = `Run npm install -g ${packageName} to update`; |
| 101 | + |
| 102 | + // Use String.padEnd() instead of manual padding calculation |
| 103 | + const updatePadded = ` ${updateMsg}`.padEnd(boxWidth - 1); |
| 104 | + const installPadded = ` ${installMsg}`.padEnd(boxWidth - 1); |
| 105 | + |
| 106 | + logger.warn(''); |
| 107 | + logger.warn(chalk`{yellow ╭─────────────────────────────────────────────────────────────╮}`); |
| 108 | + logger.warn(chalk`{yellow │ │}`); |
| 109 | + logger.warn(chalk`{yellow │${updatePadded} │}`); |
| 110 | + logger.warn(chalk`{yellow │${installPadded} │}`); |
| 111 | + logger.warn(chalk`{yellow │ │}`); |
| 112 | + logger.warn(chalk`{yellow ╰─────────────────────────────────────────────────────────────╯}`); |
| 113 | + logger.warn(''); |
| 114 | + } |
| 115 | + |
| 116 | + // Update the last check time after a successful check |
| 117 | + await updateLastCheckTime(); |
| 118 | + } catch (error) { |
| 119 | + // Silently fail - don't block the command if update check fails |
| 120 | + // Only log in debug mode if available |
| 121 | + if (logger.level === 'debug' || logger.level === 'silly') { |
| 122 | + logger.debug(`Update check failed: ${error.message}`); |
| 123 | + } |
| 124 | + } |
| 125 | +} |
0 commit comments