├── .gitattributes ├── .gitignore ├── .babelrc ├── .github ├── demo.png └── workflows │ └── main.yml ├── .prettierrc ├── src ├── types.ts ├── borderedText.ts ├── isNpmOrYarn.ts ├── cache.spec.ts ├── index.spec.ts ├── getDistVersion.ts ├── getDistVersion.spec.ts ├── index.ts ├── cache.ts ├── hasNewVersion.ts └── hasNewVersion.spec.ts ├── rollup.config.js ├── tsconfig.json ├── LICENSE ├── CONTRIBUTING.md ├── CHANGELOG.md ├── README.md ├── package.json └── CODE_OF_CONDUCT.md /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | build/ 3 | package-lock.json 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-typescript"] 3 | } 4 | -------------------------------------------------------------------------------- /.github/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexbrazier/simple-update-notifier/HEAD/.github/demo.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "tabWidth": 2, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | export interface IUpdate { 2 | pkg: { name: string; version: string }; 3 | updateCheckInterval?: number; 4 | shouldNotifyInNpmScript?: boolean; 5 | distTag?: string; 6 | alwaysRun?: boolean; 7 | debug?: boolean; 8 | } 9 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import ts from 'rollup-plugin-ts'; 2 | 3 | const output = { 4 | format: 'cjs', 5 | file: './build/index.js', 6 | exports: 'default', 7 | }; 8 | 9 | const plugins = [ts()]; 10 | 11 | const config = { 12 | input: './src/index.ts', 13 | output, 14 | plugins, 15 | }; 16 | 17 | export default config; 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "esModuleInterop": true, 7 | "forceConsistentCasingInFileNames": true, 8 | "strict": true, 9 | "skipLibCheck": false, 10 | "outDir": "build", 11 | "declaration": true 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/borderedText.ts: -------------------------------------------------------------------------------- 1 | const borderedText = (text: string) => { 2 | const lines = text.split('\n'); 3 | const width = Math.max(...lines.map((l) => l.length)); 4 | const res = [`┌${'─'.repeat(width + 2)}┐`]; 5 | for (const line of lines) { 6 | res.push(`│ ${line.padEnd(width)} │`); 7 | } 8 | res.push(`└${'─'.repeat(width + 2)}┘`); 9 | return res.join('\n'); 10 | }; 11 | 12 | export default borderedText; 13 | -------------------------------------------------------------------------------- /src/isNpmOrYarn.ts: -------------------------------------------------------------------------------- 1 | import process from 'process'; 2 | 3 | const packageJson = process.env.npm_package_json; 4 | const userAgent = process.env.npm_config_user_agent; 5 | const isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); 6 | const isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); 7 | 8 | const isNpm = isNpm6 || isNpm7; 9 | const isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); 10 | const isNpmOrYarn = isNpm || isYarn; 11 | 12 | export default isNpmOrYarn; 13 | -------------------------------------------------------------------------------- /src/cache.spec.ts: -------------------------------------------------------------------------------- 1 | import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; 2 | 3 | createConfigDir(); 4 | 5 | jest.useFakeTimers().setSystemTime(new Date('2022-01-01')); 6 | 7 | const fakeTime = new Date('2022-01-01').getTime(); 8 | 9 | test('can save update then get the update details', () => { 10 | saveLastUpdate('test'); 11 | expect(getLastUpdate('test')).toBe(fakeTime); 12 | }); 13 | 14 | test('prefixed module can save update then get the update details', () => { 15 | saveLastUpdate('@alexbrazier/test'); 16 | expect(getLastUpdate('@alexbrazier/test')).toBe(fakeTime); 17 | }); 18 | -------------------------------------------------------------------------------- /src/index.spec.ts: -------------------------------------------------------------------------------- 1 | import simpleUpdateNotifier from '.'; 2 | import hasNewVersion from './hasNewVersion'; 3 | 4 | const consoleSpy = jest.spyOn(console, 'error'); 5 | 6 | jest.mock('./hasNewVersion', () => jest.fn().mockResolvedValue('2.0.0')); 7 | 8 | beforeEach(jest.clearAllMocks); 9 | 10 | test('it logs message if update is available', async () => { 11 | await simpleUpdateNotifier({ 12 | pkg: { name: 'test', version: '1.0.0' }, 13 | alwaysRun: true, 14 | }); 15 | 16 | expect(consoleSpy).toHaveBeenCalledTimes(1); 17 | }); 18 | 19 | test('it does not log message if update is not available', async () => { 20 | (hasNewVersion as jest.Mock).mockResolvedValue(false); 21 | await simpleUpdateNotifier({ 22 | pkg: { name: 'test', version: '2.0.0' }, 23 | alwaysRun: true, 24 | }); 25 | 26 | expect(consoleSpy).toHaveBeenCalledTimes(0); 27 | }); 28 | -------------------------------------------------------------------------------- /src/getDistVersion.ts: -------------------------------------------------------------------------------- 1 | import https from 'https'; 2 | 3 | const getDistVersion = async (packageName: string, distTag: string) => { 4 | const url = `https://registry.npmjs.org/-/package/${packageName}/dist-tags`; 5 | 6 | return new Promise((resolve, reject) => { 7 | https 8 | .get(url, (res) => { 9 | let body = ''; 10 | 11 | res.on('data', (chunk) => (body += chunk)); 12 | res.on('end', () => { 13 | try { 14 | const json = JSON.parse(body); 15 | const version = json[distTag]; 16 | if (!version) { 17 | reject(new Error('Error getting version')); 18 | } 19 | resolve(version); 20 | } catch { 21 | reject(new Error('Could not parse version response')); 22 | } 23 | }); 24 | }) 25 | .on('error', (err) => reject(err)); 26 | }); 27 | }; 28 | 29 | export default getDistVersion; 30 | -------------------------------------------------------------------------------- /src/getDistVersion.spec.ts: -------------------------------------------------------------------------------- 1 | import Stream from 'stream'; 2 | import https from 'https'; 3 | import getDistVersion from './getDistVersion'; 4 | 5 | jest.mock('https', () => ({ 6 | get: jest.fn(), 7 | })); 8 | 9 | test('Valid response returns version', async () => { 10 | const st = new Stream(); 11 | (https.get as jest.Mock).mockImplementation((url, cb) => { 12 | cb(st); 13 | 14 | st.emit('data', '{"latest":"1.0.0"}'); 15 | st.emit('end'); 16 | }); 17 | 18 | const version = await getDistVersion('test', 'latest'); 19 | 20 | expect(version).toEqual('1.0.0'); 21 | }); 22 | 23 | test('Invalid response throws error', async () => { 24 | const st = new Stream(); 25 | (https.get as jest.Mock).mockImplementation((url, cb) => { 26 | cb(st); 27 | 28 | st.emit('data', 'some invalid json'); 29 | st.emit('end'); 30 | }); 31 | 32 | expect(getDistVersion('test', 'latest')).rejects.toThrow( 33 | 'Could not parse version response' 34 | ); 35 | }); 36 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import isNpmOrYarn from './isNpmOrYarn'; 2 | import hasNewVersion from './hasNewVersion'; 3 | import { IUpdate } from './types'; 4 | import borderedText from './borderedText'; 5 | 6 | const simpleUpdateNotifier = async (args: IUpdate) => { 7 | if ( 8 | !args.alwaysRun && 9 | (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript)) 10 | ) { 11 | if (args.debug) { 12 | console.error('Opting out of running simpleUpdateNotifier()'); 13 | } 14 | return; 15 | } 16 | 17 | try { 18 | const latestVersion = await hasNewVersion(args); 19 | if (latestVersion) { 20 | console.error( 21 | borderedText(`New version of ${args.pkg.name} available! 22 | Current Version: ${args.pkg.version} 23 | Latest Version: ${latestVersion}`) 24 | ); 25 | } 26 | } catch (err) { 27 | // Catch any network errors or cache writing errors so module doesn't cause a crash 28 | if (args.debug && err instanceof Error) { 29 | console.error('Unexpected error in simpleUpdateNotifier():', err); 30 | } 31 | } 32 | }; 33 | 34 | export default simpleUpdateNotifier; 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Alex Brazier 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/cache.ts: -------------------------------------------------------------------------------- 1 | import os from 'os'; 2 | import path from 'path'; 3 | import fs from 'fs'; 4 | 5 | const homeDirectory = os.homedir(); 6 | const configDir = 7 | process.env.XDG_CONFIG_HOME || 8 | path.join(homeDirectory, '.config', 'simple-update-notifier'); 9 | 10 | const getConfigFile = (packageName: string) => { 11 | return path.join( 12 | configDir, 13 | `${packageName.replace('@', '').replace('/', '__')}.json` 14 | ); 15 | }; 16 | 17 | export const createConfigDir = () => { 18 | if (!fs.existsSync(configDir)) { 19 | fs.mkdirSync(configDir, { recursive: true }); 20 | } 21 | }; 22 | 23 | export const getLastUpdate = (packageName: string) => { 24 | const configFile = getConfigFile(packageName); 25 | 26 | try { 27 | if (!fs.existsSync(configFile)) { 28 | return undefined; 29 | } 30 | const file = JSON.parse(fs.readFileSync(configFile, 'utf8')); 31 | return file.lastUpdateCheck as number; 32 | } catch { 33 | return undefined; 34 | } 35 | }; 36 | 37 | export const saveLastUpdate = (packageName: string) => { 38 | const configFile = getConfigFile(packageName); 39 | 40 | fs.writeFileSync( 41 | configFile, 42 | JSON.stringify({ lastUpdateCheck: new Date().getTime() }) 43 | ); 44 | }; 45 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy 2 | on: 3 | push: 4 | branches: 5 | - 'master' 6 | pull_request: 7 | 8 | jobs: 9 | build: 10 | runs-on: ${{ matrix.os }} 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | node-version: [18.18.2] 15 | os: [ubuntu-latest, macOS-latest, windows-latest] 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Get yarn cache directory path 19 | id: yarn-cache-dir-path 20 | run: echo "::set-output name=dir::$(yarn cache dir)" 21 | 22 | - uses: actions/cache@v2 23 | id: yarn-cache 24 | with: 25 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 26 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 27 | restore-keys: | 28 | ${{ runner.os }}-yarn- 29 | 30 | - name: Install Node 31 | uses: actions/setup-node@v1 32 | with: 33 | node-version: ${{ matrix.node-version }} 34 | 35 | - name: Yarn Install 36 | run: yarn 37 | 38 | - name: Lint 39 | run: yarn lint 40 | 41 | - name: Test 42 | run: | 43 | yarn test 44 | 45 | - name: Build 46 | run: | 47 | yarn build 48 | -------------------------------------------------------------------------------- /src/hasNewVersion.ts: -------------------------------------------------------------------------------- 1 | import semver from 'semver'; 2 | import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; 3 | import getDistVersion from './getDistVersion'; 4 | import { IUpdate } from './types'; 5 | 6 | const hasNewVersion = async ({ 7 | pkg, 8 | updateCheckInterval = 1000 * 60 * 60 * 24, 9 | distTag = 'latest', 10 | alwaysRun, 11 | debug, 12 | }: IUpdate) => { 13 | createConfigDir(); 14 | const lastUpdateCheck = getLastUpdate(pkg.name); 15 | if ( 16 | alwaysRun || 17 | !lastUpdateCheck || 18 | lastUpdateCheck < new Date().getTime() - updateCheckInterval 19 | ) { 20 | const latestVersion = await getDistVersion(pkg.name, distTag); 21 | saveLastUpdate(pkg.name); 22 | if (semver.gt(latestVersion, pkg.version)) { 23 | return latestVersion; 24 | } else if (debug) { 25 | console.error( 26 | `Latest version (${latestVersion}) not newer than current version (${pkg.version})` 27 | ); 28 | } 29 | } else if (debug) { 30 | console.error( 31 | `Too recent to check for a new update. simpleUpdateNotifier() interval set to ${updateCheckInterval}ms but only ${ 32 | new Date().getTime() - lastUpdateCheck 33 | }ms since last check.` 34 | ); 35 | } 36 | 37 | return false; 38 | }; 39 | 40 | export default hasNewVersion; 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. 4 | 5 | ## Development workflow 6 | 7 | To get started with the project, run `yarn` in the root directory to install the required dependencies 8 | 9 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 10 | 11 | ```sh 12 | yarn build 13 | yarn lint 14 | ``` 15 | 16 | To fix formatting errors, run the following: 17 | 18 | ```sh 19 | yarn prettier 20 | ``` 21 | 22 | Remember to add tests for your change if possible. Run the unit tests by: 23 | 24 | ```sh 25 | yarn test 26 | ``` 27 | 28 | ### Linting and tests 29 | 30 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 31 | 32 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. 33 | 34 | ### Scripts 35 | 36 | The `package.json` file contains various scripts for common tasks: 37 | 38 | - `yarn lint`: lint files with ESLint. 39 | - `yarn test`: run unit tests with Jest. 40 | - `yarn build`: build the code for release. 41 | 42 | ### Sending a pull request 43 | 44 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). 45 | 46 | When you're sending a pull request: 47 | 48 | - Prefer small pull requests focused on one change. 49 | - Verify that linters and tests are passing. 50 | - Review the documentation to make sure it looks good. 51 | - Follow the pull request template when opening a pull request. 52 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 53 | 54 | ### Releasing 55 | 56 | > Maintainers only 57 | 58 | - Run `yarn release` 59 | - Update the changelog if required and follow the prompts 60 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [2.0.0](https://github.com/alexbrazier/simple-update-notifier/compare/v1.1.0...v2.0.0) (2023-06-26) 2 | 3 | ## BREAKING CHANGES 4 | 5 | - Bump semver version to avoid audit errors for users of the library (#19) 6 | - Min node version is now >= 10 7 | - If you already use a higher version of node then you can safely upgrade 8 | 9 | ## Other Updates 10 | 11 | - chore(deps): bump ua-parser-js from 1.0.2 to 1.0.33 (#17) 12 | - chore(deps): bump json5 from 2.2.1 to 2.2.3 (#18) 13 | - Update dev dependencies to latest (#21) 14 | - Force semver to latest version in for dev deps (#22) 15 | 16 | # [1.1.0](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.8...v1.1.0) (2022-11-24) 17 | 18 | Add debug flag to simpleUpdateNotifier() (#15) 19 | Use stderr, not stdout, for notification (#16) 20 | 21 | ## [1.0.8](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.7...v1.0.8) (2022-11-23) 22 | 23 | Adds support for vendor prefixed packages (#12) 24 | 25 | ## [1.0.7](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.6...v1.0.7) (2022-06-28) 26 | 27 | Downgrade semver to `7.0.0` to continue to support node 8 28 | 29 | ## [1.0.6](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.5...v1.0.6) (2022-06-27) 30 | 31 | Switch to using [semver](https://github.com/npm/node-semver) 32 | 33 | ## [1.0.5](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.4...v1.0.5) (2022-06-27) 34 | 35 | Handle prerelease versions 36 | 37 | ## [1.0.4](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.3...v1.0.4) (2022-06-26) 38 | 39 | Handle invalid version response and prerelease versions 40 | 41 | ## [1.0.3](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.2...v1.0.3) (2022-06-26) 42 | 43 | Add support for node 8 44 | 45 | ## [1.0.2](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.1...v1.0.2) (2022-06-24) 46 | 47 | Add bordered box around update notification 48 | 49 | ## [1.0.1](https://github.com/alexbrazier/simple-update-notifier/compare/v1.0.0...v1.0.1) (2022-06-24) 50 | 51 | Fix writing to cache and build for cjs 52 | 53 | # 1.0.0 (2022-06-23) 54 | 55 | Initial Release 56 | -------------------------------------------------------------------------------- /src/hasNewVersion.spec.ts: -------------------------------------------------------------------------------- 1 | import hasNewVersion from './hasNewVersion'; 2 | import { getLastUpdate } from './cache'; 3 | import getDistVersion from './getDistVersion'; 4 | 5 | jest.mock('./getDistVersion', () => jest.fn().mockReturnValue('1.0.0')); 6 | jest.mock('./cache', () => ({ 7 | getLastUpdate: jest.fn().mockReturnValue(undefined), 8 | createConfigDir: jest.fn(), 9 | saveLastUpdate: jest.fn(), 10 | })); 11 | 12 | const pkg = { name: 'test', version: '1.0.0' }; 13 | 14 | afterEach(() => jest.clearAllMocks()); 15 | 16 | const defaultArgs = { 17 | pkg, 18 | shouldNotifyInNpmScript: true, 19 | alwaysRun: true, 20 | }; 21 | 22 | test('it should not trigger update for same version', async () => { 23 | const newVersion = await hasNewVersion(defaultArgs); 24 | 25 | expect(newVersion).toBe(false); 26 | }); 27 | 28 | test('it should trigger update for patch version bump', async () => { 29 | (getDistVersion as jest.Mock).mockReturnValue('1.0.1'); 30 | 31 | const newVersion = await hasNewVersion(defaultArgs); 32 | 33 | expect(newVersion).toBe('1.0.1'); 34 | }); 35 | 36 | test('it should trigger update for minor version bump', async () => { 37 | (getDistVersion as jest.Mock).mockReturnValue('1.1.0'); 38 | 39 | const newVersion = await hasNewVersion(defaultArgs); 40 | 41 | expect(newVersion).toBe('1.1.0'); 42 | }); 43 | 44 | test('it should trigger update for major version bump', async () => { 45 | (getDistVersion as jest.Mock).mockReturnValue('2.0.0'); 46 | 47 | const newVersion = await hasNewVersion(defaultArgs); 48 | 49 | expect(newVersion).toBe('2.0.0'); 50 | }); 51 | 52 | test('it should not trigger update if version is lower', async () => { 53 | (getDistVersion as jest.Mock).mockReturnValue('0.0.9'); 54 | 55 | const newVersion = await hasNewVersion(defaultArgs); 56 | 57 | expect(newVersion).toBe(false); 58 | }); 59 | 60 | it('should trigger update check if last update older than config', async () => { 61 | const TWO_WEEKS = new Date().getTime() - 1000 * 60 * 60 * 24 * 14; 62 | (getLastUpdate as jest.Mock).mockReturnValue(TWO_WEEKS); 63 | const newVersion = await hasNewVersion({ 64 | pkg, 65 | shouldNotifyInNpmScript: true, 66 | }); 67 | 68 | expect(newVersion).toBe(false); 69 | expect(getDistVersion).toHaveBeenCalled(); 70 | }); 71 | 72 | it('should not trigger update check if last update is too recent', async () => { 73 | const TWELVE_HOURS = new Date().getTime() - 1000 * 60 * 60 * 12; 74 | (getLastUpdate as jest.Mock).mockReturnValue(TWELVE_HOURS); 75 | const newVersion = await hasNewVersion({ 76 | pkg, 77 | shouldNotifyInNpmScript: true, 78 | }); 79 | 80 | expect(newVersion).toBe(false); 81 | expect(getDistVersion).not.toHaveBeenCalled(); 82 | }); 83 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simple-update-notifier [![GitHub stars](https://img.shields.io/github/stars/alexbrazier/simple-update-notifier?label=Star%20Project&style=social)](https://github.com/alexbrazier/simple-update-notifier/stargazers) 2 | 3 | [![CI](https://github.com/alexbrazier/simple-update-notifier/workflows/Build%20and%20Deploy/badge.svg)](https://github.com/alexbrazier/simple-update-notifier/actions) 4 | [![Dependencies](https://img.shields.io/librariesio/release/npm/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier?activeTab=dependencies) 5 | [![npm](https://img.shields.io/npm/v/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) 6 | [![npm bundle size](https://img.shields.io/bundlephobia/min/simple-update-notifier)](https://bundlephobia.com/result?p=simple-update-notifier) 7 | [![npm downloads](https://img.shields.io/npm/dw/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) 8 | [![License](https://img.shields.io/npm/l/simple-update-notifier)](./LICENSE) 9 | 10 | Simple update notifier to check for npm updates for cli applications. 11 | 12 | Demo in terminal showing an update is required 13 | 14 | Checks for updates for an npm module and outputs to the command line if there is one available. The result is cached for the specified time so it doesn't check every time the app runs. 15 | 16 | ## Install 17 | 18 | ```bash 19 | npm install simple-update-notifier 20 | OR 21 | yarn add simple-update-notifier 22 | ``` 23 | 24 | ## Usage 25 | 26 | ```js 27 | import updateNotifier from 'simple-update-notifier'; 28 | import packageJson from './package.json' assert { type: 'json' }; 29 | 30 | updateNotifier({ pkg: packageJson }); 31 | ``` 32 | 33 | ### Options 34 | 35 | #### pkg 36 | 37 | Type: `object` 38 | 39 | ##### name 40 | 41 | _Required_\ 42 | Type: `string` 43 | 44 | ##### version 45 | 46 | _Required_\ 47 | Type: `string` 48 | 49 | #### updateCheckInterval 50 | 51 | Type: `number`\ 52 | Default: `1000 * 60 * 60 * 24` _(1 day)_ 53 | 54 | How often to check for updates. 55 | 56 | #### shouldNotifyInNpmScript 57 | 58 | Type: `boolean`\ 59 | Default: `false` 60 | 61 | Allows notification to be shown when running as an npm script. 62 | 63 | #### distTag 64 | 65 | Type: `string`\ 66 | Default: `'latest'` 67 | 68 | Which [dist-tag](https://docs.npmjs.com/adding-dist-tags-to-packages) to use to find the latest version. 69 | 70 | #### alwaysRun 71 | 72 | Type: `boolean`\ 73 | Default: `false` 74 | 75 | When set, `updateCheckInterval` will not be respected and a check for an update will always be performed. 76 | 77 | #### debug 78 | 79 | Type: `boolean`\ 80 | Default: `false` 81 | 82 | When set, logs explaining the decision will be output to `stderr` whenever the module opts to not print an update notification 83 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "simple-update-notifier", 3 | "version": "2.0.0", 4 | "description": "Simple update notifier to check for npm updates for cli applications", 5 | "main": "build/index.js", 6 | "types": "build/index.d.ts", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/alexbrazier/simple-update-notifier.git" 10 | }, 11 | "homepage": "https://github.com/alexbrazier/simple-update-notifier.git", 12 | "author": "alexbrazier", 13 | "license": "MIT", 14 | "engines": { 15 | "node": ">=10" 16 | }, 17 | "scripts": { 18 | "test": "jest src --noStackTrace", 19 | "build": "rollup -c rollup.config.js --bundleConfigAsCjs", 20 | "prettier:check": "prettier --check src/**/*.ts", 21 | "prettier": "prettier --write src/**/*.ts", 22 | "eslint": "eslint src/**/*.ts", 23 | "lint": "yarn prettier:check && yarn eslint", 24 | "prepare": "yarn lint && yarn build", 25 | "release": "release-it" 26 | }, 27 | "dependencies": { 28 | "semver": "^7.5.4" 29 | }, 30 | "devDependencies": { 31 | "@babel/preset-env": "^7.23.2", 32 | "@babel/preset-typescript": "^7.23.2", 33 | "@release-it/conventional-changelog": "^7.0.2", 34 | "@types/jest": "^29.5.6", 35 | "@types/node": "^20.8.7", 36 | "@typescript-eslint/eslint-plugin": "^6.9.0", 37 | "@typescript-eslint/parser": "^6.9.0", 38 | "eslint": "^8.52.0", 39 | "eslint-config-prettier": "^9.0.0", 40 | "eslint-plugin-prettier": "^5.0.1", 41 | "jest": "^29.7.0", 42 | "prettier": "^3.0.3", 43 | "release-it": "^17.2.0", 44 | "rollup": "^4.1.4", 45 | "rollup-plugin-ts": "^3.4.5", 46 | "typescript": "^5.2.2" 47 | }, 48 | "resolutions": { 49 | "semver": "^7.5.3" 50 | }, 51 | "publishConfig": { 52 | "registry": "https://registry.npmjs.org/" 53 | }, 54 | "files": [ 55 | "build", 56 | "src" 57 | ], 58 | "release-it": { 59 | "git": { 60 | "commitMessage": "chore: release ${version}", 61 | "tagName": "v${version}" 62 | }, 63 | "npm": { 64 | "publish": true 65 | }, 66 | "github": { 67 | "release": true 68 | }, 69 | "plugins": { 70 | "@release-it/conventional-changelog": { 71 | "preset": "angular", 72 | "infile": "CHANGELOG.md" 73 | } 74 | } 75 | }, 76 | "eslintConfig": { 77 | "plugins": [ 78 | "@typescript-eslint", 79 | "prettier" 80 | ], 81 | "extends": [ 82 | "prettier", 83 | "eslint:recommended", 84 | "plugin:@typescript-eslint/recommended" 85 | ], 86 | "parser": "@typescript-eslint/parser", 87 | "rules": { 88 | "prettier/prettier": [ 89 | "error", 90 | { 91 | "quoteProps": "consistent", 92 | "singleQuote": true, 93 | "tabWidth": 2, 94 | "trailingComma": "es5", 95 | "useTabs": false 96 | } 97 | ] 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | --------------------------------------------------------------------------------