summaryrefslogtreecommitdiff
path: root/packages/integrations/markdoc/src/load-config.ts
blob: 723516ce7bfdc6487a1a1f48f074834318dafe87 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import type { AstroConfig } from 'astro';
import { build as esbuild } from 'esbuild';
import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import type { AstroMarkdocConfig } from './config.js';
import { MarkdocError } from './utils.js';

export const SUPPORTED_MARKDOC_CONFIG_FILES = [
	'markdoc.config.js',
	'markdoc.config.mjs',
	'markdoc.config.mts',
	'markdoc.config.ts',
];

export type MarkdocConfigResult = {
	config: AstroMarkdocConfig;
	fileUrl: URL;
};

export async function loadMarkdocConfig(
	astroConfig: Pick<AstroConfig, 'root'>
): Promise<MarkdocConfigResult | undefined> {
	let markdocConfigUrl: URL | undefined;
	for (const filename of SUPPORTED_MARKDOC_CONFIG_FILES) {
		const filePath = new URL(filename, astroConfig.root);
		if (!fs.existsSync(filePath)) continue;

		markdocConfigUrl = filePath;
		break;
	}
	if (!markdocConfigUrl) return;

	const { code } = await bundleConfigFile({
		markdocConfigUrl,
		astroConfig,
	});
	const config: AstroMarkdocConfig = await loadConfigFromBundledFile(astroConfig.root, code);

	return {
		config,
		fileUrl: markdocConfigUrl,
	};
}

/**
 * Bundle config file to support `.ts` files.
 * Simplified fork from Vite's `bundleConfigFile` function:
 * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/config.ts#L961
 */
async function bundleConfigFile({
	markdocConfigUrl,
	astroConfig,
}: {
	markdocConfigUrl: URL;
	astroConfig: Pick<AstroConfig, 'root'>;
}): Promise<{ code: string; dependencies: string[] }> {
	let markdocError: MarkdocError | undefined;

	const result = await esbuild({
		absWorkingDir: fileURLToPath(astroConfig.root),
		entryPoints: [fileURLToPath(markdocConfigUrl)],
		outfile: 'out.js',
		write: false,
		target: ['node16'],
		platform: 'node',
		packages: 'external',
		bundle: true,
		format: 'esm',
		sourcemap: 'inline',
		metafile: true,
		plugins: [
			{
				name: 'stub-astro-imports',
				setup(build) {
					build.onResolve({ filter: /.*\.astro$/ }, () => {
						// Avoid throwing within esbuild.
						// This swallows the `hint` and blows up the stacktrace.
						markdocError = new MarkdocError({
							message: '`.astro` files are no longer supported in the Markdoc config.',
							hint: 'Use the `component()` utility to specify a component path instead. See https://docs.astro.build/en/guides/integrations-guide/markdoc/',
						});
						return {
							// Stub with an unused default export.
							path: 'data:text/javascript,export default true',
							external: true,
						};
					});
				},
			},
		],
	});
	if (markdocError) throw markdocError;
	const { text } = result.outputFiles[0];
	return {
		code: text,
		dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [],
	};
}

/**
 * Forked from Vite config loader, replacing CJS-based path concat
 * with ESM only
 * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/config.ts#L1074
 */
async function loadConfigFromBundledFile(root: URL, code: string): Promise<AstroMarkdocConfig> {
	// Write it to disk, load it with native Node ESM, then delete the file.
	const tmpFileUrl = new URL(`markdoc.config.timestamp-${Date.now()}.mjs`, root);
	fs.writeFileSync(tmpFileUrl, code);
	try {
		return (await import(tmpFileUrl.pathname)).default;
	} finally {
		try {
			fs.unlinkSync(tmpFileUrl);
		} catch {
			// already removed if this function is called twice simultaneously
		}
	}
}