html-bundle 6.2.3 → 6.3.1

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/src/bundle.mts CHANGED
@@ -1,478 +1,478 @@
1
- #!/usr/bin/env node
2
-
3
- import type { Node, TextNode } from "@web/parse5-utils";
4
- import type { AcceptedPlugin } from "postcss";
5
- import type { Router } from "express-serve-static-core";
6
- import { performance } from "perf_hooks";
7
- import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
8
- import { execFile } from "child_process";
9
- import { promisify } from "util";
10
- import { sep } from "path";
11
- import { glob } from "glob";
12
- import postcss from "postcss";
13
- import express from "express";
14
- import esbuild, { type BuildOptions } from "esbuild";
15
- import Beasties, { type Options } from "beasties";
16
- import { minify, type Options as MinifyOptions } from "html-minifier-terser";
17
- import { watch } from "chokidar";
18
- import { serialize, parse, parseFragment } from "parse5";
19
- import { getTagName, findElements } from "@web/parse5-utils";
20
- import awaitSpawn from "await-spawn";
21
- import {
22
- fileCopy,
23
- createDefaultServer,
24
- getPostCSSConfig,
25
- getBuildPath,
26
- createDir,
27
- bundleConfig,
28
- serverSentEvents,
29
- addHMRCode,
30
- } from "./utils.mjs";
31
-
32
- const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
33
- const isCritical =
34
- process.argv.includes("--isCritical") || bundleConfig.isCritical;
35
- const beasties = new Beasties({
36
- path: bundleConfig.build,
37
- logLevel: "silent",
38
- ...bundleConfig.critical,
39
- });
40
- const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
41
- const handlerFile = process.argv.includes("--handler")
42
- ? process.argv[process.argv.indexOf("--handler") + 1]
43
- : bundleConfig.handler;
44
-
45
- process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
46
- let timer = performance.now();
47
- let { plugins, options, file: postcssFile } = await getPostCSSConfig();
48
- let CSSprocessor = postcss(plugins as AcceptedPlugin[]);
49
- let router: Router | undefined;
50
- const inlineFiles = new Set<string>();
51
- const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
52
- const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
53
- const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
54
- const execFilePromise = promisify(execFile);
55
-
56
- if (bundleConfig.deletePrev) {
57
- await rm(bundleConfig.build, { force: true, recursive: true });
58
- }
59
-
60
- async function cleanupStaleInlineBundleFiles() {
61
- const staleFiles = await glob(`${bundleConfig.src}/**/*-bundle-*.tsx`);
62
-
63
- await Promise.all(
64
- staleFiles.map((file) => rm(file.replaceAll(sep, "/"), { force: true })),
65
- );
66
- }
67
-
68
- async function build(files: string[], firstRun = true) {
69
- for (const file of files) {
70
- if (INLINE_BUNDLE_FILE.test(file)) {
71
- continue;
72
- }
73
-
74
- await createDir(file);
75
-
76
- if (!SUPPORTED_FILES.test(file)) {
77
- if (handlerFile) {
78
- execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
79
- console.log("📋 Logging Handler: ", String(stdout));
80
- });
81
- } else {
82
- if ((await lstat(file)).isDirectory()) continue;
83
- await fileCopy(file);
84
- }
85
- } else {
86
- if (file.endsWith(".html")) {
87
- await writeInlineScripts(file);
88
- } else if (file.endsWith(".css")) {
89
- await minifyCSS(file, getBuildPath(file));
90
- } else {
91
- inlineFiles.add(file);
92
- }
93
- }
94
- }
95
- await minifyCode();
96
- for (const file of inlineFiles) {
97
- if (INLINE_BUNDLE_FILE.test(file)) {
98
- inlineFiles.delete(file);
99
- await rm(file);
100
- }
101
- }
102
- for (const file of files) {
103
- if (file.endsWith(".html")) {
104
- await minifyHTML(file, getBuildPath(file));
105
- }
106
- }
107
-
108
- console.log(
109
- `🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`,
110
- );
111
-
112
- if (isHMR && firstRun) {
113
- const [dynamicRouter, server] = await createDefaultServer(isSecure);
114
- router = dynamicRouter;
115
- server.listen({ port: bundleConfig.port, host: bundleConfig.host });
116
- console.log(
117
- `💻 Server listening on http${isSecure ? "s" : ""}://${
118
- bundleConfig.host === "::" ? "localhost" : bundleConfig.host
119
- }:${bundleConfig.port} and is shared in the local network.`,
120
- );
121
-
122
- console.log(`⌛ Waiting for file changes ...`);
123
-
124
- const chokidarOptions = { awaitWriteFinish: false };
125
- if (postcssFile) {
126
- const postCSSWatcher = watch(postcssFile, chokidarOptions);
127
- const tailwindCSSWatcher = watch(
128
- postcssFile.replace("postcss", "tailwind"),
129
- chokidarOptions,
130
- ); // Assuming that the file ext is the same
131
- const tsConfigWatcher = watch(
132
- postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json",
133
- chokidarOptions,
134
- );
135
-
136
- const cssFiles = files.filter((file) => file.endsWith(".css"));
137
- postCSSWatcher.on(
138
- "change",
139
- async () => await rebuildCSS(cssFiles, "postcss"),
140
- );
141
- tailwindCSSWatcher.on(
142
- "change",
143
- async () => await rebuildCSS(cssFiles, "tailwind"),
144
- );
145
- tsConfigWatcher.on("change", async () => {
146
- timer = performance.now();
147
- await build(files, false);
148
- });
149
- }
150
-
151
- const watcher = watch(bundleConfig.src, chokidarOptions);
152
- watcher.on("add", async (file) => {
153
- file = String.raw`${file}`.replace(/\\/g, "/"); // glob and chokidar diff
154
- if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
155
- return;
156
- }
157
-
158
- try {
159
- await rebuild(file);
160
- } catch {}
161
-
162
- console.log(`⚡ added ${file} to the build`);
163
- });
164
- watcher.on("change", async (file) => {
165
- if (INLINE_BUNDLE_FILE.test(file)) {
166
- return;
167
- }
168
- file = String.raw`${file}`.replace(/\\/g, "/");
169
-
170
- await rebuild(file);
171
-
172
- console.log(`⚡ modified ${file} on the build`);
173
- });
174
- watcher.on("unlink", async (file) => {
175
- if (INLINE_BUNDLE_FILE.test(file)) {
176
- return;
177
- }
178
- file = String.raw`${file}`.replace(/\\/g, "/");
179
-
180
- inlineFiles.delete(file);
181
- const buildFile = getBuildPath(file)
182
- .replace(".ts", ".js")
183
- .replace(".jsx", ".js");
184
-
185
- try {
186
- await rm(buildFile);
187
- const bfDir = buildFile.split("/").slice(0, -1).join("/");
188
- const stats = await readdir(bfDir);
189
- if (!stats.length) await rm(bfDir);
190
- } catch {}
191
-
192
- console.log(`⚡ deleted ${file} from the build`);
193
- });
194
-
195
- async function rebuild(file: string) {
196
- // Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
197
- await rebuildCSS(files.filter((file) => file.endsWith(".css")));
198
-
199
- let html;
200
- if (file.endsWith(".html")) {
201
- // To refill the inlineFiles needed to build JS
202
- for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
203
- await writeInlineScripts(htmlFile);
204
- }
205
- await minifyCode();
206
- for (const file of inlineFiles) {
207
- if (INLINE_BUNDLE_FILE.test(file)) {
208
- inlineFiles.delete(file);
209
- await rm(file);
210
- }
211
- }
212
- html = await minifyHTML(file, getBuildPath(file));
213
- } else if (/\.(jsx?|tsx?)$/.test(file)) {
214
- inlineFiles.add(file);
215
- await minifyCode();
216
- } else if (!file.endsWith(".css")) {
217
- if (handlerFile) {
218
- execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
219
- console.log("📋 Logging Handler: ", String(stdout));
220
- });
221
- } else {
222
- await fileCopy(file);
223
- }
224
- } else if (handlerFile) {
225
- execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
226
- console.log("📋 Logging Handler: ", String(stdout));
227
- });
228
- }
229
-
230
- serverSentEvents?.({ file, html });
231
- }
232
- }
233
- }
234
-
235
- async function minifyCSS(file: string, buildFile: string) {
236
- try {
237
- const fileText = await readFile(file, { encoding: "utf-8" });
238
- const result = await CSSprocessor.process(fileText, {
239
- ...options,
240
- from: file,
241
- to: buildFile,
242
- });
243
- await writeFile(buildFile, result.css);
244
- } catch (err) {
245
- // @ts-ignore
246
- console.error(err?.reason);
247
- }
248
- }
249
-
250
- async function minifyCode(): Promise<unknown> {
251
- try {
252
- return await esbuild.build({
253
- entryPoints: Array.from(inlineFiles),
254
- charset: "utf8",
255
- format: "esm",
256
- sourcemap: isHMR,
257
- splitting: true,
258
- define: {
259
- "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
260
- },
261
- loader: { ".js": "jsx", ".ts": "tsx" },
262
- bundle: true,
263
- minify: true,
264
- outdir: bundleConfig.build,
265
- outbase: bundleConfig.src,
266
- ...bundleConfig.esbuild,
267
- });
268
- // Stop app from crashing.
269
- } catch (err: any) {
270
- if (!isHMR) {
271
- console.error(err);
272
- }
273
-
274
- let missingPkg = false;
275
- if (err?.errors) {
276
- for (const error of err.errors) {
277
- if (error.location && error.text?.startsWith("Could not resolve")) {
278
- missingPkg = true;
279
- const packageNameRegex = /(?<=").*(?=")/;
280
- const [pkgName] = error.text.match(packageNameRegex);
281
-
282
- await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
283
- "install",
284
- pkgName,
285
- ]);
286
-
287
- console.log(`📦 Package ${pkgName} was installed for you`);
288
- }
289
- }
290
-
291
- if (missingPkg) {
292
- missingPkg = false;
293
- return minifyCode();
294
- }
295
- }
296
- }
297
- }
298
-
299
- const htmlFilesCache = new Map();
300
- async function writeInlineScripts(file: string) {
301
- let fileText = await readFile(file, { encoding: "utf-8" });
302
-
303
- let DOM;
304
- if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
305
- DOM = parse(fileText);
306
- } else {
307
- DOM = parseFragment(fileText);
308
- }
309
-
310
- if (isHMR) {
311
- fileText = addHMRCode(fileText, file, DOM);
312
- }
313
- htmlFilesCache.set(file, [fileText, DOM]);
314
-
315
- const scripts = findElements(DOM as Node, (e) => getTagName(e) === "script");
316
- for (let index = 0; index < scripts.length; index++) {
317
- const script = scripts[index];
318
- const scriptTextNode = script.childNodes[0] as TextNode;
319
- const isReferencedScript = script.attrs.find(
320
- (a: { name: string }) => a.name === "src",
321
- );
322
- const type = script.attrs.find((a: { name: string }) => a.name === "type");
323
- const scriptContent = scriptTextNode?.value;
324
- if (
325
- !scriptContent ||
326
- isReferencedScript ||
327
- type?.value === "importmap" ||
328
- type?.value === "application/ld+json"
329
- )
330
- continue;
331
-
332
- const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
333
- inlineFiles.add(jsFile);
334
- await writeFile(jsFile, scriptContent);
335
- }
336
- }
337
-
338
- async function minifyHTML(file: string, buildFile: string) {
339
- let fileText, DOM;
340
-
341
- if (htmlFilesCache.has(file)) {
342
- const cache = htmlFilesCache.get(file);
343
- fileText = cache[0];
344
- DOM = cache[1];
345
- } else {
346
- fileText = await readFile(file, { encoding: "utf-8" });
347
-
348
- if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
349
- DOM = parse(fileText);
350
- } else {
351
- DOM = parseFragment(fileText);
352
- }
353
- }
354
-
355
- // Minify Code
356
- const scripts = findElements(DOM, (e) => getTagName(e) === "script");
357
- for (let index = 0; index < scripts.length; index++) {
358
- const script = scripts[index];
359
- const scriptTextNode = script.childNodes[0] as TextNode;
360
- const isReferencedScript = script.attrs.find(
361
- (a: { name: string }) => a.name === "src",
362
- );
363
- const type = script.attrs.find((a: { name: string }) => a.name === "type");
364
- if (
365
- !scriptTextNode?.value ||
366
- isReferencedScript ||
367
- type?.value === "importmap" ||
368
- type?.value === "application/ld+json"
369
- )
370
- continue;
371
-
372
- // Use bundled file
373
- const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
374
-
375
- try {
376
- const scriptContent = await readFile(buildInlineScript, {
377
- encoding: "utf-8",
378
- });
379
- await rm(buildInlineScript);
380
- scriptTextNode.value = scriptContent.replace(
381
- TEMPLATE_LITERAL_MINIFIER,
382
- " ",
383
- );
384
- } catch {}
385
- }
386
-
387
- // Minify Inline Style
388
- const styles = findElements(DOM, (e) => getTagName(e) === "style");
389
- for (const style of styles) {
390
- const node = style.childNodes[0] as TextNode;
391
- const styleContent = node?.value;
392
- if (!styleContent) continue;
393
-
394
- try {
395
- const { css } = await CSSprocessor.process(styleContent, {
396
- ...options,
397
- from: undefined,
398
- });
399
- node.value = css;
400
- } catch {
401
- // @ts-ignore
402
- console.error(err?.reason);
403
- }
404
- }
405
-
406
- fileText = serialize(DOM);
407
-
408
- // Minify HTML
409
- try {
410
- fileText = await minify(fileText, {
411
- collapseWhitespace: true,
412
- removeComments: true,
413
- ...bundleConfig["html-minifier-terser"],
414
- });
415
- } catch (e) {
416
- console.error(e);
417
- }
418
-
419
- if (isCritical) {
420
- try {
421
- const isPartical = !fileText.startsWith("<!DOCTYPE html>");
422
- fileText = await beasties.process(fileText);
423
- // fix beasties jsdom
424
- if (isPartical) {
425
- fileText = fileText.replace(/<\/?(html|head|body)>/g, "");
426
- }
427
- } catch (err) {
428
- console.error(err);
429
- }
430
- }
431
-
432
- await writeFile(buildFile, fileText);
433
- return fileText;
434
- }
435
-
436
- async function rebuildCSS(files: string[], config?: string) {
437
- const newConfig = await getPostCSSConfig();
438
- plugins = newConfig.plugins;
439
- options = newConfig.options;
440
- CSSprocessor = postcss(plugins as AcceptedPlugin[]);
441
- for (const file of files) {
442
- await minifyCSS(file, getBuildPath(file));
443
- }
444
-
445
- if (config) console.log(`⚡ modified ${config}.config`);
446
- }
447
-
448
- try {
449
- await cleanupStaleInlineBundleFiles();
450
- const files = await glob(`${bundleConfig.src}/**/*`);
451
- await build(
452
- files
453
- .map((file) => file.replaceAll(sep, "/"))
454
- .filter((file) => !INLINE_BUNDLE_FILE.test(file)),
455
- );
456
- } catch (err) {
457
- console.error(err);
458
- process.exit(1);
459
- }
460
-
461
- export default router;
462
-
463
- export type Config = {
464
- build: string;
465
- src: string;
466
- port: number;
467
- secure: boolean;
468
- esbuild?: BuildOptions;
469
- "html-minifier-terser"?: MinifyOptions;
470
- critical?: Options;
471
- deletePrev?: boolean;
472
- isCritical?: boolean;
473
- hmr?: boolean;
474
- handler?: string;
475
- host?: string;
476
- key?: Buffer;
477
- cert?: Buffer;
478
- };
1
+ #!/usr/bin/env node
2
+
3
+ import type { Node, TextNode } from "@web/parse5-utils";
4
+ import type { AcceptedPlugin } from "postcss";
5
+ import type { Router } from "express-serve-static-core";
6
+ import { performance } from "perf_hooks";
7
+ import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
8
+ import { execFile } from "child_process";
9
+ import { promisify } from "util";
10
+ import { sep } from "path";
11
+ import { glob } from "glob";
12
+ import postcss from "postcss";
13
+ import express from "express";
14
+ import esbuild, { type BuildOptions } from "esbuild";
15
+ import Beasties, { type Options } from "beasties";
16
+ import { minify, type Options as MinifyOptions } from "html-minifier-terser";
17
+ import { watch } from "chokidar";
18
+ import { serialize, parse, parseFragment } from "parse5";
19
+ import { getTagName, findElements } from "@web/parse5-utils";
20
+ import awaitSpawn from "await-spawn";
21
+ import {
22
+ fileCopy,
23
+ createDefaultServer,
24
+ getPostCSSConfig,
25
+ getBuildPath,
26
+ createDir,
27
+ bundleConfig,
28
+ serverSentEvents,
29
+ addHMRCode,
30
+ } from "./utils.mjs";
31
+
32
+ const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
33
+ const isCritical =
34
+ process.argv.includes("--isCritical") || bundleConfig.isCritical;
35
+ const beasties = new Beasties({
36
+ path: bundleConfig.build,
37
+ logLevel: "silent",
38
+ ...bundleConfig.critical,
39
+ });
40
+ const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
41
+ const handlerFile = process.argv.includes("--handler")
42
+ ? process.argv[process.argv.indexOf("--handler") + 1]
43
+ : bundleConfig.handler;
44
+
45
+ process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
46
+ let timer = performance.now();
47
+ let { plugins, options, file: postcssFile } = await getPostCSSConfig();
48
+ let CSSprocessor = postcss(plugins as AcceptedPlugin[]);
49
+ let router: Router | undefined;
50
+ const inlineFiles = new Set<string>();
51
+ const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
52
+ const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
53
+ const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
54
+ const execFilePromise = promisify(execFile);
55
+
56
+ if (bundleConfig.deletePrev) {
57
+ await rm(bundleConfig.build, { force: true, recursive: true });
58
+ }
59
+
60
+ async function cleanupStaleInlineBundleFiles() {
61
+ const staleFiles = await glob(`${bundleConfig.src}/**/*-bundle-*.tsx`);
62
+
63
+ await Promise.all(
64
+ staleFiles.map((file) => rm(file.replaceAll(sep, "/"), { force: true })),
65
+ );
66
+ }
67
+
68
+ async function build(files: string[], firstRun = true) {
69
+ for (const file of files) {
70
+ if (INLINE_BUNDLE_FILE.test(file)) {
71
+ continue;
72
+ }
73
+
74
+ await createDir(file);
75
+
76
+ if (!SUPPORTED_FILES.test(file)) {
77
+ if (handlerFile) {
78
+ execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
79
+ console.log("📋 Logging Handler: ", String(stdout));
80
+ });
81
+ } else {
82
+ if ((await lstat(file)).isDirectory()) continue;
83
+ await fileCopy(file);
84
+ }
85
+ } else {
86
+ if (file.endsWith(".html")) {
87
+ await writeInlineScripts(file);
88
+ } else if (file.endsWith(".css")) {
89
+ await minifyCSS(file, getBuildPath(file));
90
+ } else {
91
+ inlineFiles.add(file);
92
+ }
93
+ }
94
+ }
95
+ await minifyCode();
96
+ for (const file of inlineFiles) {
97
+ if (INLINE_BUNDLE_FILE.test(file)) {
98
+ inlineFiles.delete(file);
99
+ await rm(file);
100
+ }
101
+ }
102
+ for (const file of files) {
103
+ if (file.endsWith(".html")) {
104
+ await minifyHTML(file, getBuildPath(file));
105
+ }
106
+ }
107
+
108
+ console.log(
109
+ `🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`,
110
+ );
111
+
112
+ if (isHMR && firstRun) {
113
+ const [dynamicRouter, server] = await createDefaultServer(isSecure);
114
+ router = dynamicRouter;
115
+ server.listen({ port: bundleConfig.port, host: bundleConfig.host });
116
+ console.log(
117
+ `💻 Server listening on http${isSecure ? "s" : ""}://${
118
+ bundleConfig.host === "::" ? "localhost" : bundleConfig.host
119
+ }:${bundleConfig.port} and is shared in the local network.`,
120
+ );
121
+
122
+ console.log(`⌛ Waiting for file changes ...`);
123
+
124
+ const chokidarOptions = { awaitWriteFinish: false };
125
+ if (postcssFile) {
126
+ const postCSSWatcher = watch(postcssFile, chokidarOptions);
127
+ const tailwindCSSWatcher = watch(
128
+ postcssFile.replace("postcss", "tailwind"),
129
+ chokidarOptions,
130
+ ); // Assuming that the file ext is the same
131
+ const tsConfigWatcher = watch(
132
+ postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json",
133
+ chokidarOptions,
134
+ );
135
+
136
+ const cssFiles = files.filter((file) => file.endsWith(".css"));
137
+ postCSSWatcher.on(
138
+ "change",
139
+ async () => await rebuildCSS(cssFiles, "postcss"),
140
+ );
141
+ tailwindCSSWatcher.on(
142
+ "change",
143
+ async () => await rebuildCSS(cssFiles, "tailwind"),
144
+ );
145
+ tsConfigWatcher.on("change", async () => {
146
+ timer = performance.now();
147
+ await build(files, false);
148
+ });
149
+ }
150
+
151
+ const watcher = watch(bundleConfig.src, chokidarOptions);
152
+ watcher.on("add", async (file) => {
153
+ file = String.raw`${file}`.replace(/\\/g, "/"); // glob and chokidar diff
154
+ if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
155
+ return;
156
+ }
157
+
158
+ try {
159
+ await rebuild(file);
160
+ } catch {}
161
+
162
+ console.log(`⚡ added ${file} to the build`);
163
+ });
164
+ watcher.on("change", async (file) => {
165
+ if (INLINE_BUNDLE_FILE.test(file)) {
166
+ return;
167
+ }
168
+ file = String.raw`${file}`.replace(/\\/g, "/");
169
+
170
+ await rebuild(file);
171
+
172
+ console.log(`⚡ modified ${file} on the build`);
173
+ });
174
+ watcher.on("unlink", async (file) => {
175
+ if (INLINE_BUNDLE_FILE.test(file)) {
176
+ return;
177
+ }
178
+ file = String.raw`${file}`.replace(/\\/g, "/");
179
+
180
+ inlineFiles.delete(file);
181
+ const buildFile = getBuildPath(file)
182
+ .replace(".ts", ".js")
183
+ .replace(".jsx", ".js");
184
+
185
+ try {
186
+ await rm(buildFile);
187
+ const bfDir = buildFile.split("/").slice(0, -1).join("/");
188
+ const stats = await readdir(bfDir);
189
+ if (!stats.length) await rm(bfDir);
190
+ } catch {}
191
+
192
+ console.log(`⚡ deleted ${file} from the build`);
193
+ });
194
+
195
+ async function rebuild(file: string) {
196
+ // Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
197
+ await rebuildCSS(files.filter((file) => file.endsWith(".css")));
198
+
199
+ let html;
200
+ if (file.endsWith(".html")) {
201
+ // To refill the inlineFiles needed to build JS
202
+ for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
203
+ await writeInlineScripts(htmlFile);
204
+ }
205
+ await minifyCode();
206
+ for (const file of inlineFiles) {
207
+ if (INLINE_BUNDLE_FILE.test(file)) {
208
+ inlineFiles.delete(file);
209
+ await rm(file);
210
+ }
211
+ }
212
+ html = await minifyHTML(file, getBuildPath(file));
213
+ } else if (/\.(jsx?|tsx?)$/.test(file)) {
214
+ inlineFiles.add(file);
215
+ await minifyCode();
216
+ } else if (!file.endsWith(".css")) {
217
+ if (handlerFile) {
218
+ execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
219
+ console.log("📋 Logging Handler: ", String(stdout));
220
+ });
221
+ } else {
222
+ await fileCopy(file);
223
+ }
224
+ } else if (handlerFile) {
225
+ execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
226
+ console.log("📋 Logging Handler: ", String(stdout));
227
+ });
228
+ }
229
+
230
+ serverSentEvents?.({ file, html });
231
+ }
232
+ }
233
+ }
234
+
235
+ async function minifyCSS(file: string, buildFile: string) {
236
+ try {
237
+ const fileText = await readFile(file, { encoding: "utf-8" });
238
+ const result = await CSSprocessor.process(fileText, {
239
+ ...options,
240
+ from: file,
241
+ to: buildFile,
242
+ });
243
+ await writeFile(buildFile, result.css);
244
+ } catch (err) {
245
+ // @ts-ignore
246
+ console.error(err?.reason);
247
+ }
248
+ }
249
+
250
+ async function minifyCode(): Promise<unknown> {
251
+ try {
252
+ return await esbuild.build({
253
+ entryPoints: Array.from(inlineFiles),
254
+ charset: "utf8",
255
+ format: "esm",
256
+ sourcemap: isHMR,
257
+ splitting: true,
258
+ define: {
259
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
260
+ },
261
+ loader: { ".js": "jsx", ".ts": "tsx" },
262
+ bundle: true,
263
+ minify: true,
264
+ outdir: bundleConfig.build,
265
+ outbase: bundleConfig.src,
266
+ ...bundleConfig.esbuild,
267
+ });
268
+ // Stop app from crashing.
269
+ } catch (err: any) {
270
+ if (!isHMR) {
271
+ console.error(err);
272
+ }
273
+
274
+ let missingPkg = false;
275
+ if (err?.errors) {
276
+ for (const error of err.errors) {
277
+ if (error.location && error.text?.startsWith("Could not resolve")) {
278
+ missingPkg = true;
279
+ const packageNameRegex = /(?<=").*(?=")/;
280
+ const [pkgName] = error.text.match(packageNameRegex);
281
+
282
+ await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
283
+ "install",
284
+ pkgName,
285
+ ]);
286
+
287
+ console.log(`📦 Package ${pkgName} was installed for you`);
288
+ }
289
+ }
290
+
291
+ if (missingPkg) {
292
+ missingPkg = false;
293
+ return minifyCode();
294
+ }
295
+ }
296
+ }
297
+ }
298
+
299
+ const htmlFilesCache = new Map();
300
+ async function writeInlineScripts(file: string) {
301
+ let fileText = await readFile(file, { encoding: "utf-8" });
302
+
303
+ let DOM;
304
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
305
+ DOM = parse(fileText);
306
+ } else {
307
+ DOM = parseFragment(fileText);
308
+ }
309
+
310
+ if (isHMR) {
311
+ fileText = addHMRCode(fileText, file, DOM);
312
+ }
313
+ htmlFilesCache.set(file, [fileText, DOM]);
314
+
315
+ const scripts = findElements(DOM as Node, (e) => getTagName(e) === "script");
316
+ for (let index = 0; index < scripts.length; index++) {
317
+ const script = scripts[index];
318
+ const scriptTextNode = script.childNodes[0] as TextNode;
319
+ const isReferencedScript = script.attrs.find(
320
+ (a: { name: string }) => a.name === "src",
321
+ );
322
+ const type = script.attrs.find((a: { name: string }) => a.name === "type");
323
+ const scriptContent = scriptTextNode?.value;
324
+ if (
325
+ !scriptContent ||
326
+ isReferencedScript ||
327
+ type?.value === "importmap" ||
328
+ type?.value === "application/ld+json"
329
+ )
330
+ continue;
331
+
332
+ const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
333
+ inlineFiles.add(jsFile);
334
+ await writeFile(jsFile, scriptContent);
335
+ }
336
+ }
337
+
338
+ async function minifyHTML(file: string, buildFile: string) {
339
+ let fileText, DOM;
340
+
341
+ if (htmlFilesCache.has(file)) {
342
+ const cache = htmlFilesCache.get(file);
343
+ fileText = cache[0];
344
+ DOM = cache[1];
345
+ } else {
346
+ fileText = await readFile(file, { encoding: "utf-8" });
347
+
348
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
349
+ DOM = parse(fileText);
350
+ } else {
351
+ DOM = parseFragment(fileText);
352
+ }
353
+ }
354
+
355
+ // Minify Code
356
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
357
+ for (let index = 0; index < scripts.length; index++) {
358
+ const script = scripts[index];
359
+ const scriptTextNode = script.childNodes[0] as TextNode;
360
+ const isReferencedScript = script.attrs.find(
361
+ (a: { name: string }) => a.name === "src",
362
+ );
363
+ const type = script.attrs.find((a: { name: string }) => a.name === "type");
364
+ if (
365
+ !scriptTextNode?.value ||
366
+ isReferencedScript ||
367
+ type?.value === "importmap" ||
368
+ type?.value === "application/ld+json"
369
+ )
370
+ continue;
371
+
372
+ // Use bundled file
373
+ const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
374
+
375
+ try {
376
+ const scriptContent = await readFile(buildInlineScript, {
377
+ encoding: "utf-8",
378
+ });
379
+ await rm(buildInlineScript);
380
+ scriptTextNode.value = scriptContent.replace(
381
+ TEMPLATE_LITERAL_MINIFIER,
382
+ " ",
383
+ );
384
+ } catch {}
385
+ }
386
+
387
+ // Minify Inline Style
388
+ const styles = findElements(DOM, (e) => getTagName(e) === "style");
389
+ for (const style of styles) {
390
+ const node = style.childNodes[0] as TextNode;
391
+ const styleContent = node?.value;
392
+ if (!styleContent) continue;
393
+
394
+ try {
395
+ const { css } = await CSSprocessor.process(styleContent, {
396
+ ...options,
397
+ from: undefined,
398
+ });
399
+ node.value = css;
400
+ } catch {
401
+ // @ts-ignore
402
+ console.error(err?.reason);
403
+ }
404
+ }
405
+
406
+ fileText = serialize(DOM);
407
+
408
+ // Minify HTML
409
+ try {
410
+ fileText = await minify(fileText, {
411
+ collapseWhitespace: true,
412
+ removeComments: true,
413
+ ...bundleConfig["html-minifier-terser"],
414
+ });
415
+ } catch (e) {
416
+ console.error(e);
417
+ }
418
+
419
+ if (isCritical) {
420
+ try {
421
+ const isPartical = !fileText.startsWith("<!DOCTYPE html>");
422
+ fileText = await beasties.process(fileText);
423
+ // fix beasties jsdom
424
+ if (isPartical) {
425
+ fileText = fileText.replace(/<\/?(html|head|body)>/g, "");
426
+ }
427
+ } catch (err) {
428
+ console.error(err);
429
+ }
430
+ }
431
+
432
+ await writeFile(buildFile, fileText);
433
+ return fileText;
434
+ }
435
+
436
+ async function rebuildCSS(files: string[], config?: string) {
437
+ const newConfig = await getPostCSSConfig();
438
+ plugins = newConfig.plugins;
439
+ options = newConfig.options;
440
+ CSSprocessor = postcss(plugins as AcceptedPlugin[]);
441
+ for (const file of files) {
442
+ await minifyCSS(file, getBuildPath(file));
443
+ }
444
+
445
+ if (config) console.log(`⚡ modified ${config}.config`);
446
+ }
447
+
448
+ try {
449
+ await cleanupStaleInlineBundleFiles();
450
+ const files = await glob(`${bundleConfig.src}/**/*`);
451
+ await build(
452
+ files
453
+ .map((file) => file.replaceAll(sep, "/"))
454
+ .filter((file) => !INLINE_BUNDLE_FILE.test(file)),
455
+ );
456
+ } catch (err) {
457
+ console.error(err);
458
+ process.exit(1);
459
+ }
460
+
461
+ export default router;
462
+
463
+ export type Config = {
464
+ build: string;
465
+ src: string;
466
+ port: number;
467
+ secure: boolean;
468
+ esbuild?: BuildOptions;
469
+ "html-minifier-terser"?: MinifyOptions;
470
+ critical?: Options;
471
+ deletePrev?: boolean;
472
+ isCritical?: boolean;
473
+ hmr?: boolean;
474
+ handler?: string;
475
+ host?: string;
476
+ key?: Buffer;
477
+ cert?: Buffer;
478
+ };