Skip to content

Registry Client API ​

The Registry client is the main interface for interacting with NPM registries. This document provides comprehensive API reference for all available methods.

Component Architecture ​

A Registry holds an Options, which lazily builds and caches an *http.Client via sync.Once, reusing the underlying TCP connection pool across requests:

Request Lifecycle ​

Taking GetPackageInformation as an example — context flows through the whole call and can cancel or time out at any point:

Registry Creation ​

NewRegistry ​

go
func NewRegistry(options ...*Options) *Registry

Creates a new registry client with optional configuration.

Parameters:

  • options - Optional configuration options

Returns:

  • *Registry - New registry client instance

Example:

go
// Default client (uses official NPM registry)
client := registry.NewRegistry()

// With custom options
options := registry.NewOptions().SetRegistryURL("https://custom-registry.com")
client := registry.NewRegistry(options)

Predefined Registry Clients ​

NewTaoBaoRegistry ​

go
func NewTaoBaoRegistry(options ...*Options) *Registry

Creates a client configured for Taobao NPM mirror (China).

NewNpmMirrorRegistry ​

go
func NewNpmMirrorRegistry(options ...*Options) *Registry

Creates a client configured for NPM mirror registry.

NewHuaWeiCloudRegistry ​

go
func NewHuaWeiCloudRegistry(options ...*Options) *Registry

Creates a client configured for Huawei Cloud NPM mirror (China).

Package Information Methods ​

GetPackageInformation ​

go
func (r *Registry) GetPackageInformation(ctx context.Context, packageName string) (*PackageInformation, error)

Retrieves comprehensive information about a package.

Parameters:

  • ctx - Context for request cancellation and timeout
  • packageName - Name of the NPM package

Returns:

  • *PackageInformation - Package metadata including all versions
  • error - Error if the request fails

Example:

go
pkg, err := client.GetPackageInformation(ctx, "react")
if err != nil {
    return err
}

fmt.Printf("Package: %s\n", pkg.Name)
fmt.Printf("Latest: %s\n", pkg.DistTags["latest"])
fmt.Printf("Description: %s\n", pkg.Description)

GetPackageVersion ​

go
func (r *Registry) GetPackageVersion(ctx context.Context, packageName, version string) (*PackageVersion, error)

Retrieves information about a specific package version.

Parameters:

  • ctx - Context for request cancellation and timeout
  • packageName - Name of the NPM package
  • version - Specific version to retrieve

Returns:

  • *PackageVersion - Version-specific package information
  • error - Error if the request fails

Example:

go
version, err := client.GetPackageVersion(ctx, "react", "18.2.0")
if err != nil {
    return err
}

fmt.Printf("Version: %s\n", version.Version)
fmt.Printf("Dependencies: %d\n", len(version.Dependencies))

Search Methods ​

SearchPackages ​

go
func (r *Registry) SearchPackages(ctx context.Context, query string, limit int) (*SearchResult, error)

Searches for packages matching the query.

Parameters:

  • ctx - Context for request cancellation and timeout
  • query - Search query string
  • limit - Maximum number of results to return

Returns:

  • *SearchResult - Search results with packages and metadata
  • error - Error if the request fails

Example:

go
results, err := client.SearchPackages(ctx, "react ui component", 10)
if err != nil {
    return err
}

fmt.Printf("Found %d results\n", results.Total)
for _, obj := range results.Objects {
    fmt.Printf("- %s: %s\n", obj.Package.Name, obj.Package.Description)
}

Statistics Methods ​

GetDownloadStats ​

go
func (r *Registry) GetDownloadStats(ctx context.Context, packageName, period string) (*DownloadStats, error)

Retrieves download statistics for a package.

Parameters:

  • ctx - Context for request cancellation and timeout
  • packageName - Name of the NPM package
  • period - Time period ("last-day", "last-week", "last-month")

Returns:

  • *DownloadStats - Download statistics
  • error - Error if the request fails

Example:

go
stats, err := client.GetDownloadStats(ctx, "react", "last-month")
if err != nil {
    return err
}

fmt.Printf("Downloads in last month: %d\n", stats.Downloads)

