@magnolia/npm-helper
v0.1.1
Published
Utility library for querying npm registries: search, package metadata, .npmrc auth resolution, and .npmrc generation
Maintainers
Readme
Magnolia NPM Helper
Utility library for querying npm registries with built-in .npmrc authentication support. Provides multi-registry search, package metadata lookup, automatic credential resolution, and interactive .npmrc generation for Magnolia Nexus repositories.
- Simple methods for search and package metadata lookup across multiple registries
- Automatic
.npmrccredential resolution (Bearer tokens, Basic auth, username/password) - Interactive CLI for configuring Magnolia Nexus
.npmrcauthentication - Automatic Nexus mirror selection based on geographic location
- Built-in version control integration (
.gitignoremanagement)
Install
npm install @magnolia/npm-helperFor local development:
npm install
npm run buildCLI Tool
The package provides a CLI with the create-npmrc command for configuring .npmrc authentication:
npx @magnolia/npm-helper <command> [options]Available Commands:
- create-npmrc — Configure
.npmrcwith Magnolia Nexus credentials
create-npmrc
Configure your .npmrc file with Magnolia Nexus credentials.
Interactive Mode
Run without options for an interactive prompt-based experience:
# Run with npx
npx @magnolia/npm-helper create-npmrc
# Or run locally during development
node dist/cli.js create-npmrcThe CLI will guide you through:
- Choosing location (project or global
.npmrc) - Choosing Nexus region (Global, US, AP, or custom URL)
- Entering your authentication token
By default, the CLI configures the npm-dx-core repository. To use npm-enterprise, specify the --repository option (requires Magnolia staff access).
Non-Interactive Mode
Use command-line options to bypass prompts:
# Configure project .npmrc with npm-dx-core in US region
npx @magnolia/npm-helper create-npmrc --location project --repository npm-dx-core --region US --token YOUR_TOKEN
# Configure global .npmrc with custom URL
npx @magnolia/npm-helper create-npmrc -l global -r npm-enterprise -u https://custom.registry.com/repository -t YOUR_TOKEN
# Enable always-auth
npx @magnolia/npm-helper create-npmrc --location project --repository npm-dx-core --region GLOBAL --token YOUR_TOKEN --always-authCLI Options
| Option | Description |
| ------------------------- | ------------------------------------------------------------------------------- |
| -l, --location <type> | Location for .npmrc file (project or global) |
| -r, --repository <name> | Magnolia repository (npm-dx-core or npm-enterprise, default: npm-dx-core) |
| --region <region> | Nexus region (GLOBAL, US, or AP) |
| -u, --custom-url <url> | Custom registry URL (alternative to region) |
| -t, --token <token> | Nexus authentication token |
| --always-auth | Enable always-auth in .npmrc |
| --overwrite | Overwrite existing auth token without prompting |
| -h, --help | Display help information |
| -v, --version | Display version number |
Any omitted options will trigger interactive prompts for those values.
Auth Token Behavior
When updating an existing .npmrc file with a new auth token:
- If the token is identical to the existing one, the CLI will skip the update and notify you
- If the token is different and
--overwriteis not specified, the CLI will prompt you to confirm - If
--overwriteis specified, the existing token will be replaced without prompting - If the token doesn't exist yet, it will be added regardless of the
--overwriteflag
Programmatic Usage
Registry Search
import { searchRegistries, fetchPackageInfo } from '@magnolia/npm-helper';
// Search multiple registries in parallel
const results = await searchRegistries({
registries: [
'https://registry.npmjs.org',
'https://nexus.magnolia-cms.com/repository/npm-dx-core/',
],
query: '@magnolia-dx',
packagePattern: /^@magnolia-dx\//,
});
console.log(`Found ${results.length} packages`);
// Fetch a single package's metadata
const info = await fetchPackageInfo(
'@magnolia-dx/magnolia-design',
'https://nexus.magnolia-cms.com/repository/npm-dx-core/',
);.npmrc Auth Resolution
import {
resolveRegistryAuth,
buildRegistryHeaders,
} from '@magnolia/npm-helper';
// Resolve auth from .npmrc files
const auth = resolveRegistryAuth(
'https://nexus.magnolia-cms.com/repository/npm-dx-core/',
process.cwd(),
);
if (auth?.token) {
console.log('Found Bearer token');
} else if (auth?.basicAuth) {
console.log('Found Basic auth');
}
// Or get ready-made fetch headers
const headers = buildRegistryHeaders(
'https://nexus.magnolia-cms.com/repository/npm-dx-core/',
);.npmrc Generation
import {
updateNpmrc,
resolveNpmrc,
MAGNOLIA_NPM_REGISTRY_URLS,
} from '@magnolia/npm-helper';
// Read and parse an existing .npmrc
const npmrc = await resolveNpmrc(process.cwd());
console.log('Repository mappings:', npmrc.repositoryMappings);
console.log('Auth tokens:', npmrc.repositoryAuth);
// Create or update .npmrc with token auth
await updateNpmrc({
npmrcDirectory: process.cwd(),
repository: 'npm-dx-core',
auth: { token: 'my-auth-token' },
});
// Create or update .npmrc with username/password auth
await updateNpmrc({
npmrcDirectory: process.cwd(),
repository: 'npm-dx-core',
rootUrl: MAGNOLIA_NPM_REGISTRY_URLS.US,
auth: { username: 'myuser', password: 'mypass' },
});Interactive Setup (Programmatic)
import {
setupNpmrcInteractive,
detectBestRegion,
createCliLogger,
} from '@magnolia/npm-helper';
import { initI18n } from '@magnolia/cli-helper';
const logger = createCliLogger();
const i18n = initI18n('magnolia-npm-helper', 'translation', './locales');
// Optionally detect the best region
const bestRegion = await detectBestRegion();
console.log(`Best region: ${bestRegion.name}`);
// Run interactive setup
const result = await setupNpmrcInteractive(
{
location: 'project',
repository: 'npm-dx-core',
},
i18n,
logger,
);
if (result.success) {
console.log(`Successfully configured ${result.npmrcPath}`);
} else if (result.cancelled) {
console.log('Setup was cancelled by user');
} else {
console.error(`Setup failed: ${result.error}`);
}API Reference
Registry Search Functions
| Function | Description |
| ---------------------------------- | --------------------------------------------------- |
| searchRegistries(options) | Search multiple registries in parallel, deduplicate |
| fetchPackageInfo(name, url, ...) | Fetch single package metadata by name |
.npmrc Auth Resolution Functions
| Function | Description |
| ---------------------------------------- | ------------------------------------------------------ |
| resolveRegistryAuth(url, projectDir?) | Resolve auth from .npmrc files (project then global) |
| buildRegistryHeaders(url, projectDir?) | Build fetch headers with auth injected |
.npmrc Management Functions
| Function | Description |
| ------------------------- | ---------------------------------------------------- |
| updateNpmrc(options) | Create/update .npmrc with registry config and auth |
| resolveNpmrc(directory) | Read and parse .npmrc file into structured data |
Interactive Setup Functions
| Function | Description |
| ---------------------------------------------- | ------------------------------------------------ |
| setupNpmrcInteractive(options, i18n, logger) | Full interactive .npmrc setup with prompts |
| detectBestRegion() | Detect best Nexus mirror via latency measurement |
| promptAuthenticationMethod(i18n) | Prompt for auth method (token vs. credentials) |
| promptForMissingOptions(...) | Prompt for missing config options |
Nexus Mirror Resolution Functions
| Function | Description |
| ------------------------------------- | ------------------------------------------------ |
| resolveNexusUrl(url, options?) | Sync: resolve best Nexus mirror by timezone |
| resolveNexusUrlAsync(url, options?) | Async: resolve with optional latency measurement |
| listKnownNexusHosts() | List all available Nexus mirrors |
Version Control Functions
| Function | Description |
| ---------------------------------------- | ------------------------------------------- |
| detectVcs(directory) | Detect VCS type (git/svn/hg) in a directory |
| getIgnoreFileName(vcsType) | Get ignore file name for VCS type |
| isNpmrcIgnored(directory, ignoreFile) | Check if .npmrc is in the ignore file |
| addToIgnoreFile(directory, ignoreFile) | Add .npmrc entry to the ignore file |
Constants
| Constant | Description |
| ----------------------------------- | ---------------------------------------------- |
| MAGNOLIA_NPM_REGISTRY_URLS.GLOBAL | https://nexus.magnolia-cms.com/repository |
| MAGNOLIA_NPM_REGISTRY_URLS.US | https://nexus.us.magnolia-cms.com/repository |
| MAGNOLIA_NPM_REGISTRY_URLS.AP | https://nexus.ap.magnolia-cms.com/repository |
Authentication Priority
When resolving .npmrc auth (read path):
_authToken— Bearer token (highest priority)_auth— Base64-encodeduser:passwordfor Basic authusername+_password— Combined into Basic auth
When writing .npmrc auth:
- Token auth — Written as
:_authToken(Bearer) - Username/password auth — Written as
:username+:_password(Base64-encoded)
Build & Test
npm run build # TypeScript -> dist/
npm test # lint + build + jest
npm run test:unit # jest only (faster iteration)
npm run dev # tsc --watch
npm run lint # eslint
npm run format # prettier checkLicense
Dual-license: Magnolia Network Agreement or GNU General Public License v3.
