summaryrefslogtreecommitdiff
path: root/packages/astro/src/vite-plugin-scripts/page-ssr.ts
blob: 00e907b03cc6f0def2fe039def9757941ace53a7 (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
import MagicString from 'magic-string';
import { type Plugin as VitePlugin, normalizePath } from 'vite';
import type { AstroSettings } from '../@types/astro.js';
import { isPage } from '../core/util.js';
import { PAGE_SSR_SCRIPT_ID } from './index.js';

export default function astroScriptsPostPlugin({
	settings,
}: {
	settings: AstroSettings;
}): VitePlugin {
	return {
		name: 'astro:scripts:page-ssr',
		enforce: 'post',
		transform(this, code, id, options) {
			if (!options?.ssr) return;

			const hasInjectedScript = settings.scripts.some((s) => s.stage === 'page-ssr');
			if (!hasInjectedScript) return;

			const filename = normalizePath(id);
			let fileURL: URL;
			try {
				fileURL = new URL(`file://${filename}`);
			} catch {
				// If we can't construct a valid URL, exit early
				return;
			}

			const fileIsPage = isPage(fileURL, settings);
			if (!fileIsPage) return;

			const s = new MagicString(code, { filename });
			s.prepend(`import '${PAGE_SSR_SCRIPT_ID}';\n`);

			return {
				code: s.toString(),
				map: s.generateMap({ hires: 'boundary' }),
			};
		},
	};
}