forked from QwikDev/qwik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdev-server.ts
280 lines (244 loc) · 7.82 KB
/
dev-server.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
// DO NOT USE FOR PRODUCTION!!!
// Internal Testing/Dev Server
// DO NOT USE FOR PRODUCTION!!!
/* eslint-disable no-console */
import express, { Request, Response } from 'express';
import { isAbsolute, join, resolve, dirname } from 'path';
import { readdirSync, statSync, unlinkSync, rmdirSync, existsSync } from 'fs';
import { Plugin, rollup } from 'rollup';
import type { QwikManifest } from '@builder.io/qwik/optimizer';
import type { RenderToStringOptions, RenderToStringResult } from '@builder.io/qwik/server';
const app = express();
const port = parseInt(process.argv[process.argv.length - 1], 10) || 3300;
const address = `http://localhost:${port}/`;
const startersDir = __dirname;
const startersAppsDir = join(startersDir, 'apps');
const appNames = readdirSync(startersAppsDir).filter(
(p) => statSync(join(startersAppsDir, p)).isDirectory() && p !== 'base'
);
const qwikDistDir = join(__dirname, '..', 'packages', 'qwik', 'dist');
const qwikDistCorePath = join(qwikDistDir, 'core.mjs');
const qwikDistServerPath = join(qwikDistDir, 'server.mjs');
const qwikDistOptimizerPath = join(qwikDistDir, 'optimizer.cjs');
const qwikDistJsxRuntimePath = join(qwikDistDir, 'jsx-runtime.mjs');
Error.stackTraceLimit = 1000;
// dev server builds ssr's the starter app on-demand (don't do this in production)
const cache = new Map<string, QwikManifest>();
async function handleApp(req: Request, res: Response) {
try {
const url = new URL(req.url, address);
const paths = url.pathname.split('/');
const appName = paths[1];
const appDir = join(startersAppsDir, appName);
if (!existsSync(appDir)) {
res.send(`❌ Invalid dev-server path: ${appDir}`);
return;
}
console.log(req.method, req.url, `[${appName} build/ssr]`);
let clientManifest = cache.get(appDir);
if (!clientManifest) {
clientManifest = await buildApp(appDir);
cache.set(appDir, clientManifest);
}
const html = await ssrApp(req, appName, appDir, clientManifest);
res.set('Content-Type', 'text/html');
res.send(html);
} catch (e: any) {
console.error(e);
res.set('Content-Type', 'text/plain; charset=utf-8');
res.send(`❌ ${e.stack || e}`);
}
}
function devPlugin(): Plugin {
return {
name: 'devPlugin',
resolveId(id, importee) {
if (id === '@builder.io/qwik') {
delete require.cache[qwikDistCorePath];
return qwikDistCorePath;
}
if (id === '@builder.io/qwik/server') {
delete require.cache[qwikDistServerPath];
return qwikDistServerPath;
}
if (id === '@builder.io/qwik/jsx-runtime') {
delete require.cache[qwikDistJsxRuntimePath];
return qwikDistJsxRuntimePath;
}
if (!id.startsWith('.') && !isAbsolute(id)) {
return { id, external: true };
}
if (importee) {
const fileId = id.split('?')[0];
if (fileId.endsWith('.css')) {
return resolve(dirname(importee), fileId);
}
}
return null;
},
transform(code, id) {
if (id.endsWith('.css')) {
return `const CSS = ${JSON.stringify(code)}; export default CSS;`;
}
return null;
},
renderDynamicImport({ targetModuleId }) {
if (targetModuleId === 'node-fetch') {
return { left: 'import(', right: ')' };
}
},
};
}
async function buildApp(appDir: string) {
const optimizer: typeof import('@builder.io/qwik/optimizer') =
requireUncached(qwikDistOptimizerPath);
const appSrcDir = join(appDir, 'src');
const appDistDir = join(appDir, 'dist');
const appServerDir = join(appDir, 'server');
// always clean the build directory
removeDir(appDistDir);
removeDir(appServerDir);
let clientManifest: QwikManifest | undefined = undefined;
const clientBuild = await rollup({
input: getSrcInput(appSrcDir),
plugins: [
devPlugin(),
optimizer.qwikRollup({
target: 'client',
buildMode: 'development',
debug: true,
srcDir: appSrcDir,
forceFullBuild: true,
entryStrategy: { type: 'single' },
manifestOutput: (m) => {
clientManifest = m;
},
}),
],
});
await clientBuild.write({
dir: appDistDir,
});
const ssrBuild = await rollup({
input: join(appSrcDir, 'entry.ssr.tsx'),
plugins: [
devPlugin(),
optimizer.qwikRollup({
target: 'ssr',
buildMode: 'development',
srcDir: appSrcDir,
entryStrategy: { type: 'inline' },
manifestInput: clientManifest,
}),
],
});
console.log('appServerDir', appServerDir);
await ssrBuild.write({
dir: appServerDir,
});
return clientManifest!;
}
function getSrcInput(appSrcDir: string) {
// get all the entry points for tsx for DEV ONLY!
const srcInputs: string[] = [];
function readDir(dir: string) {
const items = readdirSync(dir);
for (const item of items) {
const itemPath = join(dir, item);
const s = statSync(itemPath);
if (s.isDirectory()) {
readDir(itemPath);
} else if (item.endsWith('.tsx')) {
srcInputs.push(itemPath);
}
}
}
readDir(appSrcDir);
return srcInputs;
}
function removeDir(dir: string) {
try {
const items = readdirSync(dir);
const itemPaths = items.map((i) => join(dir, i));
itemPaths.forEach((itemPath) => {
if (statSync(itemPath).isDirectory()) {
removeDir(itemPath);
} else {
unlinkSync(itemPath);
}
});
rmdirSync(dir);
} catch (e) {
/**/
}
}
async function ssrApp(req: Request, appName: string, appDir: string, manifest: QwikManifest) {
const ssrPath = join(appDir, 'server', 'entry.ssr.js');
// require the build's server index (avoiding nodejs require cache)
const { render } = requireUncached(ssrPath);
// ssr the document
const base = `/${appName}/build/`;
console.log('req.url', req.url);
const opts: RenderToStringOptions = {
manifest,
url: new URL(`${req.protocol}://${req.hostname}${req.url}`),
debug: true,
base: base,
};
const result: RenderToStringResult = await render(opts);
return result.html;
}
function requireUncached(module: string) {
delete require.cache[require.resolve(module)];
return require(module);
}
function startersHomepage(_: Request, res: Response) {
res.set('Content-Type', 'text/html; charset=utf-8');
res.send(`<!DOCTYPE html>
<html>
<head>
<title>Starters Dev Server</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
line-height: 1.5;
}
a { color: #4340C4; }
a:hover { text-decoration: none; }
h1 { margin: 5px 0; }
</style>
</head>
<body>
<h1>⚡️ Starters Dev Server ⚡️</h1>
<ul>
${appNames.map((a) => `<li><a href="/${a}/">${a}</a></li>`).join('')}
</ul>
</body>
</html>
`);
}
function favicon(_: Request, res: Response) {
const path = join(startersAppsDir, 'base', 'public', 'favicon.ico');
res.sendFile(path);
}
const partytownPath = resolve(startersDir, '..', 'node_modules', '@builder.io', 'partytown', 'lib');
app.use(`/~partytown`, express.static(partytownPath));
appNames.forEach((appName) => {
const buildPath = join(startersAppsDir, appName, 'dist', 'build');
app.use(`/${appName}/build`, express.static(buildPath));
const publicPath = join(startersAppsDir, appName, 'public');
app.use(`/${appName}`, express.static(publicPath));
});
app.get('/', startersHomepage);
app.get('/favicon.ico', favicon);
app.get('/*', handleApp);
const server = app.listen(port, () => {
console.log(`Starter Dir: ${startersDir}`);
console.log(`Dev Server: ${address}\n`);
console.log(`Starters:`);
appNames.forEach((appName) => {
console.log(` ${address}${appName}/`);
});
console.log(``);
});
process.on('SIGTERM', () => server.close());