-
Notifications
You must be signed in to change notification settings - Fork 10
/
prerender.js
176 lines (143 loc) · 5.74 KB
/
prerender.js
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
import fs from 'fs';
import htmlparser from 'node-html-parser';
import path from 'path';
import { Worker } from 'worker_threads';
import { pathToFileURL } from 'url';
async function interceptPage(compilation, contents, route) {
const headers = {
request: { 'accept': 'text/html', 'content-type': 'text/html' },
response: { 'content-type': 'text/html' }
};
const interceptResources = compilation.config.plugins.filter((plugin) => {
return plugin.type === 'resource' && !plugin.isGreenwoodDefaultPlugin;
}).map((plugin) => {
return plugin.provider(compilation);
}).filter((provider) => {
return provider.shouldIntercept && provider.intercept;
});
const htmlIntercepted = await interceptResources.reduce(async (htmlPromise, resource) => {
const html = (await htmlPromise).body;
const shouldIntercept = await resource.shouldIntercept(route, html, headers);
return shouldIntercept
? resource.intercept(route, html, headers)
: htmlPromise;
}, Promise.resolve({ body: contents }));
return htmlIntercepted;
}
async function optimizePage(compilation, contents, route, outputPath, outputDir) {
const optimizeResources = compilation.config.plugins.filter((plugin) => {
return plugin.type === 'resource';
}).map((plugin) => {
return plugin.provider(compilation);
}).filter((provider) => {
return provider.shouldOptimize && provider.optimize;
});
const htmlOptimized = await optimizeResources.reduce(async (htmlPromise, resource) => {
const html = await htmlPromise;
const shouldOptimize = await resource.shouldOptimize(outputPath, html);
return shouldOptimize
? resource.optimize(outputPath, html)
: Promise.resolve(html);
}, Promise.resolve(contents));
if (route !== '/404/' && !fs.existsSync(path.join(outputDir, route))) {
fs.mkdirSync(path.join(outputDir, route), {
recursive: true
});
}
return htmlOptimized;
}
async function preRenderCompilationWorker(compilation, workerPrerender) {
const pages = compilation.graph.filter(page => !page.isSSR);
const outputDir = compilation.context.scratchDir;
console.info('pages to generate', `\n ${pages.map(page => page.route).join('\n ')}`);
await Promise.all(pages.map(async (page) => {
const { outputPath, route } = page;
const outputPathDir = path.join(outputDir, route);
const htmlResource = compilation.config.plugins.filter((plugin) => {
return plugin.name === 'plugin-standard-html';
}).map((plugin) => {
return plugin.provider(compilation);
})[0];
let html;
html = (await htmlResource.serve(page.route)).body;
html = (await interceptPage(compilation, html, route)).body;
const root = htmlparser.parse(html, {
script: true,
style: true
});
const headScripts = root.querySelectorAll('script')
.filter(script => {
return script.getAttribute('type') === 'module'
&& script.getAttribute('src') && script.getAttribute('src').indexOf('http') < 0;
}).map(script => {
return pathToFileURL(path.join(compilation.context.userWorkspace, script.getAttribute('src').replace(/\.\.\//g, '').replace('./', '')));
});
await new Promise((resolve, reject) => {
const worker = new Worker(workerPrerender.workerUrl, {
workerData: {
modulePath: null,
compilation: JSON.stringify(compilation),
route,
prerender: true,
htmlContents: html,
scripts: JSON.stringify(headScripts)
}
});
worker.on('message', (result) => {
if (result.html) {
html = result.html;
}
resolve();
});
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
});
html = await optimizePage(compilation, html, route, outputPath, outputDir);
if (!fs.existsSync(outputPathDir)) {
fs.mkdirSync(outputPathDir, {
recursive: true
});
}
console.info('generated page...', route);
await fs.promises.writeFile(path.join(outputDir, outputPath), html);
}));
}
async function preRenderCompilationCustom(compilation, customPrerender) {
const { scratchDir } = compilation.context;
const renderer = (await import(customPrerender.customUrl)).default;
console.info('pages to generate', `\n ${compilation.graph.map(page => page.route).join('\n ')}`);
await renderer(compilation, async (page, contents) => {
const { outputPath, route } = page;
console.info('generated page...', route);
const html = await optimizePage(compilation, contents, route, outputPath, scratchDir);
await fs.promises.writeFile(path.join(scratchDir, outputPath), html);
});
}
async function staticRenderCompilation(compilation) {
const pages = compilation.graph.filter(page => !page.isSSR || page.isSSR && page.data.static);
const scratchDir = compilation.context.scratchDir;
const htmlResource = compilation.config.plugins.filter((plugin) => {
return plugin.name === 'plugin-standard-html';
}).map((plugin) => {
return plugin.provider(compilation);
})[0];
console.info('pages to generate', `\n ${pages.map(page => page.route).join('\n ')}`);
await Promise.all(pages.map(async (page) => {
const { route, outputPath } = page;
let html = (await htmlResource.serve(route)).body;
html = (await interceptPage(compilation, html, route)).body;
html = await optimizePage(compilation, html, route, outputPath, scratchDir);
await fs.promises.writeFile(path.join(scratchDir, outputPath), html);
console.info('generated page...', route);
return Promise.resolve();
}));
}
export {
preRenderCompilationWorker,
preRenderCompilationCustom,
staticRenderCompilation
};