### Dependency resolution algorithm example 1 Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Illustrates how npm installs dependencies, showing that a dependency requested by a child package (C by B) can be satisfied by a higher-level installation (C by A) if versions are compatible. ```bash A +-- B +-- C +-- D ``` -------------------------------- ### Install from tarball URL Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Fetches and installs a package from a tarball URL. The URL must start with "http://" or "https://". ```bash npm install https://github.com/indexzero/forever/tarball/v0.5.6 ``` -------------------------------- ### Example package.json with script Source: https://github.com/npm/cli/blob/latest/docs/lib/content/using-npm/scripts.md This example shows how to define a script in package.json that executes an external command. The executable is made available in the PATH after npm install. ```json { "name" : "foo", "dependencies" : { "bar" : "0.1.x" }, "scripts": { "start" : "bar ./test" } } ``` -------------------------------- ### npm ls Command Example Source: https://github.com/npm/cli/blob/latest/docs/lib/content/configuring-npm/folders.md Illustrates how to visualize the installed package structure and dependencies using the 'npm ls' command. This helps in understanding the folder hierarchy and where each dependency is resolved from. ```bash npm ls ``` -------------------------------- ### Initialize Custom NPM Card with create-my-card Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/test/fixtures/old-package-lock-with-bins/node_modules/ruy/README.md This snippet demonstrates how to initialize a custom npm card using the create-my-card package. It's a command-line interface tool that guides the user through the setup process. Ensure you have npm installed. ```bash npm init my-card ``` -------------------------------- ### Install dependencies and packages Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm.md Use these commands to install project dependencies or specific packages from the registry. ```bash npm install ``` ```bash npm install blerg ``` -------------------------------- ### Execute npm start command Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-start.md This bash snippet demonstrates how to execute the 'npm start' command. It shows the expected output when the 'start' script is defined in package.json, indicating the command being run and its potential output. ```bash npm start > npm@x.x.x start > node foo.js (foo.js output would be here) ``` -------------------------------- ### GYP Command Expansion Examples Source: https://github.com/npm/cli/blob/latest/node_modules/node-gyp/gyp/docs/InputFormatReference.md Examples demonstrating how to use command expansions for dynamic values and list processing within GYP configuration files. ```gyp 'variables' : [ 'foo': ' npm@x.x.x start > node foo.js ``` -------------------------------- ### Install from local folder with symlinking Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs dependencies from a local folder and creates a symlink to it. Use `--install-links` to install the content as a package instead of creating a link. ```bash npm install ../../other-package --install-links npm install ./sub-package ``` -------------------------------- ### Generic npm query example Source: https://github.com/npm/cli/wiki/Query-Cookbook A placeholder example demonstrating the basic syntax structure for executing queries against the npm dependency tree. ```bash npm query ... ``` -------------------------------- ### Basic ProxyAgent instantiation Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/ProxyAgent.md Instantiates the ProxyAgent. This example shows the basic setup without registering it as a global dispatcher. ```javascript import { ProxyAgent } from 'undici' const proxyAgent = new ProxyAgent('my.proxy.server') ``` -------------------------------- ### Install a package from a git remote URL Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs a package directly from a hosted git provider by cloning the repository. Only the provided URL will be used for installation. ```bash npm install ``` -------------------------------- ### Proxy Request Examples Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/ProxyAgent.md Examples demonstrating how to use ProxyAgent for making requests, both globally and locally. ```APIDOC ### Example - Basic Proxy Request with global agent dispatcher ```javascript import { setGlobalDispatcher, request, ProxyAgent } from 'undici' const proxyAgent = new ProxyAgent('my.proxy.server') setGlobalDispatcher(proxyAgent) const { statusCode, body } = await request('http://localhost:3000/foo') console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` ### Example - Basic Proxy Request with local agent dispatcher ```javascript import { ProxyAgent, request } from 'undici' const proxyAgent = new ProxyAgent('my.proxy.server') const { statusCode, body } = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` ### Example - Basic Proxy Request with authentication ```javascript import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server', token: `Basic ${Buffer.from('username:password').toString('base64')}` }); setGlobalDispatcher(proxyAgent); const { statusCode, body } = await request('http://localhost:3000/foo'); console.log('response received', statusCode); // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')); // data foo } ``` ``` -------------------------------- ### Performing Global Installs Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/docs/global.md Demonstrates how to perform a global installation using the `arborist.reify` method, specifying the path, global flag, and packages to add or remove. ```APIDOC ## POST /npm/cli/reify ### Description Performs a global installation of npm packages. ### Method POST ### Endpoint /npm/cli/reify ### Parameters #### Request Body - **path** (string) - Required - The path to the node_modules directory. - **global** (boolean) - Required - Set to true for global installs. - **add** (object) - Optional - An object containing dependencies to add. Example: `{ dependencies: [ pkgSpec ] }`. - **rm** (array) - Optional - An array of package names to remove. ### Request Example ```json { "path": "/usr/local/lib", "global": true, "add": { "dependencies": [ "some-package@latest" ] }, "rm": [ "old-package" ] } ``` ### Response #### Success Response (200) - **tree** (object) - The resulting tree object, including only the added/removed dependencies. #### Response Example ```json { "tree": { "dependencies": { "some-package": { "version": "1.0.0" } } } } ``` ``` -------------------------------- ### Install package by name and tag Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs a package by its name and a specific tag, defaulting to the 'latest' tag. This is the most common way to install packages from the npm registry. ```bash npm install [<@scope>/] ``` -------------------------------- ### Install a package by tag Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs the version of a package referenced by a specific tag. This will fail if the tag does not exist for the package. ```bash npm install sax@latest ``` ```bash npm install @myorg/mypackage@latest ``` -------------------------------- ### Install Scoped Packages via CLI Source: https://github.com/npm/cli/blob/latest/docs/lib/content/using-npm/scope.md Demonstrates how to install a scoped package using the npm command line interface. ```bash npm install @myorg/mypackage ``` -------------------------------- ### Install from GitLab Repository Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs a package from a GitLab repository using the format gitlab:/. Supports commit-ish specifiers. If no commit-ish is specified, the 'master' branch is used. ```bash npm install gitlab:mygitlabuser/myproject ``` ```bash npm install gitlab:myusr/myproj#semver:^5.0 ``` -------------------------------- ### Install a package matching a version range Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs a version of a package that matches the specified version range. Ensure version ranges are quoted to be treated as a single argument by the shell. ```bash npm install sax=">=0.1.0 <0.2.0" ``` ```bash npm install @myorg/privatepackage="16 - 17" ``` -------------------------------- ### Install from Bitbucket Repository Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs a package from a Bitbucket repository using the format bitbucket:/. Supports commit-ish specifiers. If no commit-ish is specified, the 'master' branch is used. ```bash npm install bitbucket:mybitbucketuser/myproject ``` -------------------------------- ### Example package.json for build and test scripts Source: https://github.com/npm/cli/blob/latest/docs/lib/content/using-npm/scripts.md Shows a common pattern where 'prepare' script runs another script like 'build', which in turn executes a build tool like 'tsc'. This demonstrates script chaining and execution of build commands. ```json { "scripts" : { "prepare" : "npm run build", "build" : "tsc", "test" : "jest" } } ``` -------------------------------- ### Example: Deny a Specific Package Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-deny-scripts.md This example demonstrates how to deny install scripts for a package named 'telemetry-pkg'. This ensures that 'telemetry-pkg' will not execute its install scripts. ```bash npm deny-scripts telemetry-pkg ``` -------------------------------- ### Example of Pre, Script, and Post Scripts Source: https://github.com/npm/cli/blob/latest/docs/lib/content/using-npm/scripts.md Demonstrates how to define pre, main, and post scripts for a specific task. Running 'npm run compress' will execute these in sequence. ```json { "scripts": { "precompress": "{{ executes BEFORE the `compress` script }}", "compress": "{{ run command to compress files }}", "postcompress": "{{ executes AFTER `compress` script }}" } } ``` -------------------------------- ### Connect Request with Echo Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/Dispatcher.md This example shows how to establish a connection using `client.connect()` and echo data back to the client. It sets up a server that listens for the CONNECT event and forwards data. ```javascript import { createServer } from 'http' import { Client } from 'undici' import { once } from 'events' const server = createServer((request, response) => { throw Error('should never get here') }).listen() server.on('connect', (req, socket, head) => { socket.write('HTTP/1.1 200 Connection established\r\n\r\n') let data = head.toString() socket.on('data', (buf) => { data += buf.toString() }) socket.on('end', () => { socket.end(data) }) }) await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { socket } = await client.connect({ path: '/' }) const wanted = 'Body' let data = '' socket.on('data', d => { data += d }) socket.on('end', () => { console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) client.close() server.close() }) socket.write(wanted) socket.end() } catch (error) { } ``` -------------------------------- ### Initialize a new workspace with npm init Source: https://github.com/npm/cli/blob/latest/docs/lib/content/using-npm/workspaces.md This command-line example demonstrates how to use 'npm init -w' to automate the creation of a new workspace. It generates the necessary directory structure and package.json file, and also updates the root package.json to include the new workspace. ```bash npm init -w ./packages/a ``` -------------------------------- ### Push Dependency Resolution Example Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/test/fixtures/testing-peer-dep-conflict-chain/override-peer/readme.md This example illustrates the 'push-dep' resolution strategy in npm. When 'override' is installed as a dependency, npm ensures that each module receives the specific version of its dependencies it declares, even if it means duplicating dependencies. ```text Installing 'override' as a dep: push-dep +-- v@1 +-- a@1 +-- b@1, c@1, ... +-- override +-- a@2 +-- b@2, c@2, ... This is a compliant dependency resolution where every module gets the version of their dep that they declare. ``` -------------------------------- ### Gatsby Peer Dependency Conflict Example Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/test/fixtures/testing-peer-dep-conflict-chain/override-peer/readme.md This example models gatsby@2.24.53's dependency structure, showing how a peer dependency from '@pmmmwh/react-refresh-webpack-plugin' on 'react-refresh' causes a conflict. It illustrates the initial installation state and how 'react-refresh' is moved to resolve the conflict. ```text gatsby -> (react-refresh@0.7.2, @pmmmwh/react-refresh-webpack-plugin@0.4.1) @pmmmwh/react-refresh-webpack-plugin@0.4.1 -> PEER react-refresh@0.7.2 Initial installation: +-- root +-- gatsby +-- @pmmmwh/react-refresh-webpack-plugin +-- react-refresh@0.7.2 After peerDep evaluation (react-refresh@0.8.3 required): Since we _can_ move `react-refresh@0.7.2` underneath `gatsby`, we do so. ``` -------------------------------- ### GYP 'Hello, world!' Test Configuration Source: https://github.com/npm/cli/blob/latest/node_modules/node-gyp/gyp/docs/Testing.md Demonstrates a basic GYP test configuration file (`hello.gyp`) and the associated Python test script (`gyptest-all.py`) used to build and run a simple 'Hello, world!' C program. It outlines the structure of test scripts, including setup, execution, and verification steps. ```bash ls -l test/hello total 20 -rw-r--r-- 1 knight knight 312 Jul 30 20:22 gyptest-all.py -rw-r--r-- 1 knight knight 307 Jul 30 20:22 gyptest-default.py -rwxr-xr-x 1 knight knight 326 Jul 30 20:22 gyptest-target.py -rw-r--r-- 1 knight knight 98 Jul 30 20:22 hello.c -rw-r--r-- 1 knight knight 142 Jul 30 20:22 hello.gyp $ ``` ```python #!/usr/bin/env python """ Verifies simplest-possible build of a "Hello, world!" program using an explicit build target of 'all'. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('hello.gyp') test.build_all('hello.gyp') test.run_built_executable('hello', stdout="Hello, world!\n") test.pass_test() ``` ```python #!/usr/bin/env python """ Verifies simplest-possible build of a "Hello, world!" program using an explicit build target of 'all'. """ import TestGyp test = TestGyp.TestGyp() ``` ```python test.pass_test() ``` -------------------------------- ### MockPool Request Example Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/MockPool.md Demonstrates mocking a GET request to '/foo' using `mockPool.request`. The response status code and body are logged. ```javascript import { MockAgent } from 'undici' const mockAgent = new MockAgent() const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/foo', method: 'GET', }).reply(200, 'foo') const { statusCode, body } = await mockPool.request({ origin: 'http://localhost:3000', path: '/foo', method: 'GET' }) console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` -------------------------------- ### Caret dependency example Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Shows how `npm update` handles caret dependencies (`^`). The command installs the latest version that satisfies the caret range. ```json "dependencies": { "dep1": "^1.1.1" } ``` -------------------------------- ### Initialize and Load Configuration with @npmcli/config Source: https://github.com/npm/cli/blob/latest/workspaces/config/README.md Demonstrates how to initialize the Config class with various options and load the configuration. It includes setting paths, definitions, shorthands, and handling log events. The configuration is loaded asynchronously and validated upon completion. ```javascript const Config = require('@npmcli/config') const { shorthands, definitions, flatten } = require('@npmcli/config/lib/definitions') const { resolve } = require('path') const conf = new Config({ npmPath: resolve(__dirname, '..'), definitions, shorthands, flatten, argv: process.argv, env: process.env, execPath: process.execPath, platform: process.platform, cwd: process.cwd(), }) process.on('log', (level, ...args) => { console.log(level, ...args) }) conf.load().then(() => { conf.validate() console.log('loaded ok! some-key = ' + conf.get('some-key')) }).catch(er => { console.error('error loading configs!', er) }) ``` -------------------------------- ### Caret dependency below 1.0.0 example Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Illustrates `npm update` with caret dependencies on versions below 1.0.0. It installs the highest-sorting version that satisfies the specified range. ```json "dependencies": { "dep1": "^0.2.0" } ``` -------------------------------- ### Subdependency example Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Demonstrates how `npm update` handles subdependencies. It prioritizes a single version that satisfies multiple dependencies' semver requirements over installing multiple versions. ```json { "name": "my-app", "dependencies": { "dep1": "^1.0.0", "dep2": "1.0.0" } } ``` -------------------------------- ### Example - Basic RetryHandler with defaults Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/RetryHandler.md Demonstrates how to initialize a RetryHandler using default retry configurations. ```APIDOC ## Example - Basic RetryHandler with defaults ```js const client = new Client(`http://localhost:${server.address().port}`); const handler = new RetryHandler(dispatchOptions, { dispatch: client.dispatch.bind(client), handler: { onConnect() {}, onBodySent() {}, onHeaders(status, _rawHeaders, resume, _statusMessage) {}, onData(chunk) {}, onComplete() {}, onError(err) {}, }, }); ``` ``` -------------------------------- ### Tilde dependency example Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Demonstrates `npm update` behavior with tilde dependencies (`~`). It installs the highest-sorting version that satisfies the tilde range, even if a newer 'latest' version exists. ```json "dependencies": { "dep1": "~1.1.1" } ``` -------------------------------- ### Initialize and Load Config Source: https://github.com/npm/cli/blob/latest/workspaces/config/README.md How to instantiate the Config class and load the configuration hierarchy. ```APIDOC ## Initialization ### Description Instantiate the Config class with necessary definitions and environment context to manage npm configuration. ### Method Constructor ### Parameters #### Request Body - **npmPath** (string) - Required - Path to the npm module being run. - **definitions** (object) - Required - Configuration type definitions. - **shorthands** (object) - Required - CLI shorthand mappings. - **argv** (array) - Optional - CLI arguments (defaults to process.argv). - **env** (object) - Optional - Environment variables (defaults to process.env). - **cwd** (string) - Optional - Current working directory (defaults to process.cwd()). ### Request Example const conf = new Config({ npmPath: '/path/to/npm', definitions, shorthands }); ### Response #### Success Response (Promise) - **conf** (object) - Returns a promise that resolves when the configuration object is ready for use. ``` -------------------------------- ### Extract all values from an array field Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-view.md When a field is an array, requesting a non-numeric field will return all values from the objects within that array. This example gets all contributor email addresses for the 'express' package. ```bash npm view express contributors.email ``` ```bash npm view express contributors.name ``` -------------------------------- ### Example package.json scripts for npm version Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-version.md This example demonstrates how to use 'preversion', 'version', and 'postversion' scripts in package.json to automate tasks like testing, building, committing, and pushing during the versioning process. ```json { "scripts": { "preversion": "npm test", "version": "npm run build && git add -A dist", "postversion": "git push && git push --tags && rm -rf build/temp" } } ``` -------------------------------- ### Caret dependency below 1.0.0 example (higher patch) Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Shows `npm update` behavior when a caret dependency below 1.0.0 has a higher patch version available. It installs the highest-sorting version that satisfies the range. ```json "dependencies": { "dep1": "^0.4.0" } ``` -------------------------------- ### Mocked request with path callback Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/MockPool.md This example demonstrates how to mock a request using a callback function for path matching. The `matchPath` function checks if the request path starts with '/foo' and includes the query parameter 'foo=bar'. ```APIDOC ## Mocked request with path callback ### Description This example demonstrates how to mock a request using a callback function for path matching. The `matchPath` function checks if the request path starts with '/foo' and includes the query parameter 'foo=bar'. ### Method GET ### Endpoint /foo?foo=bar ### Request Example ```js import { MockAgent, setGlobalDispatcher, request } from 'undici' import querystring from 'querystring' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) const mockPool = mockAgent.get('http://localhost:3000') const matchPath = requestPath => { const [pathname, search] = requestPath.split('?') const requestQuery = querystring.parse(search) if (!pathname.startsWith('/foo')) { return false } if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') { return false } return true } mockPool.intercept({ path: matchPath, method: 'GET' }).reply(200, 'foo') const result = await request('http://localhost:3000/foo?foo=bar') // Will match and return mocked data ``` ### Response #### Success Response (200) - **body** (string) - The mocked response body 'foo'. ``` -------------------------------- ### Example dependency versions Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Illustrates the published versions of a package, used to demonstrate semver constraint satisfaction. ```json { "dist-tags": { "latest": "1.2.2" }, "versions": [ "1.2.2", "1.2.1", "1.2.0", "1.1.2", "1.1.1", "1.0.0", "0.4.1", "0.4.0", "0.2.0" ] } ``` -------------------------------- ### NPM Dependency Tree Example: Gatsby Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/test/fixtures/testing-peer-dep-conflict-chain/override/readme.md Illustrates a typical dependency tree for Gatsby, highlighting the relationship between Gatsby, its direct dependencies, and a peer dependency conflict with react-refresh. This shows the initial installation state before conflict resolution. ```text gatsby -> (react-refresh@0.7.2, @pmmmwh/react-refresh-webpack-plugin@0.4.1) @pmmmwh/react-refresh-webpack-plugin@0.4.1 -> PEER react-refresh@0.7.2 ``` -------------------------------- ### Mock a Request with Global Dispatcher Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/MockAgent.md Intercept and mock an HTTP request using MockAgent as the global dispatcher. Define mock responses using intercept and reply, then make the request. This example demonstrates mocking a GET request to '/foo'. ```javascript import { MockAgent, setGlobalDispatcher, request } from 'undici' const mockAgent = new MockAgent() setGlobalDispatcher(mockAgent) const mockPool = mockAgent.get('http://localhost:3000') mockPool.intercept({ path: '/foo' }).reply(200, 'foo') const { statusCode, body } = await request('http://localhost:3000/foo') console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/npm/cli/blob/latest/node_modules/diff/CONTRIBUTING.md Use these commands to install dependencies and execute the test suite. ```shell yarn yarn test ``` -------------------------------- ### GYP Configuration Example Source: https://github.com/npm/cli/blob/latest/node_modules/node-gyp/gyp/docs/LanguageSpecification.md This is an example of a .gyp file, which uses a Python data structure (similar to JSON) to define build targets, source files, include directories, and platform-specific configurations. It specifies settings for a 'foo' static library. ```python { 'target_defaults': { 'defines': [ 'U_STATIC_IMPLEMENTATION', ['LOGFILE', 'foo.log',], ], 'include_dirs': [ '..', ], }, 'targets': [ { 'target_name': 'foo', 'type': 'static_library', 'sources': [ 'foo/src/foo.cc', 'foo/src/foo_main.cc', ], 'include_dirs': [ 'foo', 'foo/include', ], 'conditions': [ [ 'OS==mac', { 'sources': [ 'platform_test_mac.mm' ] } ] ], 'direct_dependent_settings': { 'defines': [ 'UNIT_TEST', ], 'include_dirs': [ 'foo', 'foo/include', ], }, }, ], } ``` -------------------------------- ### NPM Dependency Tree Example: Override Package Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/test/fixtures/testing-peer-dep-conflict-chain/override/readme.md Demonstrates a simplified dependency tree for an 'override' package that has a peer dependency conflict. This scenario is used to explain how NPM attempts to resolve these conflicts, often leading to installation failures without specific flags. ```text override -> (a@2, v@1) v@1 -> PEER(a@1) ``` -------------------------------- ### Dependency resolution algorithm example 2 Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Demonstrates how npm handles conflicting dependency versions. If a package (B) requires a specific version of a dependency (D@1) that conflicts with another package's requirement (C requires D@2), the conflicting version (D@2) is installed privately for the package that needs it (C). ```bash A +-- B +-- C `-- D@2 +-- D@1 ``` -------------------------------- ### Publish Package Example Source: https://github.com/npm/cli/blob/latest/workspaces/libnpmpublish/README.md Example demonstrating how to publish an npm package using libnpmpublish. It requires fetching the package manifest and tarball data first. Options for npm version and authentication token can be provided. ```javascript // note that pacote.manifest() and pacote.tarball() can also take // any spec that npm can install. a folder shown here, since that's // far and away the most common use case. const path = '/a/path/to/your/source/code' const pacote = require('pacote') // see: http://npm.im/pacote const manifest = await pacote.manifest(path) const tarData = await pacote.tarball(path) await libpub.publish(manifest, tarData, { npmVersion: 'my-pub-script@1.0.2', token: 'my-auth-token-here' }, opts) // Package has been published to the npm registry. ``` -------------------------------- ### Define npm start script in package.json Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-start.md This JSON snippet shows how to define a custom start script within the 'scripts' object of a package.json file. The 'start' property specifies the command to be executed when 'npm start' is run. ```json { "scripts": { "start": "node foo.js" } } ``` -------------------------------- ### Approve All Install Scripts Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-approve-scripts.md Use this command to approve all currently installed dependencies' install scripts after manual review. This modifies the package.json file. ```bash npm approve-scripts --all ``` -------------------------------- ### Perform a Basic GET Request with Undici Source: https://github.com/npm/cli/blob/latest/node_modules/undici/docs/docs/api/Dispatcher.md Demonstrates how to perform a basic GET request using the `Client.request()` method. It includes setting up a mock server, making the request, and handling the response, including consuming the body and logging headers and trailers. Ensure the server is closed after the request. ```javascript import { createServer } from 'http' import { Client } from 'undici' import { once } from 'events' const server = createServer((request, response) => { response.end('Hello, World!') }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { body, headers, statusCode, trailers } = await client.request({ path: '/', method: 'GET' }) console.log(`response received ${statusCode}`) console.log('headers', headers) body.setEncoding('utf8') body.on('data', console.log) body.on('end', () => { console.log('trailers', trailers) }) client.close() server.close() } catch (error) { console.error(error) } ``` -------------------------------- ### Install Package Globally Source: https://github.com/npm/cli/blob/latest/docs/lib/content/using-npm/developers.md Installs the current package globally for testing. This command is useful for verifying that your package installs and functions correctly before publishing. ```bash npm install . -g ``` -------------------------------- ### View Arborist CLI Help Source: https://github.com/npm/cli/blob/latest/workspaces/arborist/README.md Run this command to see the available options and usage instructions for the Arborist CLI. ```bash npx @npmcli/arborist --help ``` -------------------------------- ### Update globally installed packages Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-update.md Updates all globally installed packages that are outdated. Globally installed packages do not have a `package.json` semver range, so their 'wanted' version is always 'latest'. ```bash npm update -g ``` -------------------------------- ### Install a package by name Source: https://github.com/npm/cli/blob/latest/docs/lib/content/commands/npm-install.md Installs a package and saves it to dependencies by default. Use flags like -D or -O to save to devDependencies or optionalDependencies respectively. Use --no-save to prevent saving. ```bash npm install sax ``` ```bash npm install githubname/reponame ``` ```bash npm install @myorg/privatepackage ``` ```bash npm install node-tap --save-dev ``` ```bash npm install dtrace-provider --save-optional ``` ```bash npm install readable-stream --save-exact ``` ```bash npm install ansi-regex --save-bundle ``` -------------------------------- ### SOCKS Associate UDP Relay with SocksClient Source: https://github.com/npm/cli/blob/latest/node_modules/socks/docs/examples/javascript/associateExample.md This example demonstrates how to use the SocksClient to establish a UDP relay using the 'associate' command. It sets up a local UDP socket to communicate with the SOCKS proxy, listens for the 'established' event to get the new UDP port from the proxy, and then sends UDP packets through the proxy to a specified destination. It also shows how to parse incoming UDP frames from the proxy. ```typescript const dgram = require('dgram'); const SocksClient = require('socks').SocksClient; // Create a local UDP socket for sending/receiving packets to/from the proxy. const udpSocket = dgram.createSocket('udp4'); udpSocket.bind(); // Listen for incoming UDP packets from the proxy server. udpSocket.on('message', (message, rinfo) => { console.log(SocksClient.parseUDPFrame(message)); /* { frameNumber: 0, remoteHost: { host: '8.8.8.8', port: 53 }, // The remote host that replied with a UDP packet data: // The data } */ }); const options = { proxy: { host: '104.131.124.203', port: 1081, type: 5 }, // This should be the ip and port of the expected client that will be sending UDP frames to the newly opened UDP port on the server. // Most SOCKS servers accept 0.0.0.0 as a wildcard address to accept UDP frames from any source. destination: { host: '0.0.0.0', port: 0 }, command: 'associate' }; const client = new SocksClient(options); // This event is fired when the SOCKS server has started listening on a new UDP port for UDP relaying. client.on('established', info => { console.log(info); /* { socket: , remoteHost: { // This is the remote port on the SOCKS proxy server to send UDP frame packets to. host: '104.131.124.203', port: 58232 } } */ // Send a udp frame to 8.8.8.8 on port 53 through the proxy. const packet = SocksClient.createUDPFrame({ remoteHost: { host: '8.8.8.8', port: 53 }, data: Buffer.from('hello') // A DNS lookup in the real world. }); // Send packet. udpSocket.send(packet, info.remoteHost.port, info.remoteHost.host); }); // SOCKS proxy failed to bind. client.on('error', () => { // Handle errors }); ``` -------------------------------- ### Running GYP Tests with gyptest.py Source: https://github.com/npm/cli/blob/latest/node_modules/node-gyp/gyp/docs/Testing.md Illustrates how to execute GYP test scripts using the `gyptest.py` runner. It shows examples of running a specific test script, all tests within a directory, and all tests in the entire project tree using different command-line arguments. ```bash $ python gyptest.py test/hello/gyptest-all.py PYTHONPATH=/home/knight/src/gyp/trunk/test/lib TESTGYP_FORMAT=scons /usr/bin/python test/hello/gyptest-all.py PASSED $ ``` ```bash $ python gyptest.py test/hello PYTHONPATH=/home/knight/src/gyp/trunk/test/lib TESTGYP_FORMAT=scons /usr/bin/python test/hello/gyptest-all.py PASSED /usr/bin/python test/hello/gyptest-default.py PASSED /usr/bin/python test/hello/gyptest-target.py PASSED $ ``` ```bash $ python gyptest.py -a PYTHONPATH=/home/knight/src/gyp/trunk/test/lib TESTGYP_FORMAT=scons /usr/bin/python test/configurations/gyptest-configurations.py PASSED /usr/bin/python test/defines/gyptest-defines.py PASSED . . . . /usr/bin/python test/variables/gyptest-commands.py PASSED $ ```