### Example InstallSpec Configuration Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md An example of an InstallSpec for a specific Yarn version. This shows the installation location, binary mappings, and the computed hash. ```typescript const installed: InstallSpec = { location: '/home/user/.cache/node/corepack/v1/yarn/3.6.0', bin: { yarn: 'bin/yarn.js' }, hash: 'sha512.abcd1234567890...' }; ``` -------------------------------- ### Corepack Debug Output Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/configuration.md Example of the debug output generated when the DEBUG=corepack environment variable is set, showing the process of finding and installing a package manager. ```text Searching for package manager specification... Found yarn@3.6.0 in package.json Download and install of yarn@3.6.0 is finished ``` -------------------------------- ### Example Debug Output Source: https://github.com/nodejs/corepack/blob/main/_autodocs/errors.md Sample debug output from Corepack, illustrating the information captured during package installation, including version resolution and verification. ```text Search for default version: Looking for yarn@... Search for default version: found in remote registry yarn@4.0.1 Download and install of yarn@4.0.1 is finished Setting yarn@4.0.1+sha224... as Last Known Good version ``` -------------------------------- ### Enable Corepack Installation Source: https://github.com/nodejs/corepack/blob/main/README.md Run this command to install the required Yarn and pnpm binaries on your path. This is the default method for versions 14.19.0 up to (but not including) 25.0.0. ```shell corepack enable ``` -------------------------------- ### Hash Mismatch Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/errors.md Provides a comment illustrating a hash mismatch scenario during package installation. This occurs when the downloaded file's integrity verification fails against the expected hash. ```typescript // Installed package hash doesn't match expected: // Expected: sha512.abcd1234 // Got: sha512.efgh5678 ``` -------------------------------- ### Example LocalEnvFile Usage Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md An example of how to declare and initialize a LocalEnvFile object with common Corepack environment variables. ```typescript const env: LocalEnvFile = { 'COREPACK_ENABLE_NETWORK': '0', 'COREPACK_HOME': '/custom/cache', 'DEBUG': 'corepack' }; ``` -------------------------------- ### Locator Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/README.md Shows an exact, resolved package manager reference. This always specifies a particular version. ```javascript { name: 'yarn', reference: '3.6.0' } ``` -------------------------------- ### Install Global Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Installs package managers globally and sets them as system defaults. This command can install specific versions, use tags like 'latest', or install from offline tarballs. It caches the package manager and activates it unless the --cache-only flag is used. ```bash corepack install -g yarn@^1 ``` ```bash corepack install -g pnpm ``` ```bash corepack install -g --cache-only yarn@3.6.0 ``` ```bash corepack install -g --cache-only /path/to/corepack.tgz ``` -------------------------------- ### Get Install Folder (TypeScript) Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-utilties.md Returns the path to the versioned install folder where package managers are cached. The version is hardcoded to 'v1' to prevent conflicts with older installations. ```typescript const installFolder = folderUtils.getInstallFolder(); // Returns: '/home/user/.cache/node/corepack/v1' ``` -------------------------------- ### Locator Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Shows how to define a Locator with a specific version and a content hash. ```typescript const resolved: Locator = { name: 'yarn', reference: '3.6.0+sha224.953c8233f7a92884eee2de69a1b92d1f2ec1655e66d08071ba9a02fa' }; ``` -------------------------------- ### Descriptor Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/README.md Illustrates a user-specified package manager with a version range. This can represent a version range, tag, or custom URL. ```javascript { name: 'yarn', range: '^3.0.0' } ``` -------------------------------- ### Install Package Manager Version Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Downloads and installs a specified package manager version to the cache, handling integrity verification and metadata creation. Use this to prepare a package manager for execution. ```typescript const installed = await corepackUtils.installVersion( '/home/user/.cache/node/corepack/v1', { name: 'yarn', reference: '3.6.0' }, { spec: packageManagerSpec } ); // Returns: { // location: '/home/user/.cache/node/corepack/v1/yarn/3.6.0', // bin: { yarn: 'bin/yarn.js', yarnpkg: 'bin/yarn.js' }, // hash: 'sha512.abcd1234...' // } ``` -------------------------------- ### LazyLocator Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Demonstrates creating a LazyLocator where the package manager version is fetched asynchronously. ```typescript const lazy: LazyLocator = { name: 'yarn', reference: async () => { return await engine.getDefaultVersion('yarn'); } }; ``` -------------------------------- ### Example .corepack.env Configuration Source: https://github.com/nodejs/corepack/blob/main/_autodocs/configuration.md Configure network settings, offline builds, security, and debugging for Corepack using shell-style environment variables in a .corepack.env file. ```bash # Network configuration COREPACK_NPM_REGISTRY=https://registry.company.com COREPACK_NPM_TOKEN=npm_secret123 # Offline builds COREPACK_ENABLE_NETWORK=0 # Security COREPACK_INTEGRITY_KEYS=0 # Debug DEBUG=corepack ``` -------------------------------- ### Example PackageManagerSpec Configuration Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md An example of how to configure the PackageManagerSpec for Yarn. This includes the URL template, binary mappings, registry details, and post-install commands. ```typescript const spec: PackageManagerSpec = { url: 'https://registry.npmjs.org/@yarnpkg/cli-dist/-/cli-dist-{}.tgz', bin: { yarn: 'bin/yarn.js', yarnpkg: 'bin/yarn.js' }, registry: { type: 'npm', package: '@yarnpkg/cli-dist' }, commands: { use: ['yarn', 'install'] } }; ``` -------------------------------- ### Ensure Package Manager Installation Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Ensures a package manager version is installed. Downloads it if not already cached, verifies integrity, and returns installation information. Use this to guarantee a specific package manager version is available. ```typescript const info = await engine.ensurePackageManager({ name: 'yarn', reference: '3.6.0' }); // Returns: { // location: '/home/user/.cache/node/corepack/v1/yarn/3.6.0', // bin: ['yarn', 'yarnpkg'], // hash: 'sha512.abcd1234...', // locator: { name: 'yarn', reference: '3.6.0+sha224...' }, // spec: {...} // } ``` -------------------------------- ### Information about an Installed Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Use InstallSpec to represent information about an installed package manager. It includes the absolute path to the installation directory, optional binary definitions, and a hash for verification. ```typescript export interface InstallSpec { location: string; // Absolute path to installation directory bin?: BinList | BinSpec; // Binary definitions (optional) hash: string; // Format: "algo.hexdigest" } ``` -------------------------------- ### Enable Package Manager Shims Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Installs package manager shims to a system directory. You can enable all shims or specify individual package managers. The installation directory can also be customized. ```bash # Enable all shims next to corepack binary corepack enable ``` ```bash # Enable specific shims in custom directory corepack enable --install-directory /usr/local/bin yarn pnpm ``` ```bash # Enable only Yarn shims corepack enable yarn ``` -------------------------------- ### Install Corepack using npm Source: https://github.com/nodejs/corepack/blob/main/README.md Install Corepack globally using npm. Note that this method has an overhead, and using the version distributed with Node.js is preferred. ```shell npm install -g corepack ``` -------------------------------- ### installVersion Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Downloads and installs a specified package manager version to the cache, handling integrity verification and metadata creation. ```APIDOC ## async installVersion(installTarget: string, locator: Locator, options: {spec: PackageManagerSpec}): Promise ### Description Downloads and installs a package manager version to the cache. Handles integrity verification, binary extraction, and corepack metadata creation. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **installTarget** (`string`) - Required - Root cache directory - **locator** (`Locator`) - Required - Package manager and version to install - **options.spec** (`PackageManagerSpec`) - Required - Specification for downloading ### Returns - `Promise` — Installation details including location, bin paths, and hash ### Throws - `Error` - File not found in tarball at expected binPath - `Error` - Hash mismatch (integrity verification failed) - `Error` - Unable to locate bin in package.json ### Environment Variables - `COREPACK_DEFAULT_TO_LATEST`: If not "0", auto-updates LastKnownGood for same major version - `COREPACK_NPM_REGISTRY`: Override npm registry URL - `COREPACK_INTEGRITY_KEYS`: Custom integrity keys or "0" to disable verification ### Example ```typescript const installed = await corepackUtils.installVersion( '/home/user/.cache/node/corepack/v1', { name: 'yarn', reference: '3.6.0' }, { spec: packageManagerSpec } ); // Returns: { // location: '/home/user/.cache/node/corepack/v1/yarn/3.6.0', // bin: { yarn: 'bin/yarn.js', yarnpkg: 'bin/yarn.js' }, // hash: 'sha512.abcd1234...' // } ``` ``` -------------------------------- ### getInstallFolder() Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-utilties.md Returns the path to the versioned installation directory where package managers are cached. The version is currently hardcoded to 'v1' to ensure schema changes do not affect older installations. ```APIDOC ## getInstallFolder() ### Description Returns the versioned install folder path where package managers are cached. The versioning allows for schema updates without breaking compatibility with older installations. ### Returns - `string` — Absolute path to install directory ### Note Version is currently hardcoded to `v1`. Incrementing allows schema changes without conflicting with old installations. ### Example ```typescript const installFolder = folderUtils.getInstallFolder(); // Returns: '/home/user/.cache/node/corepack/v1' ``` ``` -------------------------------- ### Descriptor Examples Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Illustrates various ways to define a Descriptor, including exact versions, ranges, tags, and custom URLs. ```typescript // Exact version const desc1: Descriptor = { name: 'yarn', range: '3.6.0' }; // Version range const desc2: Descriptor = { name: 'pnpm', range: '^8.0.0' }; // Tag const desc3: Descriptor = { name: 'npm', range: 'latest' }; // Custom URL const desc4: Descriptor = { name: 'yarn', range: 'https://example.com/yarn.tgz' }; ``` -------------------------------- ### Example Corepack Configuration Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Illustrates a partial Corepack configuration object, showing the structure for npm, yarn, and pnpm definitions, including default versions and version ranges. ```typescript const config: Config = { definitions: { npm: { default: '10.5.0', fetchLatestFrom: { type: 'npm', package: 'npm' }, transparent: { commands: [['npx']] }, ranges: { '>=20.0.0': { url: 'https://registry.npmjs.org/npm/-/npm-{}.tgz', bin: { npm: 'bin/npm-cli.js', npx: 'bin/npx-cli.js' }, registry: { type: 'npm', package: 'npm' } } } }, yarn: { default: '4.0.1', fetchLatestFrom: { type: 'npm', package: '@yarnpkg/cli-dist' }, transparent: { commands: [] }, ranges: { '>=3.0.0': { /* ... */ } } }, pnpm: { default: '8.6.0', fetchLatestFrom: { type: 'npm', package: 'pnpm' }, transparent: { commands: [['pnpx']] }, ranges: { /* ... */ } } }, keys: { npm: [/* ... npm public keys ... */] } }; ``` -------------------------------- ### InstallSpec Interface Definition Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Defines the structure for installation specifications, including location, binary definitions, and hash. ```typescript export interface InstallSpec { location: string; // Installation directory path bin?: BinList | BinSpec; // Binary definitions hash: string; // Format: "algo.hexdigest" (e.g., "sha512.abc...") } ``` -------------------------------- ### Install Local Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Installs the package manager configured in the project's package.json. It resolves to the exact version, downloads if not cached, and adds it to the cache without setting it as the system default. ```bash corepack install ``` -------------------------------- ### Corepack Pack Command Output Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md This shows the typical console output when the 'pack' command successfully creates a tarball. ```text Adding yarn@3.6.0 to the cache... Packing the selected tools in corepack.tgz... All done! ``` -------------------------------- ### Install Global Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Installs package managers globally, making them available as system defaults. This command allows for managing different package manager versions across your system. ```APIDOC ## InstallGlobalCommand Installs package managers as system defaults. ### Command Path `install` (with `-g,--global` flag) ### Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `-g,--global` | boolean | required | Must be present to use this command | | `--cache-only` | boolean | false | Cache only, don't set as default | ### Arguments | Argument | Type | Required | Description | |----------|------|----------|-------------| | args | Rest | Yes | Package managers or tarball paths | ### Behavior for Descriptors 1. Parses package manager specs 2. Resolves versions (allows tags like "latest") 3. Downloads if needed 4. Sets as LastKnownGood (unless `--cache-only`) ### Behavior for Tarballs 1. Reads tarball structure (must be created by `corepack pack`) 2. Extracts entries with `.corepack` metadata files 3. Validates archive format 4. Extracts to cache 5. Activates versions (unless `--cache-only`) ### Example Usage ```bash # Install latest Yarn 1.x as default corepack install -g yarn@^1 # Install latest pnpm and make it default corepack install -g pnpm # Cache without setting default corepack install -g --cache-only yarn@3.6.0 # Install from offline tarball corepack install -g --cache-only /path/to/corepack.tgz ``` ### Throws | Error Type | Condition | |-----------|-----------| | `UsageError` | No package managers specified | | `UsageError` | Invalid tarball format | | `UsageError` | Unsupported package manager in tarball | ``` -------------------------------- ### findInstalledVersion Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Searches the cache directory for an installed version matching a semantic version range. It returns the highest installed version that satisfies the range, or null if no match is found. ```APIDOC ## findInstalledVersion(installTarget: string, descriptor: Descriptor): Promise ### Description Searches the cache directory for an installed version matching a semantic version range. Returns the highest installed version that satisfies the range, or null if no matching version is found. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **installTarget** (`string`) - Required - Root cache directory path - **descriptor** (`Descriptor`) - Required - Package manager name and version range ### Returns - `Promise` - Highest installed version matching range, or null if none found ### Example ```typescript const version = await corepackUtils.findInstalledVersion( '/home/user/.cache/node/corepack/v1', { name: 'yarn', range: '3.x' } ); // Returns: '3.6.0' if installed, or null ``` ``` -------------------------------- ### Install Local Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Installs the package manager configured in the project's package.json. This command ensures the project uses its specified package manager version without affecting the global system. ```APIDOC ## InstallLocalCommand Installs the package manager configured in the project. ### Command Path `install` (without `-g,--global` flag) ### Behavior 1. Loads package manager from project's package.json 2. Resolves to exact version 3. Downloads if not cached 4. Adds to cache (does not set as system default) ### Example Usage ```bash # Install project's configured package manager corepack install ``` ### Output Example ``` Adding yarn@3.6.0 to the cache... ``` ``` -------------------------------- ### Ensure Package Manager Installation Source: https://github.com/nodejs/corepack/blob/main/_autodocs/README.md Ensures a specific version of a package manager is cached locally. Returns the location of the installed package manager. ```typescript // Ensure package manager is cached const installed = await engine.ensurePackageManager({ name: 'yarn', reference: '3.6.0' }); // installed.location: '/home/user/.cache/node/corepack/v1/yarn/3.6.0' ``` -------------------------------- ### EnableCommand Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Installs package manager shims to a system directory, allowing Corepack to manage package managers. It can enable specific package managers or all available ones. ```APIDOC ## EnableCommand Installs package manager shims to a system directory. ### Command Path `enable` ### Options #### `--install-directory` (string) - Default: Auto-detected - Description: Where to install shims ### Arguments #### `names` (Rest) - Default: All except npm - Description: Package managers to enable ### Example Usage ```bash # Enable all shims next to corepack binary corepack enable # Enable specific shims in custom directory corepack enable --install-directory /usr/local/bin yarn pnpm # Enable only Yarn shims corepack enable yarn ``` ``` -------------------------------- ### ensurePackageManager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Ensures a package manager version is installed. Downloads it if not already cached, verifies integrity, and returns installation information. ```APIDOC ## async ensurePackageManager(locator: Locator): Promise ### Description Ensures a package manager version is installed. Downloads it if not already cached, verifies integrity, and returns installation information. ### Parameters #### Path Parameters - **locator** (Locator) - Required - Exact version to install (name and reference) ### Returns `Promise` — Installation details including location, bin paths, and hash ### Example ```typescript const info = await engine.ensurePackageManager({ name: 'yarn', reference: '3.6.0' }); // Returns: { // location: '/home/user/.cache/node/corepack/v1/yarn/3.6.0', // bin: ['yarn', 'yarnpkg'], // hash: 'sha512.abcd1234...', // locator: { name: 'yarn', reference: '3.6.0+sha224...' }, // spec: {...} // } ``` ``` -------------------------------- ### Corepack Pack Command JSON Output Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md This illustrates the JSON output format when the '--json' option is used with the 'pack' command. ```json "/home/user/project/corepack.tgz" ``` -------------------------------- ### Re-download Package with Corepack Source: https://github.com/nodejs/corepack/blob/main/_autodocs/errors.md If a package download is corrupted, you can force a re-download using the 'corepack install' command with the '-g' flag for global installation and specifying the package name. Ensure the package manager is correctly specified. ```bash corepack install -g yarn ``` -------------------------------- ### Fetch All Available Versions of Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Fetches an array of all published versions for a specified package manager from its registry. Use this to get a complete list of releases. ```typescript const versions = await corepackUtils.fetchAvailableVersions({ type: 'npm', package: 'yarn' }); // Returns: ['1.22.0', '1.22.1', ..., '3.6.0', '4.0.0', '4.0.1'] ``` -------------------------------- ### Set and Install Local Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md This method updates the package.json with the specified package manager and executes any defined post-install commands. It returns an exit code, with 0 indicating success. The COREPACK_MIGRATE_FROM environment variable can be used to specify the previous package manager for migration purposes. ```typescript const code = await cmd.setAndInstallLocalPackageManager(packageManagerInfo); ``` -------------------------------- ### File Preservation Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-specutils.md Demonstrates how specUtils preserves line endings (CRLF vs LF) and indentation (spaces vs tabs) when updating the package.json file. ```typescript // Original file: 4-space indented, CRLF line endings { "name": "my-app", "packageManager": "yarn@1.22.0" } // After setLocalPackageManager with proper preservation: { "name": "my-app", "packageManager": "yarn@3.6.0+sha224.abc..." } // Still 4-space indented and CRLF ``` -------------------------------- ### Example Usage of SupportedPackageManagers Enum Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Demonstrates how to import and use the SupportedPackageManagers enum to type a variable. The enum values are strings. ```typescript import { SupportedPackageManagers } from './types'; const pm: SupportedPackageManagers = SupportedPackageManagers.Yarn; // pm === 'yarn' ``` -------------------------------- ### Fetch Package Metadata as JSON Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-npmregistryutils.md Fetches package metadata from the npm registry. Use this to get all available information about a package, including all versions and dist-tags. Supports fetching metadata for a specific version by providing the version string. ```typescript import * as npmRegistryUtils from './npmRegistryUtils'; // Fetch all versions for a package const metadata = await npmRegistryUtils.fetchAsJson('yarn'); // Returns: { name: 'yarn', versions: {...}, dist-tags: {...}, ... } // Fetch specific version const versionMeta = await npmRegistryUtils.fetchAsJson('yarn', '3.6.0'); // Returns: { name: 'yarn', version: '3.6.0', dist: {...}, ... } ``` -------------------------------- ### CacheCommand Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Clears the Corepack cache. This command removes the entire install folder and rebuilds the cache on the next package manager invocation. ```APIDOC ## CacheCommand Clears the Corepack cache. ### Command Paths `cache clean`, `cache clear` ### Options None ### Example Usage ```bash corepack cache clean corepack cache clear ``` ``` -------------------------------- ### Run Package Manager Version Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Executes a package manager binary, replacing the current process. This function is used to run installed package managers with specific arguments. Note that this function never returns as it replaces the current process. ```typescript // This never returns - process is replaced with yarn await corepackUtils.runVersion( { name: 'yarn', reference: '3.6.0' }, installSpec, 'yarn', ['install'] ); ``` -------------------------------- ### Environment Variable Priority Example Source: https://github.com/nodejs/corepack/blob/main/_autodocs/configuration.md Demonstrates how shell environment variables override settings in .corepack.env files, which in turn override built-in defaults. This ensures the highest priority setting is used. ```bash # .corepack.env COREPACK_HOME=/opt/corepack # Shell export COREPACK_HOME=/home/user/.custom-corepack # Result: /home/user/.custom-corepack is used ``` -------------------------------- ### Get Temporary Folder (TypeScript) Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-utilties.md Creates and returns a unique temporary directory for downloads, with an optional target parent directory. Throws UsageError on permission issues or Error on other file system errors. ```typescript const tmpDir = folderUtils.getTemporaryFolder(installFolder); // Creates: '/path/to/corepack-12345-a1b2c3d4' // Returns that path ``` -------------------------------- ### Get Binary Names for Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Obtain a set of all binary names associated with a specific package manager. For example, 'yarn' also has 'yarnpkg'. ```typescript const bins = engine.getBinariesFor('yarn'); // Returns: Set { 'yarn', 'yarnpkg' } ``` -------------------------------- ### runVersion Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Loads and executes a package manager binary, replacing the current process with the specified arguments. ```APIDOC ## async runVersion(locator: Locator, installSpec: InstallSpec & {spec: PackageManagerSpec}, binName: string, args: Array): Promise ### Description Loads a package manager binary and executes it, replacing the current process. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **locator** (`Locator`) - Required - Package manager identification - **installSpec** (`InstallSpec & {spec: PackageManagerSpec}`) - Required - Installation and specification info - **binName** (`string`) - Required - Binary name to execute (e.g., "yarn") - **args** (`Array`) - Required - Arguments to pass to the binary ### Returns - `Promise` — Never returns (process is replaced) ### Throws - `Error` - Specified binary not found in installation ### Environment Variables - `COREPACK_ROOT`: Set to corepack package directory for feature detection by pm ### Side Effects - Replaces `process.argv`, `process.execArgv`, `process.mainModule` - Disables v8-compile-cache for npm >= 9.7.0 (avoids segfault) - Sets `COREPACK_ROOT` environment variable - Executes binary via `Module.runMain()` on next tick ### Example ```typescript // This never returns - process is replaced with yarn await corepackUtils.runVersion( { name: 'yarn', reference: '3.6.0' }, installSpec, 'yarn', ['install'] ); ``` ``` -------------------------------- ### Engine Constructor Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Initializes a new Engine instance. It can be configured with custom settings or use default configurations. ```APIDOC ## Constructor Engine ### Description Initializes a new Engine instance. It can be configured with custom settings or use default configurations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (`Config`) - Optional - Configuration object defining package manager definitions, ranges, registries, and integrity keys. Defaults to `defaultConfig`. ### Request Example ```typescript import { Engine } from './Engine'; const engine = new Engine(); // Or with custom configuration: const customEngine = new Engine(customConfig); ``` ### Response None ``` -------------------------------- ### Uninstall Global Package Managers Source: https://github.com/nodejs/corepack/blob/main/README.md Before installing Corepack using npm, uninstall any existing global Yarn and pnpm binaries. This command should be sufficient for most installations. ```shell npm uninstall -g yarn pnpm ``` -------------------------------- ### Update Corepack using npm Source: https://github.com/nodejs/corepack/blob/main/README.md Update Corepack to the latest version by running this command. If Corepack was installed via a Windows Installer, you may need to remove it first. ```shell npm install -g corepack@latest ``` -------------------------------- ### Use Package Manager Command Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Configures a package manager for the current project. Use this command to set a specific package manager and version for your project. ```bash corepack use yarn ``` ```bash corepack use yarn@3.6.0 ``` ```bash corepack use pnpm ``` -------------------------------- ### Check for Yarn Switch Path Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Identifies if a given file path corresponds to a Yarn 1.x installation managed by Yarn Switch. This is useful for differentiating between various Yarn installations. ```typescript if (corepackUtils.isYarnSwitchPath(symlink)) { console.log('This is a Yarn Switch installation - skipping'); } ``` -------------------------------- ### Instantiate Engine Class Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Create a new instance of the Engine class. You can use the default configuration or provide a custom one. ```typescript import { Engine } from './Engine'; const engine = new Engine(); // Or with custom configuration: const customEngine = new Engine(customConfig); ``` -------------------------------- ### Find Installed Version by Range Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Searches the Corepack cache for the highest installed version of a package manager that satisfies a given semantic version range. Returns null if no matching version is found. ```typescript const version = await corepackUtils.findInstalledVersion( '/home/user/.cache/node/corepack/v1', { name: 'yarn', range: '3.x' } ); // Returns: '3.6.0' if installed, or null ``` -------------------------------- ### isYarnSwitchPath Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Checks if a given file path points to a Yarn Switch installation. ```APIDOC ## isYarnSwitchPath(p: string): boolean ### Description Checks if a path points to a Yarn Switch installation (indicates Yarn 1.x installed separately). ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **p** (`string`) - Required - File path to check ### Returns - `boolean` — true if path contains `/switch/bin/` ### Example ```typescript if (corepackUtils.isYarnSwitchPath(symlink)) { console.log('This is a Yarn Switch installation - skipping'); } ``` ``` -------------------------------- ### Corepack File Organization Source: https://github.com/nodejs/corepack/blob/main/_autodocs/README.md Illustrates the directory structure and key files within the Corepack project, including entry points, utilities, and command implementations. ```text sources/ ├── _lib.ts # Entry point (exports runMain) ├── _cli.ts # CLI entry ├── main.ts # Main orchestration ├── Engine.ts # Package manager engine ├── types.ts # Type definitions ├── corepackUtils.ts # Core utilities ├── specUtils.ts # Spec loading/saving ├── npmRegistryUtils.ts # npm registry access ├── httpUtils.ts # HTTP operations ├── nodeUtils.ts # Node.js error handling ├── folderUtils.ts # Path management ├── semverUtils.ts # Version helpers ├── debugUtils.ts # Debug logging └── commands/ # CLI commands ├── Base.ts # Base command class ├── Use.ts # corepack use ├── Up.ts # corepack up ├── Install*.ts # install commands ├── Pack.ts # corepack pack ├── Enable.ts # corepack enable ├── Disable.ts # corepack disable ├── Cache.ts # corepack cache └── deprecated/ # Legacy commands ``` -------------------------------- ### Internal Implementation of Use Command Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md This snippet shows the internal logic for resolving and ensuring a package manager is set up for the project. It handles version resolution, downloading, and updating the project's package.json. ```typescript const [descriptor] = await this.resolvePatternsToDescriptors({ patterns: [this.pattern] }); const resolved = await engine.resolveDescriptor(descriptor, {allowTags: true}); const packageManagerInfo = await engine.ensurePackageManager(resolved); await this.setAndInstallLocalPackageManager(packageManagerInfo); ``` -------------------------------- ### fetchAvailableVersions Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Fetches all available versions of a package manager from a registry. It returns a promise that resolves to an array of version strings. ```APIDOC ## fetchAvailableVersions(spec: RegistrySpec): Promise> ### Description Fetches all available versions from a registry. The function returns a promise that resolves to an array containing all discovered version strings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **spec** (`RegistrySpec`) - Required - Registry specification ### Returns - `Promise>` - Array of version strings ### Example ```typescript const versions = await corepackUtils.fetchAvailableVersions({ type: 'npm', package: 'yarn' }); // Returns: ['1.22.0', '1.22.1', ..., '3.6.0', '4.0.0', '4.0.1'] ``` ``` -------------------------------- ### DisableCommand Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Removes package manager shims from a system directory. This command can disable specific package managers or all installed shims. ```APIDOC ## DisableCommand Removes package manager shims from a system directory. ### Command Path `disable` ### Options #### `--install-directory` (string) - Default: Auto-detected - Description: Where shims are located ### Arguments #### `names` (Rest) - Default: All except npm - Description: Package managers to disable ### Example Usage ```bash # Disable all shims corepack disable # Disable Yarn from custom directory corepack disable --install-directory /usr/local/bin yarn # Disable pnpm and npm corepack disable pnpm npm ``` ``` -------------------------------- ### Configure Package Manager with URL in package.json Source: https://github.com/nodejs/corepack/blob/main/README.md You can also specify a URL to a .js file or a .tgz archive for the package manager. The 'bin' field in the package.json of the archive will determine the executable. ```json { "packageManager": "yarn@https://registry.npmjs.org/@yarnpkg/cli-dist/-/cli-dist-3.2.3.tgz#sha224.16a0797d1710d1fb7ec40ab5c3801b68370a612a9b66ba117ad9924b" } ``` -------------------------------- ### Core API References Source: https://github.com/nodejs/corepack/blob/main/_autodocs/README.md API references for the core functionalities of Corepack, including package manager discovery, resolution, installation, and execution. ```APIDOC ## Core API References ### Engine Class - **getPackageManagerFor()** — Identify package manager by binary name - **resolveDescriptor()** — Resolve version ranges to exact versions - **ensurePackageManager()** — Download and cache package manager - **executePackageManagerRequest()** — Run package manager with correct version ### Core Utilities - **fetchLatestStableVersion()** — Get latest version from registry - **installVersion()** — Download and cache package manager - **runVersion()** — Execute package manager binary - Integrity verification and signature checking ### Project Spec Handling - **parseSpec()** — Parse package manager specifications - **loadSpec()** — Find and load project's package manager configuration - **setLocalPackageManager()** — Update project with new package manager - `devEngines.packageManager` field support ### npm Registry Operations - **fetchLatestStableVersion()** — Get latest npm package version - **fetchAvailableVersions()** — List all published versions - **verifySignature()** — Cryptographic signature verification - Authentication: Bearer token, Basic auth, custom registries ### CLI Commands - **corepack enable** — Install package manager shims - **corepack disable** — Remove package manager shims - **corepack use** — Configure project to use specific package manager - **corepack up** — Update to latest version in same major - **corepack install** — Install package manager to cache - **corepack pack** — Create offline tarball - **corepack cache clean** — Clear cache ### Foundational Utilities - **folderUtils** — Cache directory paths - **httpUtils** — HTTP fetch with auth and prompts - **nodeUtils** — Node.js error handling - **semverUtils** — Semantic versioning helpers - **debugUtils** — Debug logging ``` -------------------------------- ### getDefaultVersion Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Gets the default version for a specific package manager. Checks LastKnownGood file first, then environment variables, then remote registry. ```APIDOC ## async getDefaultVersion(packageManager: SupportedPackageManagers): Promise ### Description Gets the default version for a specific package manager. Checks LastKnownGood file first, then environment variables, then remote registry. ### Method N/A (Instance Method) ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **packageManager** (`SupportedPackageManagers`) - Required - Package manager name ### Request Example ```typescript const version = await engine.getDefaultVersion('yarn'); // Returns: "4.0.1+sha224...." ``` ### Response #### Success Response - **Return Value** (`Promise`) - Version string (may include hash) ### Throws - **`UsageError`**: Package manager is not supported ### Environment Variables - **COREPACK_DEFAULT_TO_LATEST**: Set to `0` to use internal config instead of fetching latest ``` -------------------------------- ### getTemporaryFolder(target?: string) Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-utilties.md Creates and returns a unique temporary directory for downloads. It can optionally take a target directory as a parent, otherwise it uses the system's default temporary directory. The function ensures uniqueness by creating directories with names like 'corepack--'. ```APIDOC ## getTemporaryFolder(target?: string) ### Description Creates and returns a unique temporary directory for downloads. This function is useful for staging downloads and ensures that temporary directories do not collide with each other. ### Parameters #### Path Parameters - **target** (`string`) - Optional - `os.tmpdir()` - Parent directory for temp folder ### Returns - `string` — Absolute path to unique temporary directory ### Throws - `UsageError` - No write permission (EACCES) - `Error` - Unexpected file system error ### Note Creates directory with random name `corepack--` to avoid collisions. ### Example ```typescript const tmpDir = folderUtils.getTemporaryFolder(installFolder); // Creates: '/path/to/corepack-12345-a1b2c3d4' // Returns that path ``` ``` -------------------------------- ### Get Default Package Manager Descriptors Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Asynchronously retrieve the default descriptors, including default versions, for all supported package managers. ```typescript const defaults = await engine.getDefaultDescriptors(); // Returns: [ // { name: 'npm', range: '10.5.0+...' }, // { name: 'yarn', range: '4.0.1+...' }, // { name: 'pnpm', range: '8.6.0+...' } // ] ``` -------------------------------- ### fetchAsJson(packageName: string, version?: string): Promise Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-npmregistryutils.md Fetches package metadata from the npm registry as JSON. It can retrieve all versions or a specific version of a package. ```APIDOC ## fetchAsJson(packageName: string, version?: string): Promise ### Description Fetches package metadata from the npm registry as JSON. It can retrieve all versions or a specific version of a package. ### Parameters #### Path Parameters - **packageName** (string) - Required - npm package name (e.g., "yarn", "@yarnpkg/cli-dist") - **version** (string) - Optional - Specific version to fetch (omit for all versions) ### Returns `Promise` — Parsed JSON metadata object ### Throws - `UsageError` - Network disabled via COREPACK_ENABLE_NETWORK=0 - `Error` - Network request failed - `Error` - HTTP error response ### Environment Variables - `COREPACK_NPM_REGISTRY`: Custom registry URL (default: https://registry.npmjs.org) - `COREPACK_NPM_TOKEN`: Bearer token for authentication - `COREPACK_NPM_USERNAME`: Basic auth username - `COREPACK_NPM_PASSWORD`: Basic auth password ### Example ```typescript import * as npmRegistryUtils from './npmRegistryUtils'; // Fetch all versions for a package const metadata = await npmRegistryUtils.fetchAsJson('yarn'); // Returns: { name: 'yarn', versions: {...}, dist-tags: {...}, ... } // Fetch specific version const versionMeta = await npmRegistryUtils.fetchAsJson('yarn', '3.6.0'); // Returns: { name: 'yarn', version: '3.6.0', dist: {...}, ... } ``` ``` -------------------------------- ### Execute Package Manager Request Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Executes a package manager with given arguments. Resolves the correct version, downloads if needed, and spawns the executable. Use when you need to run a package manager command with specific arguments. ```typescript await engine.executePackageManagerRequest( { packageManager: 'yarn', binaryName: 'yarn', binaryVersion: null }, { cwd: process.cwd(), args: ['install'] } ); ``` -------------------------------- ### activatePackageManager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Sets a package manager as the system default by updating the LastKnownGood file. ```APIDOC ## activatePackageManager(locator: Locator): Promise ### Description Sets a package manager as the system default by updating the LastKnownGood file. ### Parameters #### Path Parameters - **locator** (Locator) - Yes - Package manager to set as default ### Returns `Promise` ### Request Example ```typescript await engine.activatePackageManager({ name: 'yarn', reference: '4.0.0+sha224...' }); ``` ``` -------------------------------- ### Get Package Manager for Binary Name Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Determine the package manager associated with a given binary name. Returns null if the binary name is not recognized. ```typescript const pm = engine.getPackageManagerFor('yarn'); // Returns: 'yarn' const pm = engine.getPackageManagerFor('unknown'); // Returns: null ``` -------------------------------- ### executePackageManagerRequest Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Executes a package manager with given arguments. Resolves the correct version, downloads if needed, and spawns the executable. ```APIDOC ## async executePackageManagerRequest(request: PackageManagerRequest, options: {cwd: string, args: Array}): Promise ### Description Executes a package manager with given arguments. Resolves the correct version, downloads if needed, and spawns the executable. ### Parameters #### Path Parameters - **request** (PackageManagerRequest) - Required - Contains packageManager, binaryName, and binaryVersion - **options.cwd** (string) - Required - Current working directory - **options.args** (Array) - Required - Arguments to pass to the package manager ### Returns `Promise` ### Throws - `UsageError` - Cannot resolve version to valid release ### Example ```typescript await engine.executePackageManagerRequest( { packageManager: 'yarn', binaryName: 'yarn', binaryVersion: null }, { cwd: process.cwd(), args: ['install'] } ); ``` ``` -------------------------------- ### Activate Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-engine.md Sets a package manager as the system default by updating the LastKnownGood file. Requires a Locator object specifying the package manager name and reference. ```typescript await engine.activatePackageManager({ name: 'yarn', reference: '4.0.0+sha224...' }); ``` -------------------------------- ### Clear Corepack Cache Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-commands.md Use this command to clear the Corepack cache. It removes the entire install folder and rebuilds the cache on the next package manager invocation. ```bash corepack cache clean corepack cache clear ``` -------------------------------- ### Force Download Prompt for Package Managers Source: https://github.com/nodejs/corepack/blob/main/_autodocs/configuration.md Set COREPACK_ENABLE_DOWNLOAD_PROMPT to '1' to always display a download prompt and require user confirmation before downloading package managers. This setting cannot be overridden in .corepack.env. ```bash export COREPACK_ENABLE_DOWNLOAD_PROMPT=1 corepack pnpm install # Shows download confirmation ``` -------------------------------- ### Get Corepack Home Folder (TypeScript) Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-utilties.md Retrieves the root Corepack cache directory. Respects COREPACK_HOME, XDG_CACHE_HOME, and LOCALAPPDATA environment variables for path determination. ```typescript import * as folderUtils from './folderUtils'; const cacheDir = folderUtils.getCorepackHomeFolder(); // Returns: '/home/user/.cache/node/corepack' ``` -------------------------------- ### Enable Automatic Package Manager Pinning Source: https://github.com/nodejs/corepack/blob/main/_autodocs/configuration.md Set COREPACK_ENABLE_AUTO_PIN to '1' to automatically add the 'packageManager' field to package.json when it's missing. This simplifies project setup. ```bash export COREPACK_ENABLE_AUTO_PIN=1 cd my-project yarn install # Automatically adds yarn@X.Y.Z to package.json ``` -------------------------------- ### Switch Project's Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/errors.md If you intend to change the default package manager for a project, use the 'corepack use' command followed by the desired manager (e.g., npm). This updates the project's configuration to reflect the new manager. ```bash corepack use npm ``` -------------------------------- ### Package.json with devEngines.packageManager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-specutils.md Illustrates the structure of the packageManager and devEngines fields in package.json, used for specifying package manager constraints and validation behavior. ```json { "packageManager": "yarn@3.6.0+sha224.abc...", "devEngines": { "packageManager": { "name": "yarn", "version": "^3.0.0", "onFail": "warn" } } } ``` -------------------------------- ### Get npm Registry from Package Manager Spec Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Resolves the appropriate registry specification for a given package manager spec, respecting environment overrides for npm registries. ```typescript const registry = corepackUtils.getRegistryFromPackageManagerSpec(spec); // Returns: { type: 'npm', package: '@yarnpkg/cli-dist' } ``` -------------------------------- ### Fetch Available Tags for Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/api-reference-corepackutils.md Retrieves all distribution tags (e.g., 'latest', 'next') for a given package manager from its registry. This is useful for understanding different release channels available for a package manager. ```typescript const tags = await corepackUtils.fetchAvailableTags({ type: 'npm', package: 'pnpm' }); // Returns: { latest: '8.6.0', next: '9.0.0-beta.1', stable: '8.6.0' } ``` -------------------------------- ### Information about a Downloaded Package Manager Source: https://github.com/nodejs/corepack/blob/main/_autodocs/types.md Use DownloadSpec to store information about a package manager that has been downloaded but not yet installed. It includes the temporary extraction directory, the output file path, and the computed hash. ```typescript export interface DownloadSpec { tmpFolder: string; // Temporary extraction directory outputFile: string | null; // Single file path (.js) or null (.tgz extracted) hash: string; // Computed hash } ``` -------------------------------- ### Set NPM Username and Password for Authentication Source: https://github.com/nodejs/corepack/blob/main/_autodocs/errors.md Alternatively, authentication can be handled by setting the COREPACK_NPM_USERNAME and COREPACK_NPM_PASSWORD environment variables. These credentials will be used for registry authentication. ```bash COREPACK_NPM_USERNAME=your_username COREPACK_NPM_PASSWORD=your_password ```