-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
scripts.ts
48 lines (44 loc) · 1.52 KB
/
scripts.ts
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
import type { ModuleInfo } from 'rollup';
import slash from 'slash';
import { fileURLToPath } from 'url';
import vite from 'vite';
import type { AstroConfig, SSRElement } from '../../../@types/astro';
import type { PluginMetadata as AstroPluginMetadata } from '../../../vite-plugin-astro/types';
import { viteID } from '../../util.js';
import { createModuleScriptElementWithSrc } from '../ssr-element.js';
import { crawlGraph } from './vite.js';
export async function getScriptsForURL(
filePath: URL,
astroConfig: AstroConfig,
viteServer: vite.ViteDevServer
): Promise<Set<SSRElement>> {
const elements = new Set<SSRElement>();
const rootID = viteID(filePath);
let rootProjectFolder = slash(fileURLToPath(astroConfig.root));
const modInfo = viteServer.pluginContainer.getModuleInfo(rootID);
addHoistedScripts(elements, modInfo, rootProjectFolder);
for await (const moduleNode of crawlGraph(viteServer, rootID, true)) {
const id = moduleNode.id;
if (id) {
const info = viteServer.pluginContainer.getModuleInfo(id);
addHoistedScripts(elements, info, rootProjectFolder);
}
}
return elements;
}
function addHoistedScripts(
set: Set<SSRElement>,
info: ModuleInfo | null,
rootProjectFolder: string
) {
if (!info?.meta?.astro) {
return;
}
let id = info.id;
const astro = info?.meta?.astro as AstroPluginMetadata['astro'];
for (let i = 0; i < astro.scripts.length; i++) {
const scriptId = `${id}?astro&type=script&index=${i}&lang.ts`;
const element = createModuleScriptElementWithSrc(scriptId);
set.add(element);
}
}