2022-07-20 14:56:32 +00:00
|
|
|
import type { AstroConfig } from 'astro';
|
|
|
|
|
|
|
|
function appendForwardSlash(path: string) {
|
|
|
|
return path.endsWith('/') ? path : path + '/';
|
|
|
|
}
|
|
|
|
|
2022-07-28 14:58:44 +00:00
|
|
|
interface FileInfo {
|
|
|
|
fileId: string;
|
|
|
|
fileUrl: string;
|
|
|
|
}
|
|
|
|
|
2022-07-20 14:56:32 +00:00
|
|
|
/** @see 'vite-plugin-utils' for source */
|
2022-07-28 14:58:44 +00:00
|
|
|
export function getFileInfo(id: string, config: AstroConfig): FileInfo {
|
2022-07-20 14:56:32 +00:00
|
|
|
const sitePathname = appendForwardSlash(
|
|
|
|
config.site ? new URL(config.base, config.site).pathname : config.base
|
|
|
|
);
|
|
|
|
|
2022-07-28 14:58:44 +00:00
|
|
|
// Try to grab the file's actual URL
|
|
|
|
let url: URL | undefined = undefined;
|
|
|
|
try {
|
|
|
|
url = new URL(`file://${id}`);
|
|
|
|
} catch {}
|
|
|
|
|
2022-07-20 14:56:32 +00:00
|
|
|
const fileId = id.split('?')[0];
|
2022-07-28 14:58:44 +00:00
|
|
|
let fileUrl: string;
|
|
|
|
const isPage = fileId.includes('/pages/');
|
2022-07-28 15:00:32 +00:00
|
|
|
if (isPage) {
|
2022-07-28 14:58:44 +00:00
|
|
|
fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, '');
|
2022-07-28 15:00:32 +00:00
|
|
|
} else if (url && url.pathname.startsWith(config.root.pathname)) {
|
2022-07-28 14:58:44 +00:00
|
|
|
fileUrl = url.pathname.slice(config.root.pathname.length);
|
|
|
|
} else {
|
|
|
|
fileUrl = fileId;
|
|
|
|
}
|
|
|
|
|
2022-07-20 14:56:32 +00:00
|
|
|
if (fileUrl && config.trailingSlash === 'always') {
|
|
|
|
fileUrl = appendForwardSlash(fileUrl);
|
|
|
|
}
|
|
|
|
return { fileId, fileUrl };
|
|
|
|
}
|