summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/frontmatter-injection.ts
blob: 4828873fd2c128170dbb7db117e5217b9ee66db4 (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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;
}

/**
 * @deprecated Use `setVfileFrontmatter` instead
 */
export function toRemarkInitializeAstroData({
	userFrontmatter,
}: {
	userFrontmatter: Record<string, any>;
}) {
	return () =>
		function (tree: any, vfile: VFile) {
			if (!vfile.data.astro) {
				vfile.data.astro = { frontmatter: userFrontmatter };
			}
		};
}