astro/packages/integrations/markdoc/src/index.ts

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

76 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-02-06 16:13:57 +00:00
import type { AstroIntegration } from 'astro';
2023-02-06 16:21:17 +00:00
import type { InlineConfig } from 'vite';
2023-02-06 21:11:01 +00:00
import _Markdoc from '@markdoc/markdoc';
import fs from 'node:fs';
import { parseFrontmatter } from './utils.js';
import { fileURLToPath } from 'node:url';
const contentEntryType = {
extensions: ['.mdoc'],
async getEntryInfo({ fileUrl }: { fileUrl: URL }) {
const rawContents = await fs.promises.readFile(fileUrl, 'utf-8');
const parsed = parseFrontmatter(rawContents, fileURLToPath(fileUrl));
return {
data: parsed.data,
body: parsed.content,
slug: parsed.data.slug,
rawData: parsed.matter,
};
},
async render({ entry }: { entry: any }) {
function getParsed() {
return Markdoc.parse(entry.body);
}
async function getTransformed(inlineConfig: any) {
let config = inlineConfig;
// TODO: load config file
// if (!config) {
// try {
// const importedConfig = await import('./markdoc.config.ts');
// config = importedConfig.default.transform;
// } catch {}
// }
return Markdoc.transform(getParsed(), config);
}
return { getParsed, getTransformed };
},
};
2023-02-06 16:13:57 +00:00
export default function markdoc(partialOptions: {} = {}): AstroIntegration {
return {
name: '@astrojs/markdoc',
hooks: {
'astro:config:setup': async ({ updateConfig, config, addContentEntryType, command }: any) => {
addContentEntryType(contentEntryType);
2023-02-06 16:13:57 +00:00
console.log('Markdoc working!');
2023-02-06 23:09:23 +00:00
const markdocConfigUrl = new URL('./markdoc.config.ts', config.srcDir);
2023-02-06 16:21:17 +00:00
const viteConfig: InlineConfig = {
plugins: [
{
name: '@astrojs/markdoc',
async transform(code, id) {
if (!id.endsWith('.mdoc')) return;
2023-02-06 23:09:23 +00:00
return `import { Markdoc } from '@astrojs/markdoc';\nexport const body = ${JSON.stringify(
code
)};\nexport function getParsed() { return Markdoc.parse(body); }\nexport async function getTransformed(inlineConfig) {
let config = inlineConfig;
if (!config) {
try {
const importedConfig = await import(${JSON.stringify(markdocConfigUrl.pathname)});
config = importedConfig.default.transform;
} catch {}
}
return Markdoc.transform(getParsed(), config) }`;
2023-02-06 16:21:17 +00:00
},
},
],
};
updateConfig({ vite: viteConfig });
2023-02-06 16:13:57 +00:00
},
},
};
}
2023-02-06 21:11:01 +00:00
export const Markdoc = _Markdoc;