DownloadTarball ​

go
func (r *Registry) DownloadTarball(ctx context.Context, packageName, version, destPath string) error

Downloads an NPM package tarball to a local file path.

Parameters:

  • ctx - Context for cancellation and timeout control
  • packageName - Name of the package to download
  • version - Version to download (e.g., "18.0.0" or "latest")
  • destPath - Local file path where the tarball will be saved

Returns:

  • error - Error if the download fails

Example:

go
ctx := context.Background()

// Download specific version
err := client.DownloadTarball(ctx, "react", "18.0.0", "./react.tgz")
if err != nil {
    return fmt.Errorf("download failed: %w", err)
}

// Download latest version
err = client.DownloadTarball(ctx, "vue", "latest", "./vue.tgz")
if err != nil {
    return fmt.Errorf("download failed: %w", err)
}

// Verify the downloaded file
info, err := os.Stat("./react.tgz")
if err != nil {
    return err
}
fmt.Printf("File size: %d bytes\n", info.Size())

Using CNPM mirror for faster downloads in China:

go
options := registry.NewOptions().SetRegistryURL(registry.RegistryUrlCnpm)
client := registry.NewRegistry(options)

err := client.DownloadTarball(ctx, "axios", "1.0.0", "/tmp/axios.tgz")
if err != nil {
    log.Fatalf("Download failed: %v", err)
}

fmt.Println("Download successful!")

Registry Information Methods ​

GetRegistryInformation ​

go
func (r *Registry) GetRegistryInformation(ctx context.Context) (*RegistryInformation, error)

Retrieves information about the registry itself.

Parameters:

  • ctx - Context for request cancellation and timeout

Returns:

  • *RegistryInformation - Registry metadata and statistics
  • error - Error if the request fails

Example:

go
info, err := client.GetRegistryInformation(ctx)
if err != nil {
    return err
}

fmt.Printf("Registry: %s\n", info.DbName)
fmt.Printf("Total packages: %d\n", info.DocCount)
fmt.Printf("Data size: %d MB\n", info.DataSize/(1024*1024))

Method Index (76 methods) ​

All 76 methods grouped by domain. ctx is always context.Context; 🔒 marks write operations that require a valid token configured on the server (Options.Token).

Read-only requests go straight through the mirror/proxy to the Registry; write operations inject Authorization: Bearer <token> into the header, and the Registry authenticates before mutating:

Package Metadata (read-only) ​

MethodSignatureDescription
GetPackageInformation(ctx, name) → *models.Package, errorFull package metadata (can be 10MB+)
GetPackageInformationSummary(ctx, name) → *models.Package, errorLightweight summary (recommended)
GetAbbreviatedPackageInformation(ctx, name) → *models.Package, errorAbbreviated metadata
GetPackageVersion(ctx, name, version) → *models.Version, errorSpecific version metadata
GetPackageVersions(ctx, name) → []string, errorAll version numbers
GetPackageVersionCount(ctx, name) → int, errorTotal version count
GetPackageLatestVersion(ctx, name) → string, errorLatest version (dist-tags only)

dist-tags ​

MethodSignatureDescription
GetDistTags(ctx, name) → map[string]string, errorAll dist-tags
GetDistTagsAbbreviated(ctx, name) → map[string]string, errorAbbreviated dist-tags
GetDistTag(ctx, name, tag) → string, errorVersion a single tag points to
SetDistTag 🔒(ctx, name, tag, version) → errorSet a single dist-tag
SetDistTags 🔒(ctx, name, tags) → errorSet dist-tags in bulk
DeleteDistTag 🔒(ctx, name, tag) → errorDelete a dist-tag
MethodSignatureDescription
SearchPackages(ctx, query, limit) → *models.SearchResult, errorKeyword search (paginated)
SearchPackagesWithOptions(ctx, query, opts SearchOptions) → *models.SearchResult, errorAdvanced search (weighting / offset)

Download Statistics (always queries api.npmjs.org) ​

