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);
|
2019-01-02 20:32:09 +00:00
|
|
|
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
|
|
|
|
2017-11-15 00:44:53 +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];
|
2019-01-02 20:32:09 +00:00
|
|
|
const packageVersion = match[2] || 'latest';
|
2019-07-25 00:55:13 +00:00
|
|
|
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
|
2017-08-10 17:12:50 +00:00
|
|
|
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
|
|
|
}
|