unpkg/server/utils/parsePackageURL.js

40 lines
941 B
JavaScript
Raw Normal View History

const url = require('url')
2017-05-25 18:25:42 +00:00
const URLFormat = /^\/((?:@[^\/@]+\/)?[^\/@]+)(?:@([^\/]+))?(\/.*)?$/
function decodeParam(param) {
2017-08-12 16:40:53 +00:00
if (param) {
try {
return decodeURIComponent(param)
} catch (error) {
// Ignore invalid params.
}
}
2017-08-12 16:40:53 +00:00
return ''
}
2017-05-25 18:25:42 +00:00
function parsePackageURL(packageURL) {
const { pathname, search, query } = url.parse(packageURL, true)
2017-05-25 18:25:42 +00:00
const match = URLFormat.exec(pathname)
if (match == null)
return null
const packageName = match[1]
const packageVersion = decodeParam(match[2]) || 'latest'
2017-05-25 18:25:42 +00:00
const filename = decodeParam(match[3])
return { // If the URL is /@scope/name@version/file.js?main=browser:
pathname, // /@scope/name@version/path.js
search, // ?main=browser
query, // { main: 'browser' }
packageName, // @scope/name
packageVersion, // version
filename // /file.js
2017-05-25 18:25:42 +00:00
}
}
2017-08-19 18:44:01 +00:00
module.exports = parsePackageURL