unpkg/modules/utils/parsePackageURL.js

34 lines
879 B
JavaScript
Raw Normal View History

2019-01-06 00:50:05 +00:00
import url from 'url';
2018-04-04 19:06:17 +00:00
const packageURLFormat = /^\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(\/.*)?$/;
2017-05-25 18:25:42 +00:00
2019-02-01 17:17:42 +00:00
export default function parsePackageURL(originalURL) {
2019-01-02 20:56:24 +00:00
let { pathname, search, query } = url.parse(originalURL, true);
try {
pathname = decodeURIComponent(pathname);
} catch (error) {
return null;
}
2017-08-12 16:40:53 +00:00
2018-04-04 19:06:17 +00:00
const match = packageURLFormat.exec(pathname);
2017-05-25 18:25:42 +00:00
// Disallow invalid URL formats.
2018-03-20 17:34:31 +00:00
if (match == null) {
return null;
}
2017-05-25 18:25:42 +00:00
2018-02-18 02:00:56 +00:00
const packageName = match[1];
const packageVersion = match[2] || 'latest';
const filename = (match[3] || '').replace(/\/\/+/g, '/');
2017-05-25 18:25:42 +00:00
2017-11-08 16:57:15 +00:00
return {
// If the URL is /@scope/name@version/file.js?main=browser:
pathname, // /@scope/name@version/path.js
2018-12-17 17:38:05 +00:00
search: search || '', // ?main=browser
2017-11-08 16:57:15 +00:00
query, // { main: 'browser' }
packageName, // @scope/name
packageVersion, // version
2017-11-08 16:57:15 +00:00
filename // /file.js
2018-02-18 02:00:56 +00:00
};
2017-05-25 18:25:42 +00:00
}