tiny-updater
Version:
A small update notifier for NPM packages, useful for CLI apps.
45 lines (44 loc) ⢠1.35 kB
JavaScript
/* IMPORT */
import colors from 'tiny-colors';
import whenExit from 'when-exit';
import compare from './compare.js';
/* MAIN */
const Utils = {
/* API */
fetch: async (url) => {
const signal = Utils.getExitSignal();
const request = await fetch(url, { signal });
const json = await request.json();
return json;
},
getExitSignal: () => {
const aborter = new AbortController();
whenExit(() => aborter.abort());
return aborter.signal;
},
getLatestVersion: async (name) => {
const latestUrl = `https://registry.npmjs.org/${name}/latest`;
const latest = await Utils.fetch(latestUrl);
return latest.version;
},
isNumber: (value) => {
return typeof value === 'number';
},
isString: (value) => {
return typeof value === 'string';
},
isUpdateAvailable: (current, latest) => {
return compare(current, latest) === -1;
},
noop: () => {
return;
},
notify: (name, version, latest) => {
if (!globalThis.process?.stdout?.isTTY)
return; // Probably piping stdout
const log = () => console.log(`\n\nš¦ Update available for ${colors.cyan(name)}: ${colors.gray(version)} ā ${colors.green(latest)}`);
whenExit(log);
}
};
/* EXPORT */
export default Utils;