summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/frontmatter-injection.ts
blob: 91b98ebcba63a2bf4381c2b14b682246b7072bca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import type { VFileData as Data, VFile } from 'vfile';
import type { MarkdownAstroData } from './types.js';

function isValidAstroData(obj: unknown): obj is MarkdownAstroData {
	if (typeof obj === 'object' && obj !== null && obj.hasOwnProperty('frontmatter')) {
		const { frontmatter } = obj as any;
		try {
			// ensure frontmatter is JSON-serializable
			JSON.stringify(frontmatter);
		} catch {
			return false;
		}
		return typeof frontmatter === 'object' && frontmatter !== null;
	}
	return false;
}

export class InvalidAstroDataError extends TypeError {}

export function safelyGetAstroData(vfileData: Data): MarkdownAstroData | InvalidAstroDataError {
	const { astro } = vfileData;

	if (!astro || !isValidAstroData(astro)) {
		return new InvalidAstroDataError();
	}

	return astro;
}

export function setVfileFrontmatter(vfile: VFile, frontmatter: Record<string, any>) {
	vfile.data ??= {};
	vfile.data.astro ??= {};
	(vfile.data.astro as any).frontmatter = frontmatter;
}