MethodSignatureDescription
GetDownloadStats(ctx, name, period) → *models.DownloadStats, errorDownload total for a period
GetDownloadStatsByDateRange(ctx, name, start, end) → *models.DownloadStats, errorCustom date range
GetDownloadRangeStats(ctx, name, period) → *models.DownloadRangeStats, errorDaily download trend
GetDownloadRangeStatsByDateRange(ctx, name, start, end) → *models.DownloadRangeStats, errorCustom range daily trend
GetBulkDownloadStats(ctx, names []string, period) → map[string]*models.DownloadStats, errorBulk download totals
GetBulkDownloadStatsByDateRange(ctx, names, start, end) → map[string]*models.DownloadStats, errorBulk custom range
GetBulkDownloadRangeStats(ctx, names, period) → map[string]*models.DownloadRangeStats, errorBulk daily trend
GetBulkDownloadRangeStatsByDateRange(ctx, names, start, end) → map[string]*models.DownloadRangeStats, errorBulk custom range daily trend

Download Tarball ​

MethodSignatureDescription
DownloadTarball(ctx, name, version, destPath) → errorDownload a tarball to a local path

Security Audit (read-only) ​

MethodSignatureDescription
QuickAudit(ctx, payload *models.QuickAuditRequest) → *models.QuickAuditResult, errorQuick audit (name→version)
BulkAudit(ctx, advisories map[string][]string) → map[string][]models.Advisory, errorBulk audit
GetAdvisory(ctx, advisoryID int) → *models.Advisory, errorGet an advisory by ID
ListAdvisories(ctx, opts models.AdvisoryListOptions) → []models.Advisory, errorAdvisory list

Stars (read + write) ​

MethodSignatureDescription
GetStarredByPackage(ctx, name) → []string, errorUsers who starred a package
GetStarredByUser(ctx, username) → []string, errorPackages starred by a user
StarPackage 🔒(ctx, name) → errorStar a package
UnstarPackage 🔒(ctx, name) → errorUnstar a package

Access Control & Collaborators ​

MethodSignatureDescription
GetPackageAccess 🔒(ctx, name) → *models.PackageAccess, errorPackage access settings
SetPackageAccess 🔒(ctx, name, access *models.PackageAccessUpdate) → errorUpdate package access
GrantAccess 🔒(ctx, name, user, permission) → errorGrant collaborator permission
RevokeAccess 🔒(ctx, name, user) → errorRemove a collaborator
ListCollaborators 🔒(ctx, name) → []models.Collaborator, errorCollaborator list

Publish & Deprecate ​

MethodSignatureDescription
PublishPackage 🔒(ctx, pkg *models.Package) → errorPublish a package
PublishPackageFromTarball 🔒(ctx, name, version string, tarball []byte, meta *models.PublishMetadata) → errorPublish from a tarball
DeprecateVersion 🔒(ctx, name, version, message) → errorDeprecate a version
UnpublishPackage 🔒(ctx, name) → errorUnpublish an entire package (dangerous)
UnpublishPackageVersion 🔒(ctx, name, version) → errorUnpublish a version

Token Management (require token) ​

MethodSignatureDescription
ListTokens(ctx) → []models.Token, errorToken list
GetToken(ctx, tokenID) → *models.Token, errorSingle token details
CreateToken 🔒(ctx, opts *models.TokenCreation) → *models.Token, errorCreate a token
DeleteToken 🔒(ctx, tokenID) → errorDelete a token

Users & Auth ​

MethodSignatureDescription
WhoAmI(ctx) → string, errorCurrent authenticated username
GetUser 🔒(ctx, name) → *models.UserProfile, errorUser profile
Login(ctx, name, password) → *models.LoginResult, errorLog in
CreateUser(ctx, user *models.UserCreation) → *models.LoginResult, errorSign up

Orgs & Teams (require token) ​

