astro/packages/integrations/mdx/src/utils.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

40 lines
1 KiB
TypeScript
Raw Normal View History

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