-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
plugin-manifest.ts
283 lines (258 loc) · 8.71 KB
/
plugin-manifest.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import glob from 'fast-glob';
import { fileURLToPath } from 'node:url';
import type { OutputChunk } from 'rollup';
import { type Plugin as VitePlugin } from 'vite';
import { runHookBuildSsr } from '../../../integrations/index.js';
import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../../vite-plugin-scripts/index.js';
import type {
SSRManifestI18n,
SerializedRouteInfo,
SerializedSSRManifest,
} from '../../app/types.js';
import { joinPaths, prependForwardSlash } from '../../path.js';
import { serializeRouteData } from '../../routing/index.js';
import { addRollupInput } from '../add-rollup-input.js';
import { getOutFile, getOutFolder } from '../common.js';
import { cssOrder, mergeInlineCss, type BuildInternals } from '../internal.js';
import type { AstroBuildPlugin } from '../plugin.js';
import type { StaticBuildOptions } from '../types.js';
import { normalizeTheLocale } from '../../../i18n/index.js';
const manifestReplace = '@@ASTRO_MANIFEST_REPLACE@@';
const replaceExp = new RegExp(`['"](${manifestReplace})['"]`, 'g');
export const SSR_MANIFEST_VIRTUAL_MODULE_ID = '@astrojs-manifest';
export const RESOLVED_SSR_MANIFEST_VIRTUAL_MODULE_ID = '\0' + SSR_MANIFEST_VIRTUAL_MODULE_ID;
function vitePluginManifest(options: StaticBuildOptions, internals: BuildInternals): VitePlugin {
return {
name: '@astro/plugin-build-manifest',
enforce: 'post',
options(opts) {
return addRollupInput(opts, [SSR_MANIFEST_VIRTUAL_MODULE_ID]);
},
resolveId(id) {
if (id === SSR_MANIFEST_VIRTUAL_MODULE_ID) {
return RESOLVED_SSR_MANIFEST_VIRTUAL_MODULE_ID;
}
},
augmentChunkHash(chunkInfo) {
if (chunkInfo.facadeModuleId === RESOLVED_SSR_MANIFEST_VIRTUAL_MODULE_ID) {
return Date.now().toString();
}
},
async load(id) {
if (id === RESOLVED_SSR_MANIFEST_VIRTUAL_MODULE_ID) {
const imports = [
`import { deserializeManifest as _deserializeManifest } from 'astro/app'`,
`import { _privateSetManifestDontUseThis } from 'astro:ssr-manifest'`,
];
const contents = [
`const manifest = _deserializeManifest('${manifestReplace}');`,
`_privateSetManifestDontUseThis(manifest);`,
];
const exports = [`export { manifest }`];
return [...imports, ...contents, ...exports].join('\n');
}
},
async generateBundle(_opts, bundle) {
for (const [chunkName, chunk] of Object.entries(bundle)) {
if (chunk.type === 'asset') {
continue;
}
if (chunk.modules[RESOLVED_SSR_MANIFEST_VIRTUAL_MODULE_ID]) {
internals.manifestEntryChunk = chunk;
delete bundle[chunkName];
}
if (chunkName.startsWith('manifest')) {
internals.manifestFileName = chunkName;
}
}
},
};
}
export function pluginManifest(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
return {
targets: ['server'],
hooks: {
'build:before': () => {
return {
vitePlugin: vitePluginManifest(options, internals),
};
},
'build:post': async ({ mutate }) => {
if (!internals.manifestEntryChunk) {
throw new Error(`Did not generate an entry chunk for SSR`);
}
const manifest = await createManifest(options, internals);
const shouldPassMiddlewareEntryPoint =
options.settings.adapter?.adapterFeatures?.edgeMiddleware;
await runHookBuildSsr({
config: options.settings.config,
manifest,
logger: options.logger,
entryPoints: internals.entryPoints,
middlewareEntryPoint: shouldPassMiddlewareEntryPoint
? internals.middlewareEntryPoint
: undefined,
});
const code = injectManifest(manifest, internals.manifestEntryChunk);
mutate(internals.manifestEntryChunk, ['server'], code);
},
},
};
}
export async function createManifest(
buildOpts: StaticBuildOptions,
internals: BuildInternals
): Promise<SerializedSSRManifest> {
if (!internals.manifestEntryChunk) {
throw new Error(`Did not generate an entry chunk for SSR`);
}
// Add assets from the client build.
const clientStatics = new Set(
await glob('**/*', {
cwd: fileURLToPath(buildOpts.settings.config.build.client),
})
);
for (const file of clientStatics) {
internals.staticFiles.add(file);
}
const staticFiles = internals.staticFiles;
return buildManifest(buildOpts, internals, Array.from(staticFiles));
}
/**
* It injects the manifest in the given output rollup chunk. It returns the new emitted code
* @param buildOpts
* @param internals
* @param chunk
*/
export function injectManifest(manifest: SerializedSSRManifest, chunk: Readonly<OutputChunk>) {
const code = chunk.code;
return code.replace(replaceExp, () => {
return JSON.stringify(manifest);
});
}
function buildManifest(
opts: StaticBuildOptions,
internals: BuildInternals,
staticFiles: string[]
): SerializedSSRManifest {
const { settings } = opts;
const routes: SerializedRouteInfo[] = [];
const domainLookupTable: Record<string, string> = {};
const entryModules = Object.fromEntries(internals.entrySpecifierToBundleMap.entries());
if (settings.scripts.some((script) => script.stage === 'page')) {
staticFiles.push(entryModules[PAGE_SCRIPT_ID]);
}
const prefixAssetPath = (pth: string) => {
if (settings.config.build.assetsPrefix) {
return joinPaths(settings.config.build.assetsPrefix, pth);
} else {
return prependForwardSlash(joinPaths(settings.config.base, pth));
}
};
for (const route of opts.manifest.routes) {
if (!route.prerender) continue;
if (!route.pathname) continue;
const outFolder = getOutFolder(opts.settings.config, route.pathname, route.type);
const outFile = getOutFile(opts.settings.config, outFolder, route.pathname, route.type);
const file = outFile.toString().replace(opts.settings.config.build.client.toString(), '');
routes.push({
file,
links: [],
scripts: [],
styles: [],
routeData: serializeRouteData(route, settings.config.trailingSlash),
});
staticFiles.push(file);
}
for (const route of opts.manifest.routes) {
const pageData = internals.pagesByComponent.get(route.component);
if (route.prerender || !pageData) continue;
const scripts: SerializedRouteInfo['scripts'] = [];
if (pageData.hoistedScript) {
const shouldPrefixAssetPath = pageData.hoistedScript.type === 'external';
const hoistedValue = pageData.hoistedScript.value;
const value = shouldPrefixAssetPath ? prefixAssetPath(hoistedValue) : hoistedValue;
scripts.unshift(
Object.assign({}, pageData.hoistedScript, {
value,
})
);
}
if (settings.scripts.some((script) => script.stage === 'page')) {
const src = entryModules[PAGE_SCRIPT_ID];
scripts.push({
type: 'external',
value: prefixAssetPath(src),
});
}
// may be used in the future for handling rel=modulepreload, rel=icon, rel=manifest etc.
const links: [] = [];
const styles = pageData.styles
.sort(cssOrder)
.map(({ sheet }) => sheet)
.map((s) => (s.type === 'external' ? { ...s, src: prefixAssetPath(s.src) } : s))
.reduce(mergeInlineCss, []);
routes.push({
file: '',
links,
scripts: [
...scripts,
...settings.scripts
.filter((script) => script.stage === 'head-inline')
.map(({ stage, content }) => ({ stage, children: content })),
],
styles,
routeData: serializeRouteData(route, settings.config.trailingSlash),
});
}
/**
* logic meant for i18n domain support, where we fill the lookup table
*/
const i18n = settings.config.i18n;
if (
settings.config.experimental.i18nDomains &&
i18n &&
i18n.domains &&
(i18n.routing === 'domains-prefix-always' ||
i18n.routing === 'domains-prefix-other-locales' ||
i18n.routing === 'domains-prefix-other-no-redirect')
) {
for (const [locale, domainValue] of Object.entries(i18n.domains)) {
domainLookupTable[domainValue] = normalizeTheLocale(locale);
}
}
// HACK! Patch this special one.
if (!(BEFORE_HYDRATION_SCRIPT_ID in entryModules)) {
// Set this to an empty string so that the runtime knows not to try and load this.
entryModules[BEFORE_HYDRATION_SCRIPT_ID] = '';
}
let i18nManifest: SSRManifestI18n | undefined = undefined;
if (settings.config.i18n) {
i18nManifest = {
fallback: settings.config.i18n.fallback,
routing: settings.config.i18n.routing,
locales: settings.config.i18n.locales,
defaultLocale: settings.config.i18n.defaultLocale,
domainLookupTable,
};
}
return {
adapterName: opts.settings.adapter?.name ?? '',
routes,
site: settings.config.site,
base: settings.config.base,
trailingSlash: settings.config.trailingSlash,
compressHTML: settings.config.compressHTML,
assetsPrefix: settings.config.build.assetsPrefix,
componentMetadata: Array.from(internals.componentMetadata),
renderers: [],
clientDirectives: Array.from(settings.clientDirectives),
entryModules,
assets: staticFiles.map(prefixAssetPath),
i18n: i18nManifest,
buildFormat: settings.config.build.format,
};
}