1# nvm Coding Agent Instructions23This document provides guidance for AI coding agents when working with the Node Version Manager (nvm) codebase.45## Overview67nvm is a version manager for Node.js, implemented as a POSIX-compliant function that works across multiple shells (sh, dash, bash, ksh, zsh). The codebase is primarily written in shell script and emphasizes portability and compatibility.89### Core Architecture1011- **Main script**: `nvm.sh` - Contains all core functionality and the main `nvm()` function12- **Installation script**: `install.sh` - Handles downloading and installing nvm itself13- **Execution wrapper**: `nvm-exec` - Allows running commands with specific Node.js versions14- **Bash completion**: `bash_completion` - Provides tab completion for bash users15- **Tests**: Comprehensive test suite in `test/` directory using the [urchin](https://www.npmjs.com/package/urchin) test framework1617## Key Files and Their Purposes1819### `nvm.sh`20The core functionality file containing:21- Main `nvm()` function (starts around line 3000)22- All internal helper functions (prefixed with `nvm_`)23- Command implementations for install, use, ls, etc.24- Shell compatibility logic25- POSIX compliance utilities2627### `install.sh`28Handles nvm installation via curl/wget/git:29- Downloads nvm from GitHub30- Sets up directory structure31- Configures shell integration32- Supports both git clone and script download methods3334### `nvm-exec`35Simple wrapper script that:36- Sources nvm.sh with `--no-use` flag37- Switches to specified Node version via `NODE_VERSION` env var or `.nvmrc`38- Executes the provided command with that Node version3940## Top-Level nvm Commands and Internal Functions4142### Core Commands4344#### `nvm install [version]`45- **Internal functions**: `nvm_install_binary()`, `nvm_install_source()`, `nvm_download_artifact()`46- Downloads and installs specified Node.js version47- Automatically `nvm use`s that version after installation48- Supports LTS versions, version ranges, and built-in aliases (like `node`, `stable`) and user-defined aliases49- Can install from binary or compile from source50- When compiling from source, accepts additional arguments that are passed to the compilation task5152#### `nvm use [version]`53- **Internal functions**: `nvm_resolve_alias()`, `nvm_version_path()`, `nvm_change_path()`54- Switches current shell to use specified Node.js version55- Updates PATH environment variable56- Supports `.nvmrc` file integration5758#### `nvm ls [pattern]`59- **Internal functions**: `nvm_ls()`, `nvm_tree_contains_path()`60- Lists installed Node.js versions61- Supports pattern matching and filtering62- Shows current version and aliases6364#### `nvm ls-remote [pattern]`65- **Internal functions**: `nvm_ls_remote()`, `nvm_download()`, `nvm_ls_remote_index_tab()`66- Lists available Node.js versions from nodejs.org and iojs.org, or the env-var-configured mirrors67- Supports LTS filtering and pattern matching68- Downloads version index on-demand6970#### `nvm alias [name] [version]`71- **Internal functions**: `nvm_alias()`, `nvm_alias_path()`72- Creates text files containing the mapped version, named as the alias name73- Special aliases: `default`, `node`, `iojs`, `stable`, `unstable` (note: `stable` and `unstable` are deprecated, from node's pre-v1 release plan)74- Stored in `$NVM_DIR/alias/` directory7576#### `nvm current`77- **Internal functions**: `nvm_ls_current()`78- Shows currently active Node.js version79- Returns "system" if using system Node.js8081#### `nvm which [version]`82- **Internal functions**: `nvm_version_path()`, `nvm_resolve_alias()`83- Shows path to specified Node.js version84- Resolves aliases and version strings8586### Utility Commands8788#### `nvm cache clear|dir`89- Cache management for downloaded binaries and source code90- Clears or shows cache directory path9192#### `nvm debug`93- Diagnostic information for troubleshooting94- Shows environment, tool versions, and paths9596#### `nvm deactivate`97- Removes nvm modifications from current shell98- Restores original PATH99100#### `nvm unload`101- Completely removes nvm from shell environment102- Unsets all nvm functions and variables103104### Internal Function Categories105106#### Version Resolution107- `nvm_resolve_alias()` - Resolves aliases to version numbers108- `nvm_version()` - Finds best matching local version109- `nvm_remote_version()` - Finds best matching remote version110- `nvm_normalize_version()` - Standardizes version strings111- `nvm_version_greater()` - Compares version numbers112- `nvm_version_greater_than_or_equal_to()` - Version comparison with equality113- `nvm_get_latest()` - Gets latest version from a list114115#### Installation Helpers116- `nvm_install_binary()` - Downloads and installs precompiled binaries117- `nvm_install_source()` - Compiles Node.js from source118- `nvm_download_artifact()` - Downloads tarballs or binaries119- `nvm_compute_checksum()` - Verifies download integrity120- `nvm_checksum()` - Checksum verification wrapper121- `nvm_get_mirror()` - Gets appropriate download mirror122- `nvm_get_arch()` - Determines system architecture123124#### Path Management125- `nvm_change_path()` - Updates PATH for version switching126- `nvm_strip_path()` - Removes nvm paths from PATH127- `nvm_version_path()` - Gets installation path for version128- `nvm_version_dir()` - Gets version directory name129- `nvm_prepend_path()` - Safely prepends to PATH130131#### Shell Detection and Compatibility132- `nvm_is_zsh()` - Shell detection for zsh133- `nvm_is_iojs_version()` - Checks if version is io.js134- `nvm_get_os()` - Operating system detection135- `nvm_supports_source_options()` - Checks if shell supports source options136137#### Network and Remote Operations138- `nvm_download()` - Generic download function139- `nvm_ls_remote()` - Lists remote versions140- `nvm_ls_remote_iojs()` - Lists remote io.js versions141- `nvm_ls_remote_index_tab()` - Parses remote version index142143#### Utility Functions144- `nvm_echo()`, `nvm_err()` - Output functions145- `nvm_has()` - Checks if command exists146- `nvm_sanitize_path()` - Cleans sensitive data from paths147- `nvm_die_on_prefix()` - Validates npm prefix settings148- `nvm_ensure_default_set()` - Ensures default alias is set149- `nvm_auto()` - Automatic version switching from .nvmrc150151#### Alias Management152- `nvm_alias()` - Creates or lists aliases153- `nvm_alias_path()` - Gets path to alias file154- `nvm_unalias()` - Removes aliases155- `nvm_resolve_local_alias()` - Resolves local aliases156157#### Listing and Display158- `nvm_ls()` - Lists local versions159- `nvm_ls_current()` - Shows current version160- `nvm_tree_contains_path()` - Checks if path is in nvm tree161- `nvm_format_version()` - Formats version display162163## Running Tests164165### Test Framework166nvm uses the [urchin](https://www.npmjs.com/package/urchin) test framework for shell script testing.167168### Test Structure169```170test/171├── fast/ # Quick unit tests172├── slow/ # Integration tests173├── sourcing/ # Shell sourcing tests174├── install_script/ # Installation script tests175├── installation_node/ # Node installation tests176├── installation_iojs/ # io.js installation tests177└── common.sh # Shared test utilities178```179180### Running Tests181182#### Install Dependencies183```bash184npm install # Installs urchin, semver, and replace tools185```186187#### Run All Tests188```bash189npm test # Runs tests in the current shell only (sh, bash, dash, zsh)190make test # Runs tests in default shells (sh, bash, dash, zsh)191make test-sh # Runs tests only in sh192make test-bash # Runs tests only in bash193make test-dash # Runs tests only in dash194make test-zsh # Runs tests only in zsh195make SHELLS=ksh test # Runs tests only in ksh (experimental, see issue #574)196```197198#### Run Specific Test Suites199```bash200npm run test/fast # Runs fast tests in the current shell201npm run test/slow # Runs slow tests in the current shell202npm run test/sourcing # Runs sourcing tests in the current shell203npm run test/install_script # Runs install script tests in the current shell204npm run test/installation # Runs installation tests (node + iojs) in the current shell205npm run test/installation/node # Runs Node installation tests in the current shell206npm run test/installation/iojs # Runs io.js installation tests in the current shell207make TEST_SUITE=fast test # Only fast tests208make TEST_SUITE=slow test # Only slow tests209make SHELLS=bash test # Only bash shell210```211212#### Individual Test Execution213```bash214./test/fast/Unit\ tests/nvm_get_arch # Run single test (WARNING: This will exit/terminate your current shell session)215./node_modules/.bin/urchin test/fast/ # Run fast test suite216./node_modules/.bin/urchin 'test/fast/Unit tests/nvm_get_arch' # Run single test safely without shell termination217./node_modules/.bin/urchin test/slow/ # Run slow test suite218./node_modules/.bin/urchin test/sourcing/ # Run sourcing test suite219./node_modules/.bin/urchin test/install_script/ # Run install script test suite220./node_modules/.bin/urchin test/installation_node/ # Run Node installation test suite221./node_modules/.bin/urchin test/installation_iojs/ # Run io.js installation test suite222```223224#### Linting and Docs Checks225```bash226npm run eclint # Checks EditorConfig compliance227npm run doctoc:check # Verifies README table of contents228npm run dockerfile_lint # Lints the Dockerfile229npm run test:check-exec # Checks test files have executable permission230npm run test:check-nonexec # Checks non-test files don't have executable permission231npm run markdown-link-check # Validates markdown links (requires markdown-link-check)232```233234### Test Writing Guidelines235- Tests should work across all supported shells (sh, bash, dash, zsh, ksh)236- Define and use a `die()` function for test failures237- Clean up after tests in cleanup functions238- Mock external dependencies when needed239- Place mocks in `test/mocks/` directory240- Mock files should only be updated by the existing `update_test_mocks.sh` script, and any new mocks must be added to this script241242## Shell Environment Setup243244### Supported Shells245- **bash** - Full feature support246- **zsh** - Full feature support247- **dash** - Basic POSIX support248- **sh** - Basic POSIX support249- **ksh** - Limited support (experimental)250251### Installing Shell Environments252253#### Ubuntu/Debian254```bash255sudo apt-get update256sudo apt-get install bash zsh dash ksh257# sh is typically provided by dash or bash and is available by default258```259260#### macOS261```bash262# bash and zsh are available by default, bash is not the default shell for new user accounts263# Install other shells via Homebrew264brew install dash ksh265# For actual POSIX sh (not bash), install mksh which provides a true POSIX sh266brew install mksh267```268269#### Manual Shell Testing270```bash271# Test in specific shell272bash -c "source nvm.sh && nvm --version"273zsh -c "source nvm.sh && nvm --version"274dash -c ". nvm.sh && nvm --version"275sh -c ". nvm.sh && nvm --version" # On macOS: mksh -c ". nvm.sh && nvm --version"276ksh -c ". nvm.sh && nvm --version"277```278279### Shell-Specific Considerations280- **zsh**: Requires basically any non-default zsh option to be temporarily unset to restore POSIX compliance281- **dash**: Limited feature set, avoid bash-specific syntax282- **ksh**: Some features may not work, primarily for compatibility testing283284## CI Environment Details285286### GitHub Actions Workflows287288#### `.github/workflows/tests.yml`289- Runs test suite across multiple shells and test suites290- Uses `script` command for proper TTY simulation291- Matrix strategy covers shell × test suite combinations292- Excludes install_script tests from non-bash shells293294#### `.github/workflows/shellcheck.yml`295- Lints all shell scripts using shellcheck296- Tests against multiple shell targets (bash, sh, dash, ksh)297 - Note: zsh is not included due to [shellcheck limitations](https://github.com/koalaman/shellcheck/issues/809)298- Uses Homebrew to install latest shellcheck version299300#### `.github/workflows/lint.yml`301- Runs additional linting and formatting checks302- Validates documentation and code style303304### Travis CI (Legacy)305- Configured in `.travis.yml`306- Tests on multiple Ubuntu versions307- Installs shell environments via apt packages308309### CI Test Execution310```bash311# Simulate CI environment locally312unset TRAVIS_BUILD_DIR # Disable Travis-specific logic313unset GITHUB_ACTIONS # Disable GitHub Actions logic314make test315```316317## Setting Up shellcheck Locally318319### Installation320321#### macOS (Homebrew)322```bash323brew install shellcheck324```325326#### Ubuntu/Debian327```bash328sudo apt-get install shellcheck329```330331#### From Source332```bash333# Download from https://github.com/koalaman/shellcheck/releases334wget https://github.com/koalaman/shellcheck/releases/download/latest/shellcheck-latest.linux.x86_64.tar.xz335tar -xf shellcheck-latest.linux.x86_64.tar.xz336sudo cp shellcheck-latest/shellcheck /usr/local/bin/337```338339### Usage340341#### Lint Main Files342```bash343shellcheck -s bash nvm.sh344shellcheck -s bash install.sh345shellcheck -s bash nvm-exec346shellcheck -s bash bash_completion347```348349#### Lint Across Shell Types350```bash351shellcheck -s sh nvm.sh # POSIX sh352shellcheck -s bash nvm.sh # Bash extensions353shellcheck -s dash nvm.sh # Dash compatibility354shellcheck -s ksh nvm.sh # Ksh compatibility355```356357#### Common shellcheck Directives in nvm358- `# shellcheck disable=SC2039` - Allow bash extensions in POSIX mode359- `# shellcheck disable=SC2016` - Allow literal `$` in single quotes360- `# shellcheck disable=SC2001` - Allow sed usage instead of parameter expansion361- `# shellcheck disable=SC3043` - Allow `local` keyword (bash extension)362363### Fixing shellcheck Issues3641. **Quoting**: Always quote variables: `"${VAR}"` instead of `$VAR`3652. **POSIX compliance**: Avoid bash-specific features in portable sections3663. **Array usage**: Use `set --` for positional parameters instead of arrays, which are not supported in POSIX3674. **Local variables**: Declared with `local FOO` and then initialized on the next line (the latter is for ksh support)368369## Development Best Practices370371### Code Style372- Use 2-space indentation373- Follow POSIX shell guidelines for portability374- Prefix internal functions with `nvm_`375- Use `nvm_echo` instead of `echo` for output376- Use `nvm_err` for error messages377378### Compatibility379- Test changes across all supported shells380- Avoid bash-specific features in core functionality381- Use `nvm_is_zsh` to check when zsh-specific behavior is needed382- Mock external dependencies in tests383384### Performance385- Cache expensive operations (like remote version lists)386- Use local variables to avoid scope pollution387- Minimize subprocess calls where possible388- Implement lazy loading for optional features389390### Debugging391- Use `nvm debug` command for environment information392- Enable verbose output with `set -x` during development393- Test with `NVM_DEBUG=1` environment variable394- Check `$NVM_DIR/.cache` for cached data issues395396## Common Gotchas3973981. **PATH modification**: nvm modifies PATH extensively; be careful with restoration3992. **Shell sourcing**: nvm must be sourced, not executed as a script4003. **Version resolution**: Aliases, partial versions, and special keywords interact complexly4014. **Platform differences**: Handle differences between Linux, macOS, and other Unix systems4025. **Network dependencies**: Many operations require internet access for version lists4036. **Concurrent access**: Multiple shells can conflict when installing versions simultaneously404405## Windows Support406407nvm works on Windows via several compatibility layers:408409### WSL2 (Windows Subsystem for Linux)410- Full nvm functionality available411- **Important**: Ensure you're using WSL2, not WSL1 - see [Microsoft's WSL2 installation guide](https://docs.microsoft.com/en-us/windows/wsl/install) for up-to-date instructions412- Install Ubuntu or other Linux distribution from Microsoft Store413- Follow Linux installation instructions within WSL2414415### Cygwin416- POSIX-compatible environment for Windows417- Download Cygwin from [cygwin.com](https://www.cygwin.com/install.html) and run the installer418- During installation, include these packages: bash, curl, git, tar, and wget419- May require additional PATH configuration420421### Git Bash (MSYS2)422- Comes with Git for Windows423- Limited functionality compared to full Linux environment424- Some features may not work due to path translation issues, including:425 - Binary extraction paths may be incorrectly translated426 - Symlink creation may fail427 - Some shell-specific features may behave differently428 - File permissions handling differs from Unix systems429430### Setup Instructions for Windows431432#### WSL2 (recommended)4331. Install WSL2 using the official Microsoft guide: https://docs.microsoft.com/en-us/windows/wsl/install4342. Install Ubuntu or preferred Linux distribution from Microsoft Store4353. Follow standard Linux installation within WSL2436437#### Git Bash4381. Install Git for Windows (includes Git Bash) from https://git-scm.com/download/win4392. Open Git Bash terminal4403. Run nvm installation script441442#### Cygwin4431. Download and install Cygwin from https://www.cygwin.com/install.html4442. Include bash, curl, git, tar, and wget packages during installation4453. Run nvm installation in Cygwin terminal446447This guide should help AI coding agents understand the nvm codebase structure, testing procedures, and development environment setup requirements.448449<!-- BEGIN myr contribute (generated; content-hash: sha256:73bf524b145fbfc86f73c6bb0d86b0af4e22b06a5a42d87f0bb8ceccd80b4105) -->450## Contributing to github.com/nvm-sh/nvm451452This project takes changes through Myr: an answer to one of its asks lands only by passing the gate. This block is generated from the config folder, and the gate decides what lands. The full guide is the `nvm-contribute` skill (`.agents/skills/nvm-contribute/SKILL.md`).453454It needs the Myr CLI (the install script on the platform's `/install` page) signed in with `myr login --url <platform>`, and runs in a clone of the project, `git clone <platform>/github.com/nvm-sh/nvm.git`, where `<platform>` is the host this project lives on: in such a clone, `git remote get-url origin` names it.4554561. Read the ask, then claim it: `myr ask <ask>`, then `myr claim <ask>`. The claim prints your fork's remote; add it with `git remote add myr <remote>`.4572. Work inside the ask's territory until its check passes.4583. Run `myr check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.4594. Push your answer to your fork: `git push myr HEAD:main`. The push itself can be refused, on git's `remote:` lines.4605. Wait for the verdict: the rest of the checks run on the platform after git returns. Run `myr status --json` until your answer's `outcome._tag` is no longer `Checking`, then read the verdict on your head: `git fetch myr refs/notes/myr:refs/notes/myr`, then `git notes --ref=myr show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.461462- Change only files in the ask's territory; a push that changes anything else is refused with `OutOfScope`.463- Never change the judge closure (`.myr/**`, `**/.env.schema`, `**/.env.*`, `!**/.env.local`, `!**/.env.*.local`, `.github/workflows/**`, `.github/actions/**`, `.forgejo/**`, `**/vitest.config.*`, `**/vitest.*.config.*`, `**/vitest.workspace.*`, `**/vite.config.*`, `**/oxlint.config.*`, `**/oxlint.*.config.*`, `**/.oxlintrc*`, `**/eslint.config.*`, `**/eslint.*.config.*`, `**/.eslintrc*`, `**/tsconfig*.json`, `tools/oxlint/**`, `.agents/skills/*-contribute/**`, `.claude/skills/*-contribute/**`, `**/bunfig.toml`, `pnpm-workspace.yaml`, `**/turbo.json`, `**/turbo.jsonc`, `nx.json`, `.yarnrc.yml`, `.yarn/plugins/**`, `.yarn/releases/**`, `**/oxfmt.config.*`, `**/.oxfmtrc*`, `**/biome.json*`, `**/.prettierrc*`, `**/prettier.config.*`, `.claude/settings*.json`, `.cursor/hooks.json`, `.codex/hooks.json`, `.codex/config.toml`, `.github/hooks/*.json`, `.github/copilot/settings.json`, `.gemini/settings.json`, `.pi/**`, `.opencode/plugins/**`, `.amp/plugins/**`, `lefthook.yml`, `lefthook.yaml`, `.lefthook.yml`, `.lefthook.yaml`, `.lefthook/**`, `.husky/**`, `.pre-commit-config.yaml`, `package.json#/scripts`, `test/fast/Unit tests/mocks/project_dirs/inside-n_m-nested-pkg/node_modules/foo/package.json#/scripts`, `test/fast/Unit tests/mocks/project_dirs/nested-both/package.json#/scripts`, `test/fast/Unit tests/mocks/project_dirs/nested-pkg/package.json#/scripts`, `test/fast/Unit tests/mocks/project_dirs/no-nesting-both/package.json#/scripts`, `test/fast/Unit tests/mocks/project_dirs/no-nesting-pkg/package.json#/scripts`, `test/slow/nvm reinstall-packages/test-npmlink/package.json#/scripts`); a push that does is refused with `TouchedJudge`.464- Test one file with `npm test`. The lanes are `doctoc` (`npm run doctoc`) and `unit` (`npm test`).465- Every refusal has a `_tag`, `retryable` and `next`: run `next`. Add `--json` to any command for JSON.466467No fence yet: nothing checks these, so the gate won't refuse you for them.468469- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.470- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.471<!-- END myr contribute -->