44 lines
1.1 KiB
JavaScript
44 lines
1.1 KiB
JavaScript
function sanitizeHttpBaseUrl(rawValue) {
|
|
if (!rawValue) return null;
|
|
|
|
try {
|
|
const url = new URL(rawValue);
|
|
if (!['http:', 'https:'].includes(url.protocol)) return null;
|
|
|
|
url.search = '';
|
|
url.hash = '';
|
|
url.pathname = url.pathname.replace(/\/+$/, '');
|
|
return url.toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function buildHttpDownloadUrl(rawBaseUrl, filePath) {
|
|
const baseUrl = sanitizeHttpBaseUrl(rawBaseUrl);
|
|
if (!baseUrl || !filePath) return null;
|
|
|
|
try {
|
|
const url = new URL(baseUrl);
|
|
const normalizedPath = filePath.startsWith('/') ? filePath : `/${filePath}`;
|
|
const safeSegments = normalizedPath
|
|
.split('/')
|
|
.filter(Boolean)
|
|
.map((segment) => encodeURIComponent(segment));
|
|
const safePath = safeSegments.length ? `/${safeSegments.join('/')}` : '';
|
|
|
|
const basePath = url.pathname.replace(/\/+$/, '');
|
|
url.pathname = `${basePath}${safePath || '/'}` || '/';
|
|
url.search = '';
|
|
url.hash = '';
|
|
return url.toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
buildHttpDownloadUrl,
|
|
sanitizeHttpBaseUrl
|
|
};
|