### YAML Configuration Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Configuration example in YAML format. Defines upgrade, target, filter, reject, and install options. ```yaml upgrade: true target: minor filter: '^@myorg/' reject: - webpack install: always ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Example of a configuration file in JSON format. Specifies upgrade to true, target minor, filters, rejections, and installation behavior. ```json { "upgrade": true, "target": "minor", "filter": ["@myorg/*"], "reject": ["webpack"], "install": "always" } ``` -------------------------------- ### TypeScript Configuration Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Recommended configuration using TypeScript format. Imports defineConfig for defining upgrade, target, filter, reject, and install settings. ```typescript import { defineConfig } from 'npm-check-updates' export default defineConfig({ upgrade: true, target: 'minor', filter: /^@myorg\//, reject: ['webpack'], install: 'always' }) ``` -------------------------------- ### Install Beta npm-check-updates Version Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/MODULE_EXPORTS.md Installs a pre-release (beta) version of npm-check-updates using npm. ```bash npm install npm-check-updates@beta ``` -------------------------------- ### Install Figgy Pudding Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md Install the figgy-pudding library using npm. ```APIDOC ## Install Figgy Pudding `$ npm install figgy-pudding` ``` -------------------------------- ### Upgrade and Install Packages Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md This pattern upgrades packages, writes changes to the package file, and then automatically runs `npm install` to install the updated dependencies. ```typescript import { run } from 'npm-check-updates' await run({ packageFile: './package.json', upgrade: true, install: 'always' }) // Writes to package.json, then runs npm install ``` ```bash ncu -u && npm install ``` -------------------------------- ### Upgrade Package File Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md This example upgrades packages by modifying the `package.json` file. It sets the `upgrade` option to `true` and requires running `npm install` afterwards. ```typescript await run({ upgrade: true }) ``` -------------------------------- ### Install Next npm-check-updates Version Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/MODULE_EXPORTS.md Installs the next (beta) version of npm-check-updates using npm. ```bash npm install npm-check-updates@next ``` -------------------------------- ### Configuration File Example (.ncurc.ts) Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Demonstrates how to configure npm-check-updates using a configuration file, such as `.ncurc.ts`. This example sets the target version, filters, rejects packages, enables upgrades, and auto-installs. ```typescript // .ncurc.ts import { defineConfig } from 'npm-check-updates' export default defineConfig({ target: 'latest', filter: /^@scope/, reject: ['webpack'], upgrade: true, install: 'always' }) ``` -------------------------------- ### Index Type Examples Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Provides concrete examples of using the Index type for dependencies, upgraded versions, and fetch results. ```typescript // Package name → version spec const dependencies: Index = { react: "^18.0.0", express: "4.18.x" } // Package name → new version const upgraded: Index = { react: "18.2.0", express: "4.18.2" } // Package name → fetch result const results: Index = { react: { version: "18.2.0", time: "..." }, express: { version: null, error: "404 Not Found" } } ``` -------------------------------- ### Determine and Spawn Package Manager Install Command Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md Determines the appropriate package manager for installation and spawns the install command with the correct environment variables. ```typescript const packageManager = await getPackageManagerForInstall(options, pkgFile) await spawnCommand( packageManager, ['install'], // ... handlers for stdout/stderr { cwd: packageDirectory, env: { ...process.env, FORCE_COLOR: true } } ) ``` -------------------------------- ### Example PackageInfo Object Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md An example of a PackageInfo object, showing the package name, the PackageFile object, raw file content, and the file path. ```typescript { name: "app-root", pkg: { /* PackageFile object */ }, pkgFile: "{\"name\": \"app-root\", ...}", filepath: "/home/user/project/package.json" } ``` -------------------------------- ### Update and Install Packages Source: https://github.com/raineorshine/npm-check-updates/blob/main/skills/npm-check-updates/SKILL.md Update the package.json file with the latest versions and then install them using npm. This is the standard workflow for applying upgrades. ```bash # Write the upgrades back into package.json, then install. ncu -u npm install ``` -------------------------------- ### TargetFunction Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Example of a custom target version selection function. Selects 'latest' for packages starting with '@scope/' or '@types/', otherwise selects 'minor'. ```typescript const strategyByName = (name, range) => { if (name.startsWith('@scope/')) return 'latest' if (name.startsWith('@types/')) return 'latest' return 'minor' } ``` -------------------------------- ### Example Package.json Structure Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Illustrates a typical package.json file with common fields like name, version, dependencies, devDependencies, engines, and scripts. ```json { "name": "my-app", "version": "1.0.0", "dependencies": { "react": "^18.0.0", "express": "4.18.x" }, "devDependencies": { "typescript": "~5.0.0", "@types/node": "latest" }, "engines": { "node": ">=20.0.0", "npm": ">=10.0.0" }, "scripts": { "test": "jest", "build": "tsc" }, "peerDependencies": { "react": ">=16.0.0" } } ``` -------------------------------- ### Install Updated Packages Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md After upgrading the package.json file with 'ncu -u', run 'npm install' to update the installed packages and the package-lock.json file. ```sh $ npm install # update installed packages and package-lock.json ``` -------------------------------- ### Build and Distribution Commands Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/INDEX.md Commands for building the project, regenerating options, and type checking. Ensure you have Node.js and npm installed. ```bash npm run build # Build ESM/CJS npm run build:options # Regenerate options npm run typecheck # Type check ``` -------------------------------- ### npm API Implementation Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md An example implementation of the `PackageManager` interface for the npm registry, showing methods for fetching latest and greatest versions. ```typescript export const npmApi: PackageManager = { latest: async (name, options) => { // Query registry for latest version }, greatest: async (name, options) => { // Query registry for highest semver }, // ... other targets } ``` -------------------------------- ### GroupFunction Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Example of a custom grouping function. Groups packages starting with '@types/' into 'types' and packages containing 'webpack' into 'tooling'. ```typescript const customGroups = (name, defaultGroup) => { if (name.startsWith('@types/')) return 'types' if (name.includes('webpack')) return 'tooling' return defaultGroup } ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/CONFIGURATION.md Use this format for configuration files like .ncurc.yaml or .ncurc.yml. It allows specifying upgrade behavior, interactive prompts, rejected packages, and target versions. ```yaml upgrade: true interactive: true reject: - "@types/*" target: minor ``` -------------------------------- ### Package Manager Detection Examples Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md Provides examples of how to use the `run` function from npm-check-updates to automatically detect or explicitly specify the package manager for a project or workspaces. ```typescript import { run } from 'npm-check-updates' // Automatic detection await run({ packageFile: './package.json' // Detects from lock file presence }) // Explicit specification await run({ packageManager: 'pnpm', packageFile: './package.json' }) // For multiple workspaces with different managers await run({ workspaces: true // Each workspace's package manager auto-detected }) ``` -------------------------------- ### Example .ncurc.js Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/skills/npm-check-updates/SKILL.md Use a .ncurc.js file to configure ncu with predicate functions for filtering, specifying target versions, and setting cooldown periods. This example filters out internal packages and targets minor version updates. ```javascript export default { filter: name => !name.startsWith('internal-'), reject: ['@types/*'], target: 'minor', cooldown: 7, doctor: false, } ``` -------------------------------- ### GitHub Tags API Implementation Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md An example implementation of the `PackageManager` interface for fetching package versions from GitHub tags instead of the npm registry. ```typescript export const gitTagsApi: PackageManager = { latest: async (name, options) => { // Fetch GitHub tags instead } } ``` -------------------------------- ### spawnCommand(command, args, options, spawnOptions) Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Spawns a child process to execute a command, such as installing packages. It allows for custom handling of the child process's standard output and error streams. ```APIDOC ## spawnCommand(command, args, options, spawnOptions) ### Description Spawn a child process (like npm install). ### Parameters - **command** (string) - The command to execute. - **args** (string[]) - An array of arguments to pass to the command. - **options** ({ stdout?: (data: string) => void, stderr?: (data: string) => void }?) - Optional. An object with callbacks for handling stdout and stderr. - **spawnOptions** (SpawnOptions?) - Optional. Options to pass to the underlying Node.js spawn function. ### Returns - Promise - A promise that resolves when the command has finished executing. ``` -------------------------------- ### Install Latest npm-check-updates Version Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/MODULE_EXPORTS.md Installs the latest stable version of npm-check-updates using npm. ```bash npm install npm-check-updates@latest ``` -------------------------------- ### Install npm-check-updates Globally Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Install npm-check-updates globally to use the 'npm-check-updates' or 'ncu' commands. ```sh npm install -g npm-check-updates ``` -------------------------------- ### Interactive Mode with Auto-Install Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md Enable interactive mode with `install: 'always'` to automatically install selected upgrades after user selection. Requires `interactive: true` and `upgrade: true`. ```typescript import { run } from 'npm-check-updates' await run({ interactive: true, upgrade: true, install: 'always' }) // User selects packages, then auto-installs ``` -------------------------------- ### Example CooldownInfo Object Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md An example CooldownInfo object detailing a skipped upgrade for the 'react' package, including fallback information. ```typescript { name: "react", currentVersion: "18.1.0", currentVersionTime: "2024-01-01T...", version: "18.2.0", time: "2024-01-15T...", fallbackVersion: "18.1.5" } ``` -------------------------------- ### Peer Dependency Check Example (With --peer) Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Demonstrates how `--peer` ensures upgrades adhere to peer dependency constraints. In this case, `ncu-test-return-version` is upgraded to 1.1.0 to satisfy the peer dependency of `ncu-test-peer-update`. ```text ncu-test-peer-update 1.0.0 → 1.1.0 ncu-test-return-version 1.0.0 → 1.1.0 ``` -------------------------------- ### Example VersionResult Object Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md A sample VersionResult object showing a successfully fetched version and its publication time. ```typescript { version: "18.2.0", time: "2024-01-15T10:30:45.000Z" } ``` -------------------------------- ### Minimal Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/INDEX.md A basic configuration for npm-check-updates. Ensure 'npm-check-updates' is installed and imported. ```typescript import { defineConfig } from 'npm-check-updates' export default defineConfig({ upgrade: true }) ``` -------------------------------- ### Define a JSON Registry File Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Example structure for a `registry.json` file used with `npm-check-updates`. ```json { "prettier": "2.7.1", "typescript": "4.7.4" } ``` -------------------------------- ### Auto-Install After Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md This command first upgrades dependencies in package.json and then automatically runs `npm install` to apply the changes. ```bash # Auto-install after upgrade ncu -u && npm install ``` -------------------------------- ### CacheData Example Object Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md An example object conforming to the CacheData interface, illustrating how version information is stored. ```typescript { schema: "1", timestamp: 1705334445000, packages: { "react___latest": { version: "18.2.0", time: "2024-01-15T..." }, "typescript___@beta": { version: "5.4.0-beta.1", time: "2024-01-14T..." } }, peers: { "react@18": ["react-dom@18"] } } ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/CONFIGURATION.md This JSON format can be used in .ncurc.json or the 'ncu' key in package.json. It mirrors the YAML options for controlling updates. ```json { "upgrade": true, "interactive": true, "reject": ["@types/*"], "target": "minor" } ``` -------------------------------- ### Programmatic API: Interactive Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Initiate an interactive upgrade process using the `run` function with specific options. This allows for user-driven installation choices. ```typescript await run({ interactive: true, upgrade: true, install: 'always' }) ``` -------------------------------- ### Custom Doctor Install Script Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Specify a custom install script for the doctor command using the --doctorInstall flag. ```bash ncu --doctor -u --doctorInstall "yarn install" ``` -------------------------------- ### Example Custom Target Function Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/TYPES.md An example of a custom target function that selects 'minor' for scoped packages and 'patch' for others. This demonstrates how to implement custom version selection logic. ```typescript const customTarget = (name, range) => { // Use minor for packages, patch for everything else return name.startsWith('@scope/') ? 'minor' : 'patch' } ``` -------------------------------- ### CI/CD Integration Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/CONFIGURATION.md This configuration is suitable for CI/CD environments. It sets 'install' to 'never' to avoid automatic installations, uses 'errorLevel: 2' for stricter checks, and logs output minimally. ```typescript export default defineConfig({ errorLevel: 2, install: 'never', timeout: 60000, loglevel: 'minimal', jsonUpgraded: true }) ``` -------------------------------- ### Doctor Command Example Output Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Illustrates the output of the --doctor command when tests fail, showing the identification of broken dependencies. ```bash $ ncu --doctor -u Running tests before upgrading npm install npm run test Upgrading all dependencies and re-running tests ncu -u npm install npm run test Tests failed Identifying broken dependencies npm install npm install --no-save react@16.0.0 npm run test ✓ react 15.0.0 → 16.0.0 npm install --no-save react-redux@7.0.0 npm run test ✗ react-redux 6.0.0 → 7.0.0 /projects/myproject/test.js:13 throw new Error('Test failed!') ^ npm install --no-save react-dnd@11.1.3 npm run test ✓ react-dnd 10.0.0 → 11.1.3 Saving partially upgraded package.json ``` -------------------------------- ### Configuration File: Define Upgrades Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Create a `.ncurc.ts` file to configure npm-check-updates behavior. This example sets the upgrade target to 'latest' and filters for packages within a specific organization. ```typescript import { defineConfig } from 'npm-check-updates' export default defineConfig({ upgrade: true, target: 'latest', filter: /^@myorg/ }) ``` -------------------------------- ### npm Alias Package Definition Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md An example of how to define an npm alias in the `dependencies` section of a `package.json` file. ```json { "dependencies": { "lodash": "npm:lodash-es@^4.0.0" } } ``` -------------------------------- ### Resolving 'Install failed' Errors Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md Address peer dependency or postinstall script failures by filtering for peer-compatible versions, using doctor mode, or skipping auto-installation to review manually. ```typescript // Filter to peer-compatible versions await run({ peer: true, upgrade: true, install: 'always' }) ``` ```typescript // Or use doctor mode to find breaking changes await run({ doctor: true, upgrade: true }) ``` ```typescript // Or install manually after review await run({ upgrade: true, install: 'never' // Skip auto-install }) // User reviews changes, then runs: npm install ``` -------------------------------- ### Peer Dependency Check Example (Without --peer) Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Shows the default behavior without the `--peer` flag, where npm-check-updates suggests the latest versions, ignoring peer dependency constraints. `ncu-test-return-version` is upgraded to its latest version, 2.0.0. ```text ncu-test-peer-update 1.0.0 → 1.1.0 ncu-test-return-version 1.0.0 → 2.0.0 ``` -------------------------------- ### run(runOptions?, options?) Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/API_REFERENCE.md The primary function to execute npm-check-updates programmatically. It can be used to check for upgrades, perform upgrades, and install dependencies. ```APIDOC ## run(runOptions?, options?) ### Description The primary function to execute npm-check-updates programmatically. It can be used to check for upgrades, perform upgrades, and install dependencies. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Not Applicable (Function Call) ### Endpoint Not Applicable (Function Call) ### Parameters - **runOptions** (`RunOptions`) - Optional - Default: `{}` - Options to control all ncu behavior including filters, targets, package manager selection, and output format - **options.cli** (`boolean`) - Optional - Description: Internal flag indicating CLI invocation ### Return Type - `PackageFile` — Default returns the upgraded package file object - `Index` — When using `--jsonUpgraded`, returns only upgraded dependencies - `void` — When using `--global` upgrade ### Throws May reject if unhandled errors occur during execution. Errors are also logged before rejection. ### Example ```typescript import { run } from 'npm-check-updates' // Check for upgrades and display in console const result = await run() // Upgrade package file and auto-install const upgraded = await run({ packageFile: './package.json', upgrade: true, install: 'always' }) // Interactive mode with filter const selected = await run({ interactive: true, filter: /^@myorg/, }) ``` ``` -------------------------------- ### CooldownFunction Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Example of a custom cooldown function. Sets a '1d' cooldown for packages starting with '@scope/' and '7d' for others. ```typescript const conservativeCooldown = (name) => { if (name.startsWith('@scope/')) return '1d' return '7d' } ``` -------------------------------- ### Avoid Global Installs with Volta Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md When using Volta, avoid the `--global` flag with ncu. Volta manages global packages separately. ```bash # Remove Volta from PATH or use ncu without --global # Volta manages globals through its own system ncu # Check local package.json instead ``` -------------------------------- ### initOptions(runOptions, options?) Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Initializes and validates options, applies defaults, and loads configuration. This function merges `RunOptions` with config file options, applies defaults, validates values, initializes the cache provider, resolves file paths, and sets up the package manager. ```APIDOC ## initOptions(runOptions, options?) ### Description Initialize and validate options, apply defaults, and load config. ### Method N/A (Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **runOptions** (RunOptions) - Options provided by the user. - **options** (object) - Optional. Contains `cli?: boolean`. ### Returns Fully resolved `Options` object. ### Responsibilities: - Merges RunOptions with config file options - Applies built-in defaults - Validates option values - Initializes cache provider - Resolves file paths - Sets up package manager ``` -------------------------------- ### Safest Upgrade Path Workflow Source: https://github.com/raineorshine/npm-check-updates/blob/main/skills/npm-check-updates/SKILL.md A recommended workflow for upgrading dependencies safely. It involves committing changes, running ncu with a cooldown, writing updates, installing, and testing. ```shell ncu --cooldown 7 ncu -u npm install ``` -------------------------------- ### FilterFunction Examples Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Examples of custom filter functions. Use to skip packages starting with '@types/' or to only include minor or patch versions for non-major version 0 packages. ```typescript const skipDevDeps = (name) => !name.startsWith('@types/') const onlyMinorOrPatch = (name, range) => { const major = range[0]?.major return major !== 0 || name.includes('stable') } ``` -------------------------------- ### Instantiate Options with Multiple Providers Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md Illustrates how to create an options object from multiple providers, including plain objects and other figgy-pudding Opts objects. Demonstrates how properties are accessed and how nesting works. ```javascript const ReqOpts = figgyPudding({ follow: {}, }) const opts = ReqOpts({ follow: true, log: require('npmlog'), }) opts.follow // => true opts.log // => Error: ReqOpts does not define `log` const MoreOpts = figgyPudding({ log: {}, }) MoreOpts(opts).log // => npmlog object (passed in from original plain obj) MoreOpts(opts).follow // => Error: MoreOpts does not define `follow` ``` -------------------------------- ### Custom Registry Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/skills/npm-check-updates/SKILL.md Configure ncu to use a custom npm registry or a private mirror for checking dependencies. This example points to a custom npm registry. ```shell ncu --registry https://npm.example.com --packageManager npm ``` -------------------------------- ### CI/CD: Auto-Upgrade Patches Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Automate the upgrade of patch versions and then install them using npm. This is useful for maintaining minor dependencies without manual intervention. ```bash # Auto-upgrade patches only ncu --target patch -u && npm install ``` -------------------------------- ### Filter and Reject Packages for Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Allows selective upgrading of packages by specifying inclusion filters and exclusions. This example upgrades packages starting with '@myorg' but excludes 'webpack' and 'babel'. ```typescript await run({ filter: /^@myorg/, reject: ['webpack', 'babel'], upgrade: true }) ``` -------------------------------- ### Force Installation After Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md Configures npm-check-updates to always attempt installation after an upgrade, showing the helpful error message provided if the installation fails. ```typescript await run({ upgrade: true, install: 'always' }) // If install fails, shows helpful message: // "Install failed. This is not a bug in npm-check-updates. // The most common causes are invalid peer dependencies, // networking issues, or failing postinstall scripts. // Consider using --peer to filter updates to compatible // versions (takes longer) or --doctor to identify breaking upgrades." ``` -------------------------------- ### runGlobal Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Runs the upgrade logic for globally installed packages. It identifies global packages using `npm ls -g`, applies the same filtering as local packages, and returns the results as JSON. ```APIDOC ## runGlobal(options) ### Description Run upgrade logic on globally installed packages. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Returns `Promise>` — Map of global packages to new versions ### Behavior: - Uses `npm ls -g` to find global packages - Same filtering/targeting as local packages - Cannot write changes (npm global packages managed separately) - Returns JSON output for integration ``` -------------------------------- ### Show All CLI Options Source: https://github.com/raineorshine/npm-check-updates/blob/main/skills/npm-check-updates/SKILL.md Use this command to display all available command-line interface options for npm-check-updates. ```sh ncu --help ``` -------------------------------- ### run Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/MODULE_EXPORTS.md Primary entry point for programmatic usage. Executes the full upgrade detection and optional upgrade workflow. ```APIDOC ## run ### Description Primary entry point for programmatic usage. Executes the full upgrade detection and optional upgrade workflow. ### Method `async function` ### Signature ```typescript async function run( runOptions?: RunOptions, options?: { cli?: boolean } ): Promise | void> ``` ### Full Import Path `npm-check-updates` → `run` ### Availability ESM and CommonJS ### Example ```typescript import { run } from 'npm-check-updates' const result = await run({ upgrade: true }) ``` ``` -------------------------------- ### FilterResultsFunction Example Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/DATA_STRUCTURES.md Example of a filter results function. Includes only upgrades that represent a major version change. ```typescript const majorChangeOnly = (name, { upgradedVersionSemver }) => { return upgradedVersionSemver.major !== undefined } ``` -------------------------------- ### Include prerelease versions Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md By default, prerelease versions are ignored. Use the `--pre` flag to include them in the update process. ```text Prerelease versions are ignored by default. Use --pre to include prerelease versions (e.g. alpha, beta, build1235) ``` -------------------------------- ### Publish New Version Source: https://github.com/raineorshine/npm-check-updates/blob/main/deploy.md Use these commands to version, push to Git, and publish your package to npm. Optionally use a tag for unstable releases. ```bash npm version [minor] git push && git push --tags npm publish [--tag unstable] ``` -------------------------------- ### TypeScript Signature and Example: keyValueBy Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Defines the signature for creating an object map from an array. Provides a simple example of its usage. ```typescript function keyValueBy( array: readonly T[], keyProperty?: string ): Index ``` ```typescript keyValueBy(['react', 'vue']) // { react: 'react', vue: 'vue' } ``` -------------------------------- ### Define and Use Print Options with Figgy Pudding Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md Demonstrates how to define options with default values and use them to fetch and process package information. Options are automatically managed and passed down. ```javascript // print-package.js const fetch = require('./fetch.js') const puddin = require('figgy-pudding') const PrintOpts = puddin({ json: { default: false }, }) async function printPkg(name, opts) { // Expected pattern is to call this in every interface function. If `opts` is // not passed in, it will automatically create an (empty) object for it. opts = PrintOpts(opts) const uri = `https://registry.npmjs.com/${name}` const res = await fetch( uri, opts.concat({ // Add or override any passed-in configs and pass them down. log: customLogger, }), ) // The following would throw an error, because it's not in PrintOpts: // console.log(opts.log) if (opts.json) { return res.json() } else { return res.text() } } console.log( await printPkg('figgy', { // Pass in *all* configs at the toplevel, as a regular object. json: true, cache: './tmp-cache', }), ) ``` ```javascript // fetch.js const puddin = require('figgy-pudding') const FetchOpts = puddin({ log: { default: require('npmlog') }, cache: {} }) module.exports = async function (..., opts) { opts = FetchOpts(opts) } ``` -------------------------------- ### Check All Project Dependencies Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Check the latest versions of all project dependencies by running the 'ncu' command. This will display a list of packages with their current and available versions. ```sh $ ncu Checking package.json [====================] 5/5 100% eslint 7.32.0 → 8.0.0 prettier ^2.7.1 → ^3.0.0 svelte ^3.48.0 → ^3.51.0 typescript >3.0.0 → >4.0.0 untildify <4.0.0 → ^4.0.0 webpack 4.x → 5.x Run ncu -u to upgrade package.json ``` -------------------------------- ### Automated Patch Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/INDEX.md Automatically upgrade only patch versions of dependencies. The `install: 'always'` option ensures that the packages are installed after upgrading. ```typescript await run({ target: 'patch', upgrade: true, install: 'always' }) ``` -------------------------------- ### Check for Upgrades (Display Only) Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Use this command to see available upgrades without modifying any files. It's a safe way to preview changes. ```bash # Check for upgrades (display only) ncu ``` -------------------------------- ### Define Options with Aliases and Default Functions Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md Shows how to define an Options constructor using figgy-pudding, including key aliases and default values that are functions. ```javascript const MyAppOpts = figgyPudding({ lg: 'log', log: { default: () => require('npmlog'), }, cache: {}, }) ``` -------------------------------- ### Output as JSON Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Formats the upgrade information as a JSON object, suitable for programmatic consumption or integration with other tools. ```bash # Output as JSON ncu --jsonAll ``` -------------------------------- ### Interactive Selection for Upgrades Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Enables an interactive prompt to select which dependencies to upgrade. Useful for granular control over updates. ```bash # Interactive selection ncu -i -u ``` -------------------------------- ### Initialize Options Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Initializes and validates options, applying defaults and loading configuration. This function merges RunOptions with config file options, applies built-in defaults, validates values, initializes the cache provider, resolves file paths, and sets up the package manager. ```typescript async function initOptions( runOptions: RunOptions, options?: { cli?: boolean } ): Promise ``` -------------------------------- ### Check Global Packages Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Check for updates for globally installed npm packages using the '-g' flag. ```sh ncu -g ``` -------------------------------- ### Volta Package Manager Handling Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md Illustrates how to check for and handle cases where Volta is used as the package manager, particularly when the --global flag is not supported. Volta's unique global package management system requires specific handling. ```typescript const noVolta = (options: Options) => { if (options.global && (!!process.env.VOLTA_HOME || process.env.PATH?.includes('\Volta'))) { // Error: Volta uses its own system for managing global packages } } ``` -------------------------------- ### Filter packages to upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Use the `--filter` option or provide package names as arguments to specify which packages to upgrade. Multiple packages can be listed, separated by spaces or commas. ```sh # upgrade only mocha ncu mocha ncu -f mocha ncu --filter mocha ``` ```sh # upgrade only chalk, mocha, and react ncu chalk mocha react ncu chalk, mocha, react ncu -f "chalk mocha react" ``` -------------------------------- ### Upgrade Global Packages Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Use this command to upgrade globally installed npm packages. Ensure you have the necessary permissions. ```bash # Global packages ncu -g -u ``` -------------------------------- ### Monorepo Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/INDEX.md Configuration for monorepos, enabling workspace support and filtering out specific package types. Requires 'npm-check-updates' to be installed. ```typescript export default defineConfig({ workspaces: true, mergeConfig: true, filter: (name) => !name.startsWith('@types/'), target: 'minor' }) ``` -------------------------------- ### Upgrade and Write to File Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md This command upgrades dependencies and writes the changes directly to your package.json file. Use with caution. ```bash # Upgrade and write to file ncu -u ``` -------------------------------- ### TypeScript Signature: spawnCommand Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Defines the signature for spawning a child process. This is used for executing external commands like package installations. ```typescript async function spawnCommand( command: string, args: string[], options?: { stdout?: (data: string) => void, stderr?: (data: string) => void }, spawnOptions?: SpawnOptions ): Promise ``` -------------------------------- ### Production-Safe Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/INDEX.md Configuration suitable for production environments, targeting patch versions and including a cooldown period. Requires 'npm-check-updates' to be installed. ```typescript export default defineConfig({ target: 'patch', upgrade: true, cooldown: '7d', peer: true }) ``` -------------------------------- ### Define a FilterFunction Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/TYPES.md Use FilterFunction to exclude packages starting with '@types/'. This function is applied to the --filter and --reject options. ```typescript export type FilterFunction = (packageName: string, versionRange: SemVer[]) => boolean ``` ```typescript const filterFunction = (name, range) => { return !name.startsWith('@types/') } ``` -------------------------------- ### Validate Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md This snippet demonstrates how to initialize and log the resolved options for npm-check-updates. It helps verify that your configuration is being parsed and applied correctly. ```typescript import { getNcuRc } from './lib/getNcuRc' import { initOptions } from './lib/initOptions' const options = await initOptions({}) console.log('Resolved options:', options) ``` -------------------------------- ### Accessing Options Values Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md Demonstrates how to retrieve values from an options object using both the `.get()` method and direct property access via a Proxy. ```javascript const opts = MyOpts(config) opts.get('foo') // value of `foo` opts.foo // Proxy-based access through `.get()` ``` -------------------------------- ### Aggressive Development Configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/INDEX.md Configuration for aggressive development upgrades, targeting the latest versions and enabling interactive mode. Ensure 'npm-check-updates' is installed. ```typescript export default defineConfig({ target: 'latest', interactive: true, upgrade: true, install: 'always' }) ``` -------------------------------- ### Using a Specific Configuration File Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md Specify a custom configuration file name when running npm-check-updates from the command line. ```bash ncu --configFileName .ncurc.production.js -u ``` -------------------------------- ### Run npm-check-updates - Interactive Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Initiates an interactive upgrade process, allowing the user to select which packages to upgrade. Automatically installs the selected upgrades. ```typescript import { run } from 'npm-check-updates' const result = await run({ packageFile: './package.json', upgrade: true, interactive: true, install: 'always' }) // User chooses which packages to upgrade, then auto-installs ``` -------------------------------- ### Check Global Packages with npm-check-updates Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md Set the `global` option to `true` to check globally installed packages. Note that a global `package.json` cannot be directly written to. ```typescript import { run } from 'npm-check-updates' await run({ global: true, upgrade: true }) // Note: Cannot actually write global package.json ``` ```bash ncu -g -u ``` -------------------------------- ### Handling Errors with Try-Catch Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md Demonstrates how to use a try-catch block to handle potential errors during the upgrade process. Errors are logged to the console, and the process exits with code 1. ```typescript import { run } from 'npm-check-updates' try { const upgraded = await run({ packageFile: './package.json', upgrade: true }) console.log('Successfully upgraded:', upgraded) } catch (error) { console.error('Upgrade failed:', error.message) process.exit(1) } ``` -------------------------------- ### Interactive Mode via CLI Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md Use the `-i` and `-u` flags in the CLI to enable interactive mode for selecting package upgrades. ```bash ncu -i -u ``` -------------------------------- ### Enable Maximum Verbosity Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md Set the loglevel to 'silly' and verbose to true to get the most detailed output during a run. This is useful for understanding the internal workings of npm-check-updates. ```typescript await run({ loglevel: 'silly', verbose: true }) ``` -------------------------------- ### Get Options Values with values() Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md The `values()` method returns an iterator for values in options, limited to readable keys. This allows you to access only the values of the options. ```javascript const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).values()] // [1, 2] ``` -------------------------------- ### Programmatic Upgrade with run Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/MODULE_EXPORTS.md Use the 'run' function as the primary entry point for programmatically checking and applying package updates. Ensure 'npm-check-updates' is imported. ```typescript import { run } from 'npm-check-updates' const result = await run({ upgrade: true }) ``` -------------------------------- ### Upgrade Multiple Package Files Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/README.md Recursively searches for and upgrades dependencies in multiple package.json files within a project directory. ```bash # Multiple package files ncu --deep -u # or --packageFile '**\/package.json' -u ``` -------------------------------- ### Get Options Keys with keys() Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md The `keys()` method returns an iterator for keys in options, limited to readable keys. This is useful for retrieving only the names of the options. ```javascript const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).keys()] // ['x', 'y'] ``` -------------------------------- ### Configure pnpm Auto-Install Environment Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/PACKAGE_MANAGERS.md Disable strict peer dependency checking for pnpm to avoid conflicts during the auto-install process. ```typescript // Disable strict peer deps to avoid conflict env: { npm_config_strict_peer_dependencies: false } ``` -------------------------------- ### Set cooldown to 3 days (@beta target) Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Shows how cooldown interacts with the '@beta' target. No update is suggested if the current beta version is within the cooldown period. ```bash ncu --cooldown 3 --target @beta ``` -------------------------------- ### Programmatic cooldown configuration Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Provides an example of setting a custom cooldown predicate function in a .ncurc.js file. This allows for conditional cooldown periods based on package names. ```javascript /** Set cooldown to 3 days but skip it for `@my-company` packages. @param packageName The name of the dependency. @returns Cooldown days restriction for given package. */ cooldown: packageName => (packageName.startsWith('@my-company') ? 0 : 3) ``` -------------------------------- ### getNcuRc(options) Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/LIBRARY_FUNCTIONS.md Loads the `.ncurc` configuration file. It searches in locations specified by `--configFilePath`, the `packageFile` directory, and the current working directory and its parents, checking for various file names like `.ncurc`, `.ncurc.json`, etc. ```APIDOC ## getNcuRc(options) ### Description Load `.ncurc` configuration file. ### Method N/A (Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (Options) - Options object for the function. ### Returns Object with: - **config** (RcOptions) - Config object. - **path** (string) - Optional. File path if found. ### Search Locations: - Directory specified by `--configFilePath` - Directory of `packageFile` - Current working directory and parents ### File Names Checked (in order): 1. `.ncurc` 2. `.ncurc.json` 3. `.ncurc.yaml` / `.ncurc.yml` 4. `.ncurc.js` / `.ncurc.mjs` / `.ncurc.cjs` ``` -------------------------------- ### Check Specific Dependency Types with npm-check-updates Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md Specify an array of dependency types (e.g., 'dev', 'optional') to include in the check. This example includes both development and optional dependencies. ```typescript import { run } from 'npm-check-updates' await run({ dep: ['dev', 'optional'], upgrade: true }) ``` ```bash ncu --dep dev,optional -u ``` -------------------------------- ### Format output to show cooldown skips Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Demonstrates using '--format cooldown' to display packages skipped due to the cooldown threshold. This helps identify packages that were not updated because their latest versions were too recent. ```bash ncu --format cooldown --cooldown 7 ``` -------------------------------- ### Get Options Entries with entries() Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/lib/figgy-pudding/README.md The `entries()` method returns an iterator for key-value pairs in options, limited to readable keys. Each iteration yields an array `[key, value]`. ```javascript const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).entries()] // [['x', 1], ['y', 2]] ``` -------------------------------- ### Doctor Mode for Finding Breaking Changes Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/USAGE_PATTERNS.md Enable 'doctor' mode to test each potential upgrade and identify breaking changes. This mode requires specifying test and install commands. ```typescript import { run } from 'npm-check-updates' await run({ doctor: true, upgrade: true, doctorTest: 'npm test', doctorInstall: 'npm install' }) // Tests each upgrade to find breaking changes ``` ```bash ncu --doctor -u ``` -------------------------------- ### Package Manager Interface Source: https://github.com/raineorshine/npm-check-updates/blob/main/src/package-managers/README.md Implement this interface to add support for a new package manager. `list` and `latest` are required. Other methods are optional. All methods are expected to reject with '404 Not Found' if the package is not found. ```javascript { *list: (npmOptions: {}) => Promise<{ name: version } >, *latest: (pkgName: string) => Promise version, newest: (pkgName: string) => Promise version, greatest: (pkgName: string) => Promise version, minor: (pkgName: string, String currentVersion) => Promise version, patch: (pkgName: string, String currentVersion) => Promise version, } ``` -------------------------------- ### Set cooldown to 5 days (default target) Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Demonstrates the cooldown option with the default 'latest' target. If the latest version is within the cooldown period, it falls back to the greatest version that meets the threshold. ```bash ncu --cooldown 5 ``` -------------------------------- ### Handle File System Errors During Upgrade Source: https://github.com/raineorshine/npm-check-updates/blob/main/_autodocs/ERROR_HANDLING.md Provides a pattern for catching and differentiating common file system errors like permission denied (EACCES) and file not found (ENOENT) when attempting to upgrade packages. ```typescript try { await run({ packageFile: '/root/protected/package.json', upgrade: true }) } catch (err) { if (err.code === 'EACCES') { console.error('Permission denied') } else if (err.code === 'ENOENT') { console.error('File not found') } } ``` -------------------------------- ### Custom filterResults function for npm-check-updates Source: https://github.com/raineorshine/npm-check-updates/blob/main/README.md Use this function in your .ncurc.js or when importing npm-check-updates as a module to exclude upgrades after new versions have been fetched. This example excludes major version updates. ```javascript filterResults: (packageName, { current, currentVersionSemver, upgraded, upgradedVersionSemver }) => { const currentMajor = parseInt(currentVersionSemver[0]?.major, 10) const upgradedMajor = parseInt(upgradedVersionSemver?.major, 10) if (currentMajor && upgradedMajor) { return currentMajor >= upgradedMajor } return true } ```