html-bundle 5.5.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -30
- package/dist/bundle.mjs +342 -0
- package/dist/utils.mjs +195 -0
- package/logo.jpg +0 -0
- package/package.json +3 -2
- package/src/bundle.mts +395 -0
- package/src/index.d.ts +3 -0
- package/src/utils.mts +231 -0
- package/dist/bundle.js +0 -625
- package/src/bundle.ts +0 -732
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "html-bundle",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "6.0.0",
|
|
4
4
|
"description": "A very simple bundler for HTML SFC",
|
|
5
|
-
"bin": "./dist/bundle.
|
|
5
|
+
"bin": "./dist/bundle.mjs",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"start": "tsc",
|
|
8
8
|
"update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"bugs": "https://github.com/Krutsch/html-bundle/issues",
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@web/parse5-utils": "^1.3.0",
|
|
35
|
+
"await-spawn": "^4.0.2",
|
|
35
36
|
"chokidar": "^3.5.2",
|
|
36
37
|
"critical": "^4.0.1",
|
|
37
38
|
"cssnano": "^5.0.14",
|
package/src/bundle.mts
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import type { TextNode } from "parse5";
|
|
4
|
+
import type { AcceptedPlugin } from "postcss";
|
|
5
|
+
import { performance } from "perf_hooks";
|
|
6
|
+
import { readFile, rm, writeFile, readdir } from "fs/promises";
|
|
7
|
+
import { execFile } from "child_process";
|
|
8
|
+
import { promisify } from "util";
|
|
9
|
+
import glob from "glob";
|
|
10
|
+
import postcss from "postcss";
|
|
11
|
+
import esbuild from "esbuild";
|
|
12
|
+
import critical from "critical";
|
|
13
|
+
import { minify } from "html-minifier-terser";
|
|
14
|
+
import { watch } from "chokidar";
|
|
15
|
+
import { serialize, parse, parseFragment } from "parse5";
|
|
16
|
+
import { getTagName, findElements } from "@web/parse5-utils";
|
|
17
|
+
import awaitSpawn from "await-spawn";
|
|
18
|
+
import {
|
|
19
|
+
fileCopy,
|
|
20
|
+
createDefaultServer,
|
|
21
|
+
getPostCSSConfig,
|
|
22
|
+
getBuildPath,
|
|
23
|
+
createDir,
|
|
24
|
+
bundleConfig,
|
|
25
|
+
serverSentEvents,
|
|
26
|
+
addHMRCode,
|
|
27
|
+
} from "./utils.mjs";
|
|
28
|
+
|
|
29
|
+
const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
|
|
30
|
+
const isCritical = process.argv.includes("--critical") || bundleConfig.critical;
|
|
31
|
+
const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
|
|
32
|
+
const handlerFile = process.argv.includes("--handler")
|
|
33
|
+
? process.argv[process.argv.indexOf("--handler") + 1]
|
|
34
|
+
: bundleConfig.handler;
|
|
35
|
+
|
|
36
|
+
process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
|
|
37
|
+
let timer = performance.now();
|
|
38
|
+
let { plugins, options, file: postcssFile } = await getPostCSSConfig();
|
|
39
|
+
let CSSprocessor = postcss(plugins as AcceptedPlugin[]);
|
|
40
|
+
let fastify;
|
|
41
|
+
const inlineFiles = new Set<string>();
|
|
42
|
+
const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
|
|
43
|
+
const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
|
|
44
|
+
const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
|
|
45
|
+
const execFilePromise = promisify(execFile);
|
|
46
|
+
|
|
47
|
+
if (bundleConfig.deletePrev) {
|
|
48
|
+
await rm(bundleConfig.build, { force: true, recursive: true });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
glob(`${bundleConfig.src}/**/*.*`, build);
|
|
52
|
+
|
|
53
|
+
async function build(err: any, files: string[], firstRun = true) {
|
|
54
|
+
if (err) {
|
|
55
|
+
console.error(err);
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (isHMR && firstRun) {
|
|
60
|
+
fastify = await createDefaultServer(isSecure);
|
|
61
|
+
fastify.listen(bundleConfig.port);
|
|
62
|
+
console.log(`💻 Sever listening on port ${bundleConfig.port}.`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
for (const file of files) {
|
|
66
|
+
await createDir(file);
|
|
67
|
+
|
|
68
|
+
if (!SUPPORTED_FILES.test(file)) {
|
|
69
|
+
if (handlerFile) {
|
|
70
|
+
const { stdout } = await execFilePromise("node", [handlerFile, file]);
|
|
71
|
+
if (String(stdout)) console.log("📋 Logging Handler: ", String(stdout));
|
|
72
|
+
} else {
|
|
73
|
+
await fileCopy(file);
|
|
74
|
+
}
|
|
75
|
+
} else {
|
|
76
|
+
if (file.endsWith(".html")) {
|
|
77
|
+
await writeInlineScripts(file);
|
|
78
|
+
} else if (file.endsWith(".css")) {
|
|
79
|
+
await minifyCSS(file, getBuildPath(file));
|
|
80
|
+
} else {
|
|
81
|
+
inlineFiles.add(file);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
await minifyCode();
|
|
86
|
+
for (const file of inlineFiles) {
|
|
87
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
88
|
+
inlineFiles.delete(file);
|
|
89
|
+
await rm(file);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const file of files) {
|
|
93
|
+
if (file.endsWith(".html")) {
|
|
94
|
+
await minifyHTML(file, getBuildPath(file));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
console.log(
|
|
99
|
+
`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
if (isHMR && firstRun) {
|
|
103
|
+
console.log(`⌛ Waiting for file changes ...`);
|
|
104
|
+
|
|
105
|
+
if (postcssFile) {
|
|
106
|
+
const postCSSWatcher = watch(postcssFile);
|
|
107
|
+
const tailwindCSSWatcher = watch(
|
|
108
|
+
postcssFile.replace("postcss", "tailwind")
|
|
109
|
+
); // Assuming that the file ext is the same
|
|
110
|
+
const tsConfigWatcher = watch(
|
|
111
|
+
postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json"
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
const cssFiles = files.filter((file) => file.endsWith(".css"));
|
|
115
|
+
postCSSWatcher.on(
|
|
116
|
+
"change",
|
|
117
|
+
async () => await rebuildCSS(cssFiles, "postcss")
|
|
118
|
+
);
|
|
119
|
+
tailwindCSSWatcher.on(
|
|
120
|
+
"change",
|
|
121
|
+
async () => await rebuildCSS(cssFiles, "tailwind")
|
|
122
|
+
);
|
|
123
|
+
tsConfigWatcher.on("change", async () => {
|
|
124
|
+
timer = performance.now();
|
|
125
|
+
await build(null, files, false);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const watcher = watch(bundleConfig.src);
|
|
130
|
+
let addCount = 0; // The add watcher will add all the files initially - do not rebuild them
|
|
131
|
+
watcher.on("add", async (file) => {
|
|
132
|
+
if (addCount++ <= files.length || INLINE_BUNDLE_FILE.test(file)) {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
file = String.raw`${file}`.replace(/\\/g, "/"); // glob and chokidar diff
|
|
136
|
+
|
|
137
|
+
await rebuild(file);
|
|
138
|
+
|
|
139
|
+
console.log(`⚡ added ${file} to the build`);
|
|
140
|
+
});
|
|
141
|
+
watcher.on("change", async (file) => {
|
|
142
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
file = String.raw`${file}`.replace(/\\/g, "/");
|
|
146
|
+
|
|
147
|
+
await rebuild(file);
|
|
148
|
+
|
|
149
|
+
console.log(`⚡ modified ${file} on the build`);
|
|
150
|
+
});
|
|
151
|
+
watcher.on("unlink", async (file) => {
|
|
152
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
file = String.raw`${file}`.replace(/\\/g, "/");
|
|
156
|
+
|
|
157
|
+
inlineFiles.delete(file);
|
|
158
|
+
const buildFile = getBuildPath(file)
|
|
159
|
+
.replace(".ts", ".js")
|
|
160
|
+
.replace(".jsx", ".js");
|
|
161
|
+
await rm(buildFile);
|
|
162
|
+
|
|
163
|
+
const bfDir = buildFile.split("/").slice(0, -1).join("/");
|
|
164
|
+
const stats = await readdir(bfDir);
|
|
165
|
+
if (!stats.length) await rm(bfDir);
|
|
166
|
+
|
|
167
|
+
console.log(`⚡ deleted ${file} from the build`);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
async function rebuild(file: string) {
|
|
171
|
+
// Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
|
|
172
|
+
await rebuildCSS(files.filter((file) => file.endsWith(".css")));
|
|
173
|
+
|
|
174
|
+
let html;
|
|
175
|
+
if (file.endsWith(".html")) {
|
|
176
|
+
// To refill the inlineFiles needed to build JS
|
|
177
|
+
for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
|
|
178
|
+
await writeInlineScripts(htmlFile);
|
|
179
|
+
}
|
|
180
|
+
await minifyCode();
|
|
181
|
+
for (const file of inlineFiles) {
|
|
182
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
183
|
+
inlineFiles.delete(file);
|
|
184
|
+
await rm(file);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
html = await minifyHTML(file, getBuildPath(file));
|
|
188
|
+
} else if (/\.(jsx?|tsx?)$/.test(file)) {
|
|
189
|
+
inlineFiles.add(file);
|
|
190
|
+
await minifyCode();
|
|
191
|
+
} else {
|
|
192
|
+
const { stdout } = await execFilePromise("node", [handlerFile, file]);
|
|
193
|
+
if (String(stdout)) console.log("📋 Logging Handler: ", String(stdout));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
serverSentEvents?.({ file, html });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function minifyCSS(file: string, buildFile: string) {
|
|
202
|
+
try {
|
|
203
|
+
const fileText = await readFile(file, { encoding: "utf-8" });
|
|
204
|
+
const result = await CSSprocessor.process(fileText, {
|
|
205
|
+
...options,
|
|
206
|
+
from: file,
|
|
207
|
+
to: buildFile,
|
|
208
|
+
});
|
|
209
|
+
await writeFile(buildFile, result.css);
|
|
210
|
+
} catch (err) {
|
|
211
|
+
console.error(err);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function minifyCode(): Promise<unknown> {
|
|
216
|
+
try {
|
|
217
|
+
return await esbuild.build({
|
|
218
|
+
entryPoints: Array.from(inlineFiles),
|
|
219
|
+
charset: "utf8",
|
|
220
|
+
format: "esm",
|
|
221
|
+
incremental: isHMR,
|
|
222
|
+
sourcemap: isHMR,
|
|
223
|
+
splitting: true,
|
|
224
|
+
define: {
|
|
225
|
+
"process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
|
|
226
|
+
},
|
|
227
|
+
loader: { ".js": "jsx", ".ts": "tsx" },
|
|
228
|
+
bundle: true,
|
|
229
|
+
minify: true,
|
|
230
|
+
outdir: bundleConfig.build,
|
|
231
|
+
outbase: bundleConfig.src,
|
|
232
|
+
...bundleConfig.esbuild,
|
|
233
|
+
});
|
|
234
|
+
// Stop app from crashing.
|
|
235
|
+
} catch (err: any) {
|
|
236
|
+
if (!isHMR) {
|
|
237
|
+
console.error(err);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
let missingPkg = false;
|
|
241
|
+
if (err?.errors) {
|
|
242
|
+
for (const error of err.errors) {
|
|
243
|
+
if (error.text?.startsWith("Could not resolve")) {
|
|
244
|
+
missingPkg = true;
|
|
245
|
+
const packageNameRegex = /(?<=").*(?=")/;
|
|
246
|
+
const [pkgName] = error.text.match(packageNameRegex);
|
|
247
|
+
console.log(`📦 Package ${pkgName} was installed for you`);
|
|
248
|
+
|
|
249
|
+
await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
|
|
250
|
+
"install",
|
|
251
|
+
pkgName,
|
|
252
|
+
]);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (missingPkg) {
|
|
257
|
+
missingPkg = false;
|
|
258
|
+
return minifyCode();
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const htmlFilesCache = new Map();
|
|
265
|
+
async function writeInlineScripts(file: string) {
|
|
266
|
+
let fileText = await readFile(file, { encoding: "utf-8" });
|
|
267
|
+
|
|
268
|
+
let DOM;
|
|
269
|
+
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
270
|
+
DOM = parse(fileText);
|
|
271
|
+
} else {
|
|
272
|
+
DOM = parseFragment(fileText);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (isHMR) {
|
|
276
|
+
fileText = addHMRCode(fileText, file, DOM);
|
|
277
|
+
}
|
|
278
|
+
htmlFilesCache.set(file, [fileText, DOM]);
|
|
279
|
+
|
|
280
|
+
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
281
|
+
for (let index = 0; index < scripts.length; index++) {
|
|
282
|
+
const script = scripts[index];
|
|
283
|
+
const scriptTextNode = script.childNodes[0] as TextNode;
|
|
284
|
+
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
285
|
+
const scriptContent = scriptTextNode?.value;
|
|
286
|
+
if (!scriptContent || isReferencedScript) continue;
|
|
287
|
+
|
|
288
|
+
const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
|
|
289
|
+
inlineFiles.add(jsFile);
|
|
290
|
+
await writeFile(jsFile, scriptContent);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function minifyHTML(file: string, buildFile: string) {
|
|
295
|
+
let fileText, DOM;
|
|
296
|
+
|
|
297
|
+
if (htmlFilesCache.has(file)) {
|
|
298
|
+
const cache = htmlFilesCache.get(file);
|
|
299
|
+
fileText = cache[0];
|
|
300
|
+
DOM = cache[1];
|
|
301
|
+
} else {
|
|
302
|
+
fileText = await readFile(file, { encoding: "utf-8" });
|
|
303
|
+
|
|
304
|
+
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
305
|
+
DOM = parse(fileText);
|
|
306
|
+
} else {
|
|
307
|
+
DOM = parseFragment(fileText);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Minify Code
|
|
312
|
+
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
313
|
+
for (let index = 0; index < scripts.length; index++) {
|
|
314
|
+
const script = scripts[index];
|
|
315
|
+
const scriptTextNode = script.childNodes[0] as TextNode;
|
|
316
|
+
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
317
|
+
if (!scriptTextNode?.value || isReferencedScript) continue;
|
|
318
|
+
|
|
319
|
+
// Use bundled file
|
|
320
|
+
const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
|
|
321
|
+
|
|
322
|
+
const scriptContent = await readFile(buildInlineScript, {
|
|
323
|
+
encoding: "utf-8",
|
|
324
|
+
});
|
|
325
|
+
await rm(buildInlineScript);
|
|
326
|
+
scriptTextNode.value = scriptContent.replace(
|
|
327
|
+
TEMPLATE_LITERAL_MINIFIER,
|
|
328
|
+
" "
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Minify Inline Style
|
|
333
|
+
const styles = findElements(DOM, (e) => getTagName(e) === "style");
|
|
334
|
+
for (const style of styles) {
|
|
335
|
+
const node = style.childNodes[0] as TextNode;
|
|
336
|
+
const styleContent = node?.value;
|
|
337
|
+
if (!styleContent) continue;
|
|
338
|
+
|
|
339
|
+
const { css } = await CSSprocessor.process(styleContent, {
|
|
340
|
+
...options,
|
|
341
|
+
from: undefined,
|
|
342
|
+
});
|
|
343
|
+
node.value = css;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
fileText = serialize(DOM);
|
|
347
|
+
|
|
348
|
+
// Minify HTML
|
|
349
|
+
try {
|
|
350
|
+
fileText = await minify(fileText, {
|
|
351
|
+
collapseWhitespace: true,
|
|
352
|
+
removeComments: true,
|
|
353
|
+
...bundleConfig["html-minifier-terser"],
|
|
354
|
+
});
|
|
355
|
+
} catch (e) {
|
|
356
|
+
console.error(e);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (!isCritical) {
|
|
360
|
+
await writeFile(buildFile, fileText);
|
|
361
|
+
return fileText;
|
|
362
|
+
} else {
|
|
363
|
+
const buildFileArr = buildFile.split("/");
|
|
364
|
+
const fileWithBase = buildFileArr.pop();
|
|
365
|
+
const buildDir = buildFileArr.join("/");
|
|
366
|
+
|
|
367
|
+
// critical is generating the files on the fs
|
|
368
|
+
try {
|
|
369
|
+
const { html } = await critical.generate({
|
|
370
|
+
base: buildDir,
|
|
371
|
+
html: fileText,
|
|
372
|
+
target: fileWithBase,
|
|
373
|
+
inline: !isSecure,
|
|
374
|
+
extract: true,
|
|
375
|
+
rebase: () => {},
|
|
376
|
+
...bundleConfig.critical,
|
|
377
|
+
});
|
|
378
|
+
return html;
|
|
379
|
+
} catch (err) {
|
|
380
|
+
console.error(err);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function rebuildCSS(files: string[], config?: string) {
|
|
386
|
+
const newConfig = await getPostCSSConfig();
|
|
387
|
+
plugins = newConfig.plugins;
|
|
388
|
+
options = newConfig.options;
|
|
389
|
+
CSSprocessor = postcss(plugins as AcceptedPlugin[]);
|
|
390
|
+
for (const file of files) {
|
|
391
|
+
await minifyCSS(file, getBuildPath(file));
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (config) console.log(`⚡ modified ${config}.config`);
|
|
395
|
+
}
|
package/src/index.d.ts
ADDED
package/src/utils.mts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import type { FastifyServerOptions } from "fastify";
|
|
2
|
+
import { copyFile, mkdir, readFile } from "fs/promises";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import Fastify from "fastify";
|
|
5
|
+
import fastifyStatic from "fastify-static";
|
|
6
|
+
import postcssrc from "postcss-load-config";
|
|
7
|
+
import cssnano from "cssnano";
|
|
8
|
+
import { parse, parseFragment, serialize } from "parse5";
|
|
9
|
+
import {
|
|
10
|
+
createScript,
|
|
11
|
+
getTagName,
|
|
12
|
+
findElement,
|
|
13
|
+
appendChild,
|
|
14
|
+
} from "@web/parse5-utils";
|
|
15
|
+
|
|
16
|
+
export const bundleConfig = await getBundleConfig();
|
|
17
|
+
|
|
18
|
+
export function fileCopy(file: string) {
|
|
19
|
+
return copyFile(file, getBuildPath(file));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createDir(file: string) {
|
|
23
|
+
const buildPath = getBuildPath(file);
|
|
24
|
+
const dir = buildPath.split("/").slice(0, -1).join("/");
|
|
25
|
+
return mkdir(dir, { recursive: true });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function getBuildPath(file: string) {
|
|
29
|
+
return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const CONNECTIONS: Array<any> = []; // In order to send the HMR information
|
|
33
|
+
export let serverSentEvents:
|
|
34
|
+
| undefined
|
|
35
|
+
| (({ file, html }: { file: string; html?: string }) => void);
|
|
36
|
+
export async function createDefaultServer(isSecure: boolean) {
|
|
37
|
+
const fastify = Fastify(
|
|
38
|
+
isSecure
|
|
39
|
+
? ({
|
|
40
|
+
http2: true,
|
|
41
|
+
https: {
|
|
42
|
+
key: await readFile(path.join(process.cwd(), "localhost-key.pem")),
|
|
43
|
+
cert: await readFile(path.join(process.cwd(), "localhost.pem")),
|
|
44
|
+
},
|
|
45
|
+
} as FastifyServerOptions)
|
|
46
|
+
: void 0
|
|
47
|
+
);
|
|
48
|
+
fastify.setNotFoundHandler(async (_req, reply) => {
|
|
49
|
+
const file = await readFile(
|
|
50
|
+
path.join(process.cwd(), bundleConfig.build, "/index.html"),
|
|
51
|
+
{
|
|
52
|
+
encoding: "utf-8",
|
|
53
|
+
}
|
|
54
|
+
);
|
|
55
|
+
reply.header("Content-Type", "text/html; charset=UTF-8");
|
|
56
|
+
return reply.send(addHMRCode(file, `${bundleConfig.src}/index.html`));
|
|
57
|
+
});
|
|
58
|
+
fastify.register(fastifyStatic, {
|
|
59
|
+
root: path.join(process.cwd(), bundleConfig.build),
|
|
60
|
+
});
|
|
61
|
+
fastify.get("/hmr", (_req, reply) => {
|
|
62
|
+
reply.raw.setHeader("Content-Type", "text/event-stream");
|
|
63
|
+
reply.raw.setHeader("Cache-Control", "no-cache");
|
|
64
|
+
!isSecure && reply.raw.setHeader("Connection", "keep-alive");
|
|
65
|
+
|
|
66
|
+
CONNECTIONS.push(reply.raw);
|
|
67
|
+
|
|
68
|
+
serverSentEvents = (data) => {
|
|
69
|
+
if (/\.(jsx?|tsx?)$/.test(data.file)) {
|
|
70
|
+
data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
|
|
71
|
+
}
|
|
72
|
+
CONNECTIONS.forEach((rep) => {
|
|
73
|
+
rep.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
return fastify;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function getPostCSSConfig() {
|
|
81
|
+
try {
|
|
82
|
+
return await postcssrc({});
|
|
83
|
+
} catch {
|
|
84
|
+
return { plugins: [cssnano], options: {}, file: "" };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function getBundleConfig() {
|
|
89
|
+
const base = {
|
|
90
|
+
build: "build",
|
|
91
|
+
src: "src",
|
|
92
|
+
port: 5000,
|
|
93
|
+
esbuild: {},
|
|
94
|
+
"html-minifier-terser": {},
|
|
95
|
+
critical: {},
|
|
96
|
+
deletePrev: true,
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
|
|
101
|
+
const config = await import(`file://${cfgPath}`);
|
|
102
|
+
return { ...base, ...config.default };
|
|
103
|
+
} catch {
|
|
104
|
+
return base;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const htmlIdMap = new Map();
|
|
109
|
+
export function addHMRCode(
|
|
110
|
+
html: string,
|
|
111
|
+
file: string,
|
|
112
|
+
ast?: ReturnType<typeof parse | typeof parseFragment>
|
|
113
|
+
) {
|
|
114
|
+
if (!htmlIdMap.has(file)) {
|
|
115
|
+
htmlIdMap.set(file, randomText());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const script = createScript(
|
|
119
|
+
{ type: "module" },
|
|
120
|
+
getHMRCode(file, htmlIdMap.get(file), bundleConfig.src)
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
let DOM;
|
|
124
|
+
if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
|
|
125
|
+
DOM = ast || parse(html);
|
|
126
|
+
const headNode = findElement(DOM, (e) => getTagName(e) === "head");
|
|
127
|
+
appendChild(headNode, script);
|
|
128
|
+
} else {
|
|
129
|
+
DOM = ast || parseFragment(html);
|
|
130
|
+
appendChild(DOM, script);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
//@ts-ignore
|
|
134
|
+
DOM.childNodes.forEach((node) =>
|
|
135
|
+
node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) })
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
return serialize(DOM);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function randomText() {
|
|
142
|
+
return Math.random().toString(32).slice(2);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function getHMRCode(file: string, id: string, src: string) {
|
|
146
|
+
return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
|
|
147
|
+
window.isHMR = true;
|
|
148
|
+
if (!window.eventsource${id}) {
|
|
149
|
+
window.eventsource${id} = new EventSource("/hmr");
|
|
150
|
+
window.eventsource${id}.addEventListener('error', (e) => {
|
|
151
|
+
setTimeout(() => {
|
|
152
|
+
window.eventsource${id} = new EventSource("/hmr");
|
|
153
|
+
}, 1000);
|
|
154
|
+
});
|
|
155
|
+
window.eventsource${id}.addEventListener("message", ({ data }) => {
|
|
156
|
+
const dataObj = JSON.parse(data);
|
|
157
|
+
const file = "${file}";
|
|
158
|
+
|
|
159
|
+
if (file === dataObj.file && "html" in dataObj) {
|
|
160
|
+
let newHTML;
|
|
161
|
+
try {
|
|
162
|
+
newHTML = html\`\${dataObj.html}\`
|
|
163
|
+
} catch {
|
|
164
|
+
setShouldSetReactivity(false);
|
|
165
|
+
newHTML = html\`\${dataObj.html}\`
|
|
166
|
+
setShouldSetReactivity(true);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
|
|
170
|
+
document.head.remove(); // Don't try to diff the head – just re-run the scripts
|
|
171
|
+
render(newHTML, document.documentElement, false);
|
|
172
|
+
} else {
|
|
173
|
+
const hmrID = "${id}";
|
|
174
|
+
const hmrElems = Array.from(newHTML.childNodes);
|
|
175
|
+
const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
|
|
176
|
+
// render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
|
|
177
|
+
hmrWheres.forEach((where, index) => {
|
|
178
|
+
if (index < hmrElems.length) {
|
|
179
|
+
render(hmrElems[index], where, false);
|
|
180
|
+
} else {
|
|
181
|
+
where.remove();
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
|
|
185
|
+
if (hmrWheres.length) {
|
|
186
|
+
const template = document.createElement('template');
|
|
187
|
+
hmrElems[hmrWheres.length - 1].after(template);
|
|
188
|
+
render(hmrElems[rest], template, false);
|
|
189
|
+
template.remove();
|
|
190
|
+
} else {
|
|
191
|
+
render(hmrElems[rest], false, false)
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (dataObj.file === \`${src}/index.html\`) {
|
|
197
|
+
dispatchEvent(new Event("popstate"));
|
|
198
|
+
}
|
|
199
|
+
} else if (dataObj.file.endsWith(".css")) {
|
|
200
|
+
updateElem("link");
|
|
201
|
+
} else if (dataObj.file.endsWith(".js")) {
|
|
202
|
+
updateElem("script")
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function updateElem(type) {
|
|
206
|
+
const hmrId = "${id}";
|
|
207
|
+
const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
|
|
208
|
+
const attr = type === "script" ? "src" : "href";
|
|
209
|
+
const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
|
|
210
|
+
|
|
211
|
+
if (elem) {
|
|
212
|
+
updateOne(type, attr, elem)
|
|
213
|
+
} else {
|
|
214
|
+
for(const e of $$(\`[data-hmr="\${hmrId}"] \${type}\`)) {
|
|
215
|
+
updateOne(type, attr, e);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function updateOne(type, attr, elem) {
|
|
221
|
+
const clone = document.createElement(type);
|
|
222
|
+
for (const key of elem.getAttributeNames()) {
|
|
223
|
+
clone.setAttribute(key, elem.getAttribute(key));
|
|
224
|
+
}
|
|
225
|
+
clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
|
|
226
|
+
render(clone, elem, false);
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
`;
|
|
231
|
+
}
|