import https from 'https' ; import semver from 'semver' ; const { NPM_REGISTRY_URL = 'https://registry.npmjs.com' } = process . env ; param name export async function fetchManifest ( name ) { const encodedPackage = escapePackageName ( name ) ; const manifest = await fetchJSON ( `${ NPM_REGISTRY_URL }/${ encodedPackage }` ) ; if ( ! isManifest ( manifest ) ) { throw new Error ( `Package "${ name }" was not found` ) ; } if ( manifest . time . unpublished ) { throw new Error ( `Package "${ name }" was unpublished` ) ; } return manifest ; } function isManifest ( obj ) { return typeof obj === 'object' && obj !== null && 'name' in obj && 'dist-tags' in obj ; } function fetchJSON ( url ) { const { hostname , port , pathname } = new URL ( url ) ; const options = { method : 'GET' , port : port || 443 , hostname : hostname , path : pathname , } ; return new Promise < NpmManifest | null > ( ( resolve , reject ) => { const req = https . request ( options , res => { res . setEncoding ( 'utf8' ) ; if ( res . statusCode === 404 ) { resolve ( null ) ; return ; } let str = '' ; res . on ( 'data' , data => { str += data ; } ) ; res . on ( 'end' , ( ) => { if ( str ?. startsWith ( '{' ) ) { resolve ( JSON . parse ( str ) ) ; } else { resolve ( null ) ; } } ) ; } ) ; req . on ( 'error' , error => { reject ( error ) ; } ) ; req . end ( ) ; } ) ; } /**
 * Get all the published npm dist tags
 * which returns object {tagname => version}
 */ export function getAllDistTags ( manifest ) { return manifest [ 'dist-tags' ] ; } /**
 * Get all versions of the npm package and order
 * by semver oldest to newest
 */ export function getAllVersions ( manifest ) { return Object . keys ( manifest . versions ) . sort ( ( a , b ) => { return semver . gt ( a , b ) ? 1 : semver . eq ( a , b ) ? 0 : - 1 ; } ) ; } /**
 * Get the most recent versions of the npm package.
 * Returns (count * 2 + 1) results.
 */ export function getVersionsForChart ( allVersions , version , count ) { const total = count * 2 + 1 ; const index = allVersions . indexOf ( version ) ; let start = index - count ; let end = index + count + 1 ; if ( end > allVersions . length ) { const tmp = allVersions . length - total ; start = tmp > 0 ? tmp : 0 ; } else if ( start < 0 ) { start = 0 ; end = start + total ; } return allVersions . slice ( start , end ) ; } /**
 * Get the npm publish date of a specific version
 */ export function getPublishDate ( manifest , version ) { return manifest ?. time [ version ] || '' ; } /**
 * Escape an npm package name.
 * The registry expects the slashes in the (scoped) package names
 * to be sent escaped.
 */ function escapePackageName ( name ) { return name . replace ( /\//g , '%2f' ) ; }