MethodSignatureDescription
GetOrg(ctx, orgName) → *models.Organization, errorOrganization details
ListOrgMembers(ctx, orgName) → []string, errorOrg members
ListOrgPackages(ctx, orgName) → []string, errorOrg packages
CreateOrg 🔒(ctx, orgName) → *models.Organization, errorCreate an organization
DeleteOrg 🔒(ctx, orgName) → errorDelete an organization
AddOrgMember 🔒(ctx, orgName, username) → errorAdd an org member
RemoveOrgMember 🔒(ctx, orgName, username) → errorRemove an org member
ListTeams(ctx, orgName) → []models.Team, errorTeam list
ListTeamMembers(ctx, orgName, teamName) → []string, errorTeam members
ListTeamPackages(ctx, orgName, teamName) → []string, errorTeam packages
CreateTeam 🔒(ctx, orgName, teamName) → *models.Team, errorCreate a team
DeleteTeam 🔒(ctx, orgName, teamName) → errorDelete a team
AddTeamMember 🔒(ctx, orgName, teamName, username) → errorAdd a team member
RemoveTeamMember 🔒(ctx, orgName, teamName, username) → errorRemove a team member

Webhooks (require token) ​

MethodSignatureDescription
ListHooks(ctx, opts models.HookListOptions) → []models.Hook, errorWebhook list
GetHook(ctx, hookID) → *models.Hook, errorWebhook details
CreateHook 🔒(ctx, hook *models.HookCreation) → *models.Hook, errorCreate a webhook
UpdateHook 🔒(ctx, hookID, hook *models.HookUpdate) → *models.Hook, errorUpdate a webhook
DeleteHook 🔒(ctx, hookID) → errorDelete a webhook

CouchDB Views & Changes Feed (advanced — for mirroring / incremental sync) ​

MethodSignatureDescription
GetRegistryInformation(ctx) → *models.RegistryInformation, errorRegistry status and stats
RegistryHealthCheck(ctx) → bool, errorRegistry health check
IsPrivateRegistry() → boolWhether it's a private registry
GetChanges(ctx, opts models.ChangesOptions) → *models.ChangesResult, errorChanges feed
GetAllDocs(ctx, opts models.AllDocsOptions) → *models.AllDocsResult, errorAll documents
GetView(ctx, viewName, opts models.ViewOptions) → *models.ViewResult, errorView query

Configuration ​

MethodSignatureDescription
GetOptions() → *OptionsCurrent configuration options

Error Handling ​

All methods return errors that can be handled using standard Go error handling patterns. The SDK exposes typed sentinel errors you can branch on with errors.Is():

go
pkg, err := client.GetPackageInformation(ctx, "nonexistent-package")
if err != nil {
    switch {
    case errors.Is(err, context.DeadlineExceeded):
        log.Println("Request timeout")
    case errors.Is(err, context.Canceled):
        log.Println("Request canceled")
    default:
        log.Printf("API error: %v", err)
    }
    return
}

Context Usage ​

All methods accept a context.Context parameter for:

Timeout Control ​

go
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

pkg, err := client.GetPackageInformation(ctx, "react")

Request Cancellation ​

go
ctx, cancel := context.WithCancel(context.Background())

// Cancel request from another goroutine
go func() {
    time.Sleep(5 * time.Second)
    cancel()
}()

pkg, err := client.GetPackageInformation(ctx, "react")

Request Values ​

go
ctx := context.WithValue(context.Background(), "request-id", "12345")
pkg, err := client.GetPackageInformation(ctx, "react")

Best Practices ​

1. Always Use Context ​

go
// Good
ctx := context.Background()
pkg, err := client.GetPackageInformation(ctx, "react")

// Better - with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pkg, err := client.GetPackageInformation(ctx, "react")

2. Handle Errors Appropriately ​

go
pkg, err := client.GetPackageInformation(ctx, packageName)
if err != nil {
    // Log the error with context
    log.Printf("Failed to get package %s: %v", packageName, err)
    return fmt.Errorf("package lookup failed: %w", err)
}

3. Reuse Client Instances ​

go
// Good - reuse client
client := registry.NewRegistry()
for _, pkg := range packages {
    info, err := client.GetPackageInformation(ctx, pkg)
    // Process info...
}

// Avoid - creating new clients
for _, pkg := range packages {
    client := registry.NewRegistry() // Wasteful
    info, err := client.GetPackageInformation(ctx, pkg)
}

4. Use Appropriate Timeouts ​

go
// Short timeout for quick operations
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Longer timeout for search operations
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

Next Steps ​

Released under the MIT License.