2017-08-11 03:43:20 +00:00
|
|
|
require('isomorphic-fetch')
|
2017-08-17 05:47:24 +00:00
|
|
|
const createCache = require('./createCache')
|
2017-08-11 03:43:20 +00:00
|
|
|
const createMutex = require('./createMutex')
|
|
|
|
|
|
|
|
const RegistryURL = process.env.NPM_REGISTRY_URL || 'https://registry.npmjs.org'
|
|
|
|
|
2017-08-17 05:47:24 +00:00
|
|
|
const PackageInfoCache = createCache('packageInfo')
|
|
|
|
|
2017-08-11 03:43:20 +00:00
|
|
|
function fetchPackageInfo(packageName) {
|
2017-08-11 14:35:55 +00:00
|
|
|
console.log(`info: Fetching package info for ${packageName}`)
|
2017-08-11 03:43:20 +00:00
|
|
|
|
|
|
|
let encodedPackageName
|
|
|
|
if (packageName.charAt(0) === '@') {
|
|
|
|
encodedPackageName = `@${encodeURIComponent(packageName.substring(1))}`
|
|
|
|
} else {
|
|
|
|
encodedPackageName = encodeURIComponent(packageName)
|
|
|
|
}
|
|
|
|
|
|
|
|
const url = `${RegistryURL}/${encodedPackageName}`
|
|
|
|
|
|
|
|
return fetch(url, {
|
|
|
|
headers: { 'Accept': 'application/json' }
|
2017-08-17 05:47:24 +00:00
|
|
|
}).then(function (res) {
|
|
|
|
return res.status === 404 ? null : res.json()
|
2017-08-11 03:43:20 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const PackageNotFound = 'PackageNotFound'
|
|
|
|
|
|
|
|
// This mutex prevents multiple concurrent requests to
|
|
|
|
// the registry for the same package info.
|
|
|
|
const fetchMutex = createMutex(function (packageName, callback) {
|
|
|
|
fetchPackageInfo(packageName).then(function (value) {
|
|
|
|
if (value == null) {
|
|
|
|
// Cache 404s for 5 minutes. This prevents us from making
|
|
|
|
// unnecessary requests to the registry for bad package names.
|
|
|
|
// In the worst case, a brand new package's info will be
|
|
|
|
// available within 5 minutes.
|
|
|
|
PackageInfoCache.set(packageName, PackageNotFound, 300, function () {
|
|
|
|
callback(null, value)
|
|
|
|
})
|
|
|
|
} else {
|
2017-08-12 02:17:02 +00:00
|
|
|
// Cache valid package info for 1 minute.
|
2017-08-11 03:43:20 +00:00
|
|
|
PackageInfoCache.set(packageName, value, 60, function () {
|
|
|
|
callback(null, value)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}, function (error) {
|
|
|
|
// Do not cache errors.
|
|
|
|
PackageInfoCache.del(packageName, function () {
|
|
|
|
callback(error)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
function getPackageInfo(packageName, callback) {
|
|
|
|
PackageInfoCache.get(packageName, function (error, value) {
|
2017-08-17 05:47:24 +00:00
|
|
|
if (error || value != null) {
|
|
|
|
callback(error, value === PackageNotFound ? null : value)
|
2017-08-11 03:43:20 +00:00
|
|
|
} else {
|
2017-08-11 05:11:55 +00:00
|
|
|
fetchMutex(packageName, packageName, callback)
|
2017-08-11 03:43:20 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
get: getPackageInfo
|
|
|
|
}
|