html-bundle 6.0.15 → 6.0.17

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/dist/bundle.mjs CHANGED
@@ -1,342 +1,345 @@
1
- #!/usr/bin/env node
2
- import { performance } from "perf_hooks";
3
- import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
4
- import { execFile } from "child_process";
5
- import { promisify } from "util";
6
- import glob from "glob";
7
- import postcss from "postcss";
8
- import esbuild from "esbuild";
9
- import Critters from "critters";
10
- import { minify } from "html-minifier-terser";
11
- import { watch } from "chokidar";
12
- import { serialize, parse, parseFragment } from "parse5";
13
- import { getTagName, findElements } from "@web/parse5-utils";
14
- import awaitSpawn from "await-spawn";
15
- import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.mjs";
16
- const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
17
- const isCritical = process.argv.includes("--isCritical") || bundleConfig.isCritical;
18
- const critters = new Critters({
19
- path: bundleConfig.build,
20
- logLevel: "silent",
21
- });
22
- const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
23
- const handlerFile = process.argv.includes("--handler")
24
- ? process.argv[process.argv.indexOf("--handler") + 1]
25
- : bundleConfig.handler;
26
- process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
27
- let timer = performance.now();
28
- let { plugins, options, file: postcssFile } = await getPostCSSConfig();
29
- let CSSprocessor = postcss(plugins);
30
- let fastify;
31
- const inlineFiles = new Set();
32
- const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
33
- const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
34
- const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
35
- const execFilePromise = promisify(execFile);
36
- if (bundleConfig.deletePrev) {
37
- await rm(bundleConfig.build, { force: true, recursive: true });
38
- }
39
- glob(`${bundleConfig.src}/**/*`, build);
40
- async function build(err, files, firstRun = true) {
41
- if (err) {
42
- console.error(err);
43
- process.exit(1);
44
- }
45
- if (isHMR && firstRun) {
46
- fastify = await createDefaultServer(isSecure);
47
- await fastify.listen({ port: bundleConfig.port });
48
- console.log(`💻 Sever listening on http${isSecure ? "s" : ""}://localhost:5000.`);
49
- }
50
- for (const file of files) {
51
- await createDir(file);
52
- if (!SUPPORTED_FILES.test(file)) {
53
- if (handlerFile) {
54
- const { stdout } = await execFilePromise("node", [handlerFile, file]);
55
- if (String(stdout))
56
- console.log("📋 Logging Handler: ", String(stdout));
57
- }
58
- else {
59
- if ((await lstat(file)).isDirectory())
60
- continue;
61
- await fileCopy(file);
62
- }
63
- }
64
- else {
65
- if (file.endsWith(".html")) {
66
- await writeInlineScripts(file);
67
- }
68
- else if (file.endsWith(".css")) {
69
- await minifyCSS(file, getBuildPath(file));
70
- }
71
- else {
72
- inlineFiles.add(file);
73
- }
74
- }
75
- }
76
- await minifyCode();
77
- for (const file of inlineFiles) {
78
- if (INLINE_BUNDLE_FILE.test(file)) {
79
- inlineFiles.delete(file);
80
- await rm(file);
81
- }
82
- }
83
- for (const file of files) {
84
- if (file.endsWith(".html")) {
85
- await minifyHTML(file, getBuildPath(file));
86
- }
87
- }
88
- console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
89
- if (isHMR && firstRun) {
90
- console.log(`⌛ Waiting for file changes ...`);
91
- if (postcssFile) {
92
- const postCSSWatcher = watch(postcssFile);
93
- const tailwindCSSWatcher = watch(postcssFile.replace("postcss", "tailwind")); // Assuming that the file ext is the same
94
- const tsConfigWatcher = watch(postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json");
95
- const cssFiles = files.filter((file) => file.endsWith(".css"));
96
- postCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "postcss"));
97
- tailwindCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "tailwind"));
98
- tsConfigWatcher.on("change", async () => {
99
- timer = performance.now();
100
- await build(null, files, false);
101
- });
102
- }
103
- const watcher = watch(bundleConfig.src);
104
- watcher.on("add", async (file) => {
105
- file = String.raw `${file}`.replace(/\\/g, "/"); // glob and chokidar diff
106
- if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
107
- return;
108
- }
109
- await rebuild(file);
110
- console.log(`⚡ added ${file} to the build`);
111
- });
112
- watcher.on("change", async (file) => {
113
- if (INLINE_BUNDLE_FILE.test(file)) {
114
- return;
115
- }
116
- file = String.raw `${file}`.replace(/\\/g, "/");
117
- await rebuild(file);
118
- console.log(`⚡ modified ${file} on the build`);
119
- });
120
- watcher.on("unlink", async (file) => {
121
- if (INLINE_BUNDLE_FILE.test(file)) {
122
- return;
123
- }
124
- file = String.raw `${file}`.replace(/\\/g, "/");
125
- inlineFiles.delete(file);
126
- const buildFile = getBuildPath(file)
127
- .replace(".ts", ".js")
128
- .replace(".jsx", ".js");
129
- await rm(buildFile);
130
- const bfDir = buildFile.split("/").slice(0, -1).join("/");
131
- const stats = await readdir(bfDir);
132
- if (!stats.length)
133
- await rm(bfDir);
134
- console.log(`⚡ deleted ${file} from the build`);
135
- });
136
- async function rebuild(file) {
137
- // Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
138
- await rebuildCSS(files.filter((file) => file.endsWith(".css")));
139
- let html;
140
- if (file.endsWith(".html")) {
141
- // To refill the inlineFiles needed to build JS
142
- for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
143
- await writeInlineScripts(htmlFile);
144
- }
145
- await minifyCode();
146
- for (const file of inlineFiles) {
147
- if (INLINE_BUNDLE_FILE.test(file)) {
148
- inlineFiles.delete(file);
149
- await rm(file);
150
- }
151
- }
152
- html = await minifyHTML(file, getBuildPath(file));
153
- }
154
- else if (/\.(jsx?|tsx?)$/.test(file)) {
155
- inlineFiles.add(file);
156
- await minifyCode();
157
- }
158
- else if (!file.endsWith(".css")) {
159
- if (handlerFile) {
160
- const { stdout } = await execFilePromise("node", [handlerFile, file]);
161
- if (String(stdout))
162
- console.log("📋 Logging Handler: ", String(stdout));
163
- }
164
- else {
165
- await fileCopy(file);
166
- }
167
- }
168
- serverSentEvents?.({ file, html });
169
- }
170
- }
171
- }
172
- async function minifyCSS(file, buildFile) {
173
- try {
174
- const fileText = await readFile(file, { encoding: "utf-8" });
175
- const result = await CSSprocessor.process(fileText, {
176
- ...options,
177
- from: file,
178
- to: buildFile,
179
- });
180
- await writeFile(buildFile, result.css);
181
- }
182
- catch (err) {
183
- console.error(err);
184
- }
185
- }
186
- async function minifyCode() {
187
- try {
188
- return await esbuild.build({
189
- entryPoints: Array.from(inlineFiles),
190
- charset: "utf8",
191
- format: "esm",
192
- incremental: isHMR,
193
- sourcemap: isHMR,
194
- splitting: true,
195
- define: {
196
- "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
197
- },
198
- loader: { ".js": "jsx", ".ts": "tsx" },
199
- bundle: true,
200
- minify: true,
201
- outdir: bundleConfig.build,
202
- outbase: bundleConfig.src,
203
- ...bundleConfig.esbuild,
204
- });
205
- // Stop app from crashing.
206
- }
207
- catch (err) {
208
- if (!isHMR) {
209
- console.error(err);
210
- }
211
- let missingPkg = false;
212
- if (err?.errors) {
213
- for (const error of err.errors) {
214
- if (error.text?.startsWith("Could not resolve")) {
215
- missingPkg = true;
216
- const packageNameRegex = /(?<=").*(?=")/;
217
- const [pkgName] = error.text.match(packageNameRegex);
218
- await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
219
- "install",
220
- pkgName,
221
- ]);
222
- console.log(`📦 Package ${pkgName} was installed for you`);
223
- }
224
- }
225
- if (missingPkg) {
226
- missingPkg = false;
227
- return minifyCode();
228
- }
229
- }
230
- }
231
- }
232
- const htmlFilesCache = new Map();
233
- async function writeInlineScripts(file) {
234
- let fileText = await readFile(file, { encoding: "utf-8" });
235
- let DOM;
236
- if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
237
- DOM = parse(fileText);
238
- }
239
- else {
240
- DOM = parseFragment(fileText);
241
- }
242
- if (isHMR) {
243
- fileText = addHMRCode(fileText, file, DOM);
244
- }
245
- htmlFilesCache.set(file, [fileText, DOM]);
246
- const scripts = findElements(DOM, (e) => getTagName(e) === "script");
247
- for (let index = 0; index < scripts.length; index++) {
248
- const script = scripts[index];
249
- const scriptTextNode = script.childNodes[0];
250
- const isReferencedScript = script.attrs.find((a) => a.name === "src");
251
- const scriptContent = scriptTextNode?.value;
252
- if (!scriptContent || isReferencedScript)
253
- continue;
254
- const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
255
- inlineFiles.add(jsFile);
256
- await writeFile(jsFile, scriptContent);
257
- }
258
- }
259
- async function minifyHTML(file, buildFile) {
260
- let fileText, DOM;
261
- if (htmlFilesCache.has(file)) {
262
- const cache = htmlFilesCache.get(file);
263
- fileText = cache[0];
264
- DOM = cache[1];
265
- }
266
- else {
267
- fileText = await readFile(file, { encoding: "utf-8" });
268
- if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
269
- DOM = parse(fileText);
270
- }
271
- else {
272
- DOM = parseFragment(fileText);
273
- }
274
- }
275
- // Minify Code
276
- const scripts = findElements(DOM, (e) => getTagName(e) === "script");
277
- for (let index = 0; index < scripts.length; index++) {
278
- const script = scripts[index];
279
- const scriptTextNode = script.childNodes[0];
280
- const isReferencedScript = script.attrs.find((a) => a.name === "src");
281
- if (!scriptTextNode?.value || isReferencedScript)
282
- continue;
283
- // Use bundled file
284
- const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
285
- const scriptContent = await readFile(buildInlineScript, {
286
- encoding: "utf-8",
287
- });
288
- await rm(buildInlineScript);
289
- scriptTextNode.value = scriptContent.replace(TEMPLATE_LITERAL_MINIFIER, " ");
290
- }
291
- // Minify Inline Style
292
- const styles = findElements(DOM, (e) => getTagName(e) === "style");
293
- for (const style of styles) {
294
- const node = style.childNodes[0];
295
- const styleContent = node?.value;
296
- if (!styleContent)
297
- continue;
298
- const { css } = await CSSprocessor.process(styleContent, {
299
- ...options,
300
- from: undefined,
301
- });
302
- node.value = css;
303
- }
304
- fileText = serialize(DOM);
305
- // Minify HTML
306
- try {
307
- fileText = await minify(fileText, {
308
- collapseWhitespace: true,
309
- removeComments: true,
310
- ...bundleConfig["html-minifier-terser"],
311
- });
312
- }
313
- catch (e) {
314
- console.error(e);
315
- }
316
- if (isCritical) {
317
- try {
318
- const isPartical = !fileText.startsWith("<!DOCTYPE html>");
319
- fileText = await critters.process(fileText);
320
- // fix critters jsdom
321
- if (isPartical) {
322
- fileText = fileText.replace(/<\/?(html|head|body)>/g, "");
323
- }
324
- }
325
- catch (err) {
326
- console.error(err);
327
- }
328
- }
329
- await writeFile(buildFile, fileText);
330
- return fileText;
331
- }
332
- async function rebuildCSS(files, config) {
333
- const newConfig = await getPostCSSConfig();
334
- plugins = newConfig.plugins;
335
- options = newConfig.options;
336
- CSSprocessor = postcss(plugins);
337
- for (const file of files) {
338
- await minifyCSS(file, getBuildPath(file));
339
- }
340
- if (config)
341
- console.log(`⚡ modified ${config}.config`);
342
- }
1
+ #!/usr/bin/env node
2
+ import { performance } from "perf_hooks";
3
+ import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
4
+ import { execFile } from "child_process";
5
+ import { promisify } from "util";
6
+ import { sep } from "path";
7
+ import { glob } from "glob";
8
+ import postcss from "postcss";
9
+ import esbuild from "esbuild";
10
+ import Critters from "critters";
11
+ import { minify } from "html-minifier-terser";
12
+ import { watch } from "chokidar";
13
+ import { serialize, parse, parseFragment } from "parse5";
14
+ import { getTagName, findElements } from "@web/parse5-utils";
15
+ import awaitSpawn from "await-spawn";
16
+ import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.mjs";
17
+ const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
18
+ const isCritical = process.argv.includes("--isCritical") || bundleConfig.isCritical;
19
+ const critters = new Critters({
20
+ path: bundleConfig.build,
21
+ logLevel: "silent",
22
+ });
23
+ const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
24
+ const handlerFile = process.argv.includes("--handler")
25
+ ? process.argv[process.argv.indexOf("--handler") + 1]
26
+ : bundleConfig.handler;
27
+ process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
28
+ let timer = performance.now();
29
+ let { plugins, options, file: postcssFile } = await getPostCSSConfig();
30
+ let CSSprocessor = postcss(plugins);
31
+ let fastify;
32
+ const inlineFiles = new Set();
33
+ const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
34
+ const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
35
+ const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
36
+ const execFilePromise = promisify(execFile);
37
+ if (bundleConfig.deletePrev) {
38
+ await rm(bundleConfig.build, { force: true, recursive: true });
39
+ }
40
+ async function build(files, firstRun = true) {
41
+ if (isHMR && firstRun) {
42
+ fastify = await createDefaultServer(isSecure);
43
+ await fastify.listen({ port: bundleConfig.port });
44
+ console.log(`💻 Sever listening on http${isSecure ? "s" : ""}://localhost:${bundleConfig.port}.`);
45
+ }
46
+ for (const file of files) {
47
+ await createDir(file);
48
+ if (!SUPPORTED_FILES.test(file)) {
49
+ if (handlerFile) {
50
+ const { stdout } = await execFilePromise("node", [handlerFile, file]);
51
+ if (String(stdout))
52
+ console.log("📋 Logging Handler: ", String(stdout));
53
+ }
54
+ else {
55
+ if ((await lstat(file)).isDirectory())
56
+ continue;
57
+ await fileCopy(file);
58
+ }
59
+ }
60
+ else {
61
+ if (file.endsWith(".html")) {
62
+ await writeInlineScripts(file);
63
+ }
64
+ else if (file.endsWith(".css")) {
65
+ await minifyCSS(file, getBuildPath(file));
66
+ }
67
+ else {
68
+ inlineFiles.add(file);
69
+ }
70
+ }
71
+ }
72
+ await minifyCode();
73
+ for (const file of inlineFiles) {
74
+ if (INLINE_BUNDLE_FILE.test(file)) {
75
+ inlineFiles.delete(file);
76
+ await rm(file);
77
+ }
78
+ }
79
+ for (const file of files) {
80
+ if (file.endsWith(".html")) {
81
+ await minifyHTML(file, getBuildPath(file));
82
+ }
83
+ }
84
+ console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
85
+ if (isHMR && firstRun) {
86
+ console.log(`⌛ Waiting for file changes ...`);
87
+ if (postcssFile) {
88
+ const postCSSWatcher = watch(postcssFile);
89
+ const tailwindCSSWatcher = watch(postcssFile.replace("postcss", "tailwind")); // Assuming that the file ext is the same
90
+ const tsConfigWatcher = watch(postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json");
91
+ const cssFiles = files.filter((file) => file.endsWith(".css"));
92
+ postCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "postcss"));
93
+ tailwindCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "tailwind"));
94
+ tsConfigWatcher.on("change", async () => {
95
+ timer = performance.now();
96
+ await build(files, false);
97
+ });
98
+ }
99
+ const watcher = watch(bundleConfig.src);
100
+ watcher.on("add", async (file) => {
101
+ file = String.raw `${file}`.replace(/\\/g, sep); // glob and chokidar diff
102
+ if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
103
+ return;
104
+ }
105
+ await rebuild(file);
106
+ console.log(`⚡ added ${file} to the build`);
107
+ });
108
+ watcher.on("change", async (file) => {
109
+ if (INLINE_BUNDLE_FILE.test(file)) {
110
+ return;
111
+ }
112
+ file = String.raw `${file}`.replace(/\\/g, sep);
113
+ await rebuild(file);
114
+ console.log(`⚡ modified ${file} on the build`);
115
+ });
116
+ watcher.on("unlink", async (file) => {
117
+ if (INLINE_BUNDLE_FILE.test(file)) {
118
+ return;
119
+ }
120
+ file = String.raw `${file}`.replace(/\\/g, sep);
121
+ inlineFiles.delete(file);
122
+ const buildFile = getBuildPath(file)
123
+ .replace(".ts", ".js")
124
+ .replace(".jsx", ".js");
125
+ await rm(buildFile);
126
+ const bfDir = buildFile.split(sep).slice(0, -1).join(sep);
127
+ const stats = await readdir(bfDir);
128
+ if (!stats.length)
129
+ await rm(bfDir);
130
+ console.log(`⚡ deleted ${file} from the build`);
131
+ });
132
+ async function rebuild(file) {
133
+ // Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
134
+ await rebuildCSS(files.filter((file) => file.endsWith(".css")));
135
+ let html;
136
+ if (file.endsWith(".html")) {
137
+ // To refill the inlineFiles needed to build JS
138
+ for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
139
+ await writeInlineScripts(htmlFile);
140
+ }
141
+ await minifyCode();
142
+ for (const file of inlineFiles) {
143
+ if (INLINE_BUNDLE_FILE.test(file)) {
144
+ inlineFiles.delete(file);
145
+ await rm(file);
146
+ }
147
+ }
148
+ html = await minifyHTML(file, getBuildPath(file));
149
+ }
150
+ else if (/\.(jsx?|tsx?)$/.test(file)) {
151
+ inlineFiles.add(file);
152
+ await minifyCode();
153
+ }
154
+ else if (!file.endsWith(".css")) {
155
+ if (handlerFile) {
156
+ const { stdout } = await execFilePromise("node", [handlerFile, file]);
157
+ if (String(stdout))
158
+ console.log("📋 Logging Handler: ", String(stdout));
159
+ }
160
+ else {
161
+ await fileCopy(file);
162
+ }
163
+ }
164
+ serverSentEvents?.({ file, html });
165
+ }
166
+ }
167
+ }
168
+ async function minifyCSS(file, buildFile) {
169
+ try {
170
+ const fileText = await readFile(file, { encoding: "utf-8" });
171
+ const result = await CSSprocessor.process(fileText, {
172
+ ...options,
173
+ from: file,
174
+ to: buildFile,
175
+ });
176
+ await writeFile(buildFile, result.css);
177
+ }
178
+ catch (err) {
179
+ console.error(err);
180
+ }
181
+ }
182
+ async function minifyCode() {
183
+ try {
184
+ return await esbuild.build({
185
+ entryPoints: Array.from(inlineFiles),
186
+ charset: "utf8",
187
+ format: "esm",
188
+ sourcemap: isHMR,
189
+ splitting: true,
190
+ define: {
191
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
192
+ },
193
+ loader: { ".js": "jsx", ".ts": "tsx" },
194
+ bundle: true,
195
+ minify: true,
196
+ outdir: bundleConfig.build,
197
+ outbase: bundleConfig.src,
198
+ ...bundleConfig.esbuild,
199
+ });
200
+ // Stop app from crashing.
201
+ }
202
+ catch (err) {
203
+ if (!isHMR) {
204
+ console.error(err);
205
+ }
206
+ let missingPkg = false;
207
+ if (err?.errors) {
208
+ for (const error of err.errors) {
209
+ if (error.text?.startsWith("Could not resolve")) {
210
+ missingPkg = true;
211
+ const packageNameRegex = /(?<=").*(?=")/;
212
+ const [pkgName] = error.text.match(packageNameRegex);
213
+ await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
214
+ "install",
215
+ pkgName,
216
+ ]);
217
+ console.log(`📦 Package ${pkgName} was installed for you`);
218
+ }
219
+ }
220
+ if (missingPkg) {
221
+ missingPkg = false;
222
+ return minifyCode();
223
+ }
224
+ }
225
+ }
226
+ }
227
+ const htmlFilesCache = new Map();
228
+ async function writeInlineScripts(file) {
229
+ let fileText = await readFile(file, { encoding: "utf-8" });
230
+ let DOM;
231
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
232
+ DOM = parse(fileText);
233
+ }
234
+ else {
235
+ DOM = parseFragment(fileText);
236
+ }
237
+ if (isHMR) {
238
+ fileText = addHMRCode(fileText, file, DOM);
239
+ }
240
+ htmlFilesCache.set(file, [fileText, DOM]);
241
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
242
+ for (let index = 0; index < scripts.length; index++) {
243
+ const script = scripts[index];
244
+ const scriptTextNode = script.childNodes[0];
245
+ const isReferencedScript = script.attrs.find((a) => a.name === "src");
246
+ const scriptContent = scriptTextNode?.value;
247
+ if (!scriptContent || isReferencedScript)
248
+ continue;
249
+ const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
250
+ inlineFiles.add(jsFile);
251
+ await writeFile(jsFile, scriptContent);
252
+ }
253
+ }
254
+ async function minifyHTML(file, buildFile) {
255
+ let fileText, DOM;
256
+ if (htmlFilesCache.has(file)) {
257
+ const cache = htmlFilesCache.get(file);
258
+ fileText = cache[0];
259
+ DOM = cache[1];
260
+ }
261
+ else {
262
+ fileText = await readFile(file, { encoding: "utf-8" });
263
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
264
+ DOM = parse(fileText);
265
+ }
266
+ else {
267
+ DOM = parseFragment(fileText);
268
+ }
269
+ }
270
+ // Minify Code
271
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
272
+ for (let index = 0; index < scripts.length; index++) {
273
+ const script = scripts[index];
274
+ const scriptTextNode = script.childNodes[0];
275
+ const isReferencedScript = script.attrs.find((a) => a.name === "src");
276
+ if (!scriptTextNode?.value || isReferencedScript)
277
+ continue;
278
+ // Use bundled file
279
+ const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
280
+ const scriptContent = await readFile(buildInlineScript, {
281
+ encoding: "utf-8",
282
+ });
283
+ await rm(buildInlineScript);
284
+ scriptTextNode.value = scriptContent.replace(TEMPLATE_LITERAL_MINIFIER, " ");
285
+ }
286
+ // Minify Inline Style
287
+ const styles = findElements(DOM, (e) => getTagName(e) === "style");
288
+ for (const style of styles) {
289
+ const node = style.childNodes[0];
290
+ const styleContent = node?.value;
291
+ if (!styleContent)
292
+ continue;
293
+ const { css } = await CSSprocessor.process(styleContent, {
294
+ ...options,
295
+ from: undefined,
296
+ });
297
+ node.value = css;
298
+ }
299
+ fileText = serialize(DOM);
300
+ // Minify HTML
301
+ try {
302
+ fileText = await minify(fileText, {
303
+ collapseWhitespace: true,
304
+ removeComments: true,
305
+ ...bundleConfig["html-minifier-terser"],
306
+ });
307
+ }
308
+ catch (e) {
309
+ console.error(e);
310
+ }
311
+ if (isCritical) {
312
+ try {
313
+ const isPartical = !fileText.startsWith("<!DOCTYPE html>");
314
+ fileText = await critters.process(fileText);
315
+ // fix critters jsdom
316
+ if (isPartical) {
317
+ fileText = fileText.replace(/<\/?(html|head|body)>/g, "");
318
+ }
319
+ }
320
+ catch (err) {
321
+ console.error(err);
322
+ }
323
+ }
324
+ await writeFile(buildFile, fileText);
325
+ return fileText;
326
+ }
327
+ async function rebuildCSS(files, config) {
328
+ const newConfig = await getPostCSSConfig();
329
+ plugins = newConfig.plugins;
330
+ options = newConfig.options;
331
+ CSSprocessor = postcss(plugins);
332
+ for (const file of files) {
333
+ await minifyCSS(file, getBuildPath(file));
334
+ }
335
+ if (config)
336
+ console.log(`⚡ modified ${config}.config`);
337
+ }
338
+ try {
339
+ const files = await glob(`${bundleConfig.src}/**/*`);
340
+ await build(files);
341
+ }
342
+ catch (err) {
343
+ console.error(err);
344
+ process.exit(1);
345
+ }
package/dist/utils.mjs CHANGED
@@ -1,112 +1,112 @@
1
- import { copyFile, mkdir, readFile } from "fs/promises";
2
- import path from "path";
3
- import Fastify from "fastify";
4
- import fastifyStatic from "@fastify/static";
5
- import postcssrc from "postcss-load-config";
6
- import cssnano from "cssnano";
7
- import { parse, parseFragment, serialize } from "parse5";
8
- import { createScript, getTagName, findElement, appendChild, } from "@web/parse5-utils";
9
- export const bundleConfig = await getBundleConfig();
10
- export function fileCopy(file) {
11
- return copyFile(file, getBuildPath(file));
12
- }
13
- export function createDir(file) {
14
- const buildPath = getBuildPath(file);
15
- const dir = buildPath.split("/").slice(0, -1).join("/");
16
- return mkdir(dir, { recursive: true });
17
- }
18
- export function getBuildPath(file) {
19
- return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
20
- }
21
- const CONNECTIONS = []; // In order to send the HMR information
22
- export let serverSentEvents;
23
- export async function createDefaultServer(isSecure) {
24
- const fastify = Fastify(isSecure
25
- ? {
26
- http2: true,
27
- https: {
28
- key: await readFile(path.join(process.cwd(), "localhost-key.pem")),
29
- cert: await readFile(path.join(process.cwd(), "localhost.pem")),
30
- },
31
- }
32
- : void 0);
33
- fastify.setNotFoundHandler(async (_req, reply) => {
34
- const file = await readFile(path.join(process.cwd(), bundleConfig.build, "/index.html"), {
35
- encoding: "utf-8",
36
- });
37
- reply.header("Content-Type", "text/html; charset=UTF-8");
38
- return reply.send(addHMRCode(file, `${bundleConfig.src}/index.html`));
39
- });
40
- fastify.register(fastifyStatic, {
41
- root: path.join(process.cwd(), bundleConfig.build),
42
- });
43
- fastify.get("/hmr", (_req, reply) => {
44
- reply.raw.setHeader("Content-Type", "text/event-stream");
45
- reply.raw.setHeader("Cache-Control", "no-cache");
46
- !isSecure && reply.raw.setHeader("Connection", "keep-alive");
47
- CONNECTIONS.push(reply.raw);
48
- serverSentEvents = (data) => {
49
- if (/\.(jsx?|tsx?)$/.test(data.file)) {
50
- data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
51
- }
52
- CONNECTIONS.forEach((rep) => {
53
- rep.write(`data: ${JSON.stringify(data)}\n\n`);
54
- });
55
- };
56
- });
57
- return fastify;
58
- }
59
- export async function getPostCSSConfig() {
60
- try {
61
- return await postcssrc({});
62
- }
63
- catch {
64
- return { plugins: [cssnano], options: {}, file: "" };
65
- }
66
- }
67
- async function getBundleConfig() {
68
- const base = {
69
- build: "build",
70
- src: "src",
71
- port: 5000,
72
- esbuild: {},
73
- "html-minifier-terser": {},
74
- critical: {},
75
- deletePrev: true,
76
- };
77
- try {
78
- const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
79
- const config = await import(`file://${cfgPath}`);
80
- return { ...base, ...config.default };
81
- }
82
- catch {
83
- return base;
84
- }
85
- }
86
- const htmlIdMap = new Map();
87
- export function addHMRCode(html, file, ast) {
88
- if (!htmlIdMap.has(file)) {
89
- htmlIdMap.set(file, randomText());
90
- }
91
- const script = createScript({ type: "module" }, getHMRCode(file, htmlIdMap.get(file), bundleConfig.src));
92
- let DOM;
93
- if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
94
- DOM = ast || parse(html);
95
- const headNode = findElement(DOM, (e) => getTagName(e) === "head");
96
- appendChild(headNode, script);
97
- }
98
- else {
99
- DOM = ast || parseFragment(html);
100
- appendChild(DOM, script);
101
- }
102
- //@ts-ignore
103
- DOM.childNodes.forEach((node) => node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) }));
104
- return serialize(DOM);
105
- }
106
- function randomText() {
107
- return Math.random().toString(32).slice(2);
108
- }
109
- function getHMRCode(file, id, src) {
1
+ import { copyFile, mkdir, readFile } from "fs/promises";
2
+ import path from "path";
3
+ import Fastify from "fastify";
4
+ import fastifyStatic from "@fastify/static";
5
+ import postcssrc from "postcss-load-config";
6
+ import cssnano from "cssnano";
7
+ import { parse, parseFragment, serialize } from "parse5";
8
+ import { createScript, getTagName, findElement, appendChild, } from "@web/parse5-utils";
9
+ export const bundleConfig = await getBundleConfig();
10
+ export function fileCopy(file) {
11
+ return copyFile(file, getBuildPath(file));
12
+ }
13
+ export function createDir(file) {
14
+ const buildPath = getBuildPath(file);
15
+ const dir = buildPath.split(path.sep).slice(0, -1).join(path.sep);
16
+ return mkdir(dir, { recursive: true });
17
+ }
18
+ export function getBuildPath(file) {
19
+ return file.replace(`${bundleConfig.src}${path.sep}`, `${bundleConfig.build}${path.sep}`);
20
+ }
21
+ const CONNECTIONS = []; // In order to send the HMR information
22
+ export let serverSentEvents;
23
+ export async function createDefaultServer(isSecure) {
24
+ const fastify = Fastify(isSecure
25
+ ? {
26
+ http2: true,
27
+ https: {
28
+ key: await readFile(path.join(process.cwd(), "localhost-key.pem")),
29
+ cert: await readFile(path.join(process.cwd(), "localhost.pem")),
30
+ },
31
+ }
32
+ : void 0);
33
+ fastify.setNotFoundHandler(async (_req, reply) => {
34
+ const file = await readFile(path.join(process.cwd(), bundleConfig.build, `${path.sep}index.html`), {
35
+ encoding: "utf-8",
36
+ });
37
+ reply.header("Content-Type", "text/html; charset=UTF-8");
38
+ return reply.send(addHMRCode(file, `${bundleConfig.src}${path.sep}index.html`));
39
+ });
40
+ fastify.register(fastifyStatic, {
41
+ root: path.join(process.cwd(), bundleConfig.build),
42
+ });
43
+ fastify.get("/hmr", (_req, reply) => {
44
+ reply.raw.setHeader("Content-Type", "text/event-stream");
45
+ reply.raw.setHeader("Cache-Control", "no-cache");
46
+ !isSecure && reply.raw.setHeader("Connection", "keep-alive");
47
+ CONNECTIONS.push(reply.raw);
48
+ serverSentEvents = (data) => {
49
+ if (/\.(jsx?|tsx?)$/.test(data.file)) {
50
+ data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
51
+ }
52
+ CONNECTIONS.forEach((rep) => {
53
+ rep.write(`data: ${JSON.stringify(data)}\n\n`);
54
+ });
55
+ };
56
+ });
57
+ return fastify;
58
+ }
59
+ export async function getPostCSSConfig() {
60
+ try {
61
+ return await postcssrc({});
62
+ }
63
+ catch {
64
+ return { plugins: [cssnano], options: {}, file: "" };
65
+ }
66
+ }
67
+ async function getBundleConfig() {
68
+ const base = {
69
+ build: "build",
70
+ src: "src",
71
+ port: 5000,
72
+ esbuild: {},
73
+ "html-minifier-terser": {},
74
+ critical: {},
75
+ deletePrev: true,
76
+ };
77
+ try {
78
+ const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
79
+ const config = await import(`file://${cfgPath}`);
80
+ return { ...base, ...config.default };
81
+ }
82
+ catch {
83
+ return base;
84
+ }
85
+ }
86
+ const htmlIdMap = new Map();
87
+ export function addHMRCode(html, file, ast) {
88
+ if (!htmlIdMap.has(file)) {
89
+ htmlIdMap.set(file, randomText());
90
+ }
91
+ const script = createScript({ type: "module" }, getHMRCode(file, htmlIdMap.get(file), bundleConfig.src));
92
+ let DOM;
93
+ if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
94
+ DOM = ast || parse(html);
95
+ const headNode = findElement(DOM, (e) => getTagName(e) === "head");
96
+ appendChild(headNode, script);
97
+ }
98
+ else {
99
+ DOM = ast || parseFragment(html);
100
+ appendChild(DOM, script);
101
+ }
102
+ //@ts-ignore
103
+ DOM.childNodes.forEach((node) => node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) }));
104
+ return serialize(DOM);
105
+ }
106
+ function randomText() {
107
+ return Math.random().toString(32).slice(2);
108
+ }
109
+ function getHMRCode(file, id, src) {
110
110
  return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
111
111
  window.isHMR = true;
112
112
  window.lastCalled = new Map();
@@ -213,5 +213,5 @@ function getHMRCode(file, id, src) {
213
213
  }
214
214
  });
215
215
  }
216
- `;
217
- }
216
+ `;
217
+ }
package/package.json CHANGED
@@ -1,49 +1,49 @@
1
- {
2
- "name": "html-bundle",
3
- "version": "6.0.15",
4
- "description": "A very simple bundler for HTML SFC",
5
- "bin": "./dist/bundle.mjs",
6
- "scripts": {
7
- "start": "tsc",
8
- "update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
9
- },
10
- "keywords": [
11
- "bundler",
12
- "SFC",
13
- "HTML",
14
- "TypeScript",
15
- "esbuild",
16
- "hydro-js"
17
- ],
18
- "author": "Fabian Krutsch <f.krutsch@gmx.de> (https://krutsch.netlify.app/)",
19
- "license": "MIT",
20
- "devDependencies": {
21
- "@types/cssnano": "^5.0.0",
22
- "@types/glob": "^8.0.0",
23
- "@types/html-minifier-terser": "^7.0.0",
24
- "@types/parse5": "^7.0.0",
25
- "@types/postcss-load-config": "^3.0.1",
26
- "typescript": "^4.9.4"
27
- },
28
- "repository": {
29
- "type": "git",
30
- "url": "git+https://github.com/Krutsch/html-bundle.git"
31
- },
32
- "bugs": "https://github.com/Krutsch/html-bundle/issues",
33
- "dependencies": {
34
- "@fastify/static": "^6.6.1",
35
- "@web/parse5-utils": "^1.3.0",
36
- "await-spawn": "^4.0.2",
37
- "chokidar": "^3.5.3",
38
- "critters": "^0.0.16",
39
- "cssnano": "^5.1.14",
40
- "esbuild": "^0.17.3",
41
- "fastify": "^4.11.0",
42
- "glob": "^8.1.0",
43
- "html-minifier-terser": "^7.1.0",
44
- "hydro-js": "^1.5.13",
45
- "parse5": "^7.1.2",
46
- "postcss": "^8.4.21",
47
- "postcss-load-config": "^4.0.1"
48
- }
49
- }
1
+ {
2
+ "name": "html-bundle",
3
+ "version": "6.0.17",
4
+ "description": "A very simple bundler for HTML SFC",
5
+ "bin": "./dist/bundle.mjs",
6
+ "scripts": {
7
+ "start": "tsc",
8
+ "update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
9
+ },
10
+ "keywords": [
11
+ "bundler",
12
+ "SFC",
13
+ "HTML",
14
+ "TypeScript",
15
+ "esbuild",
16
+ "hydro-js"
17
+ ],
18
+ "author": "Fabian Krutsch <f.krutsch@gmx.de> (https://krutsch.netlify.app/)",
19
+ "license": "MIT",
20
+ "devDependencies": {
21
+ "@types/cssnano": "^5.0.0",
22
+ "@types/glob": "^8.1.0",
23
+ "@types/html-minifier-terser": "^7.0.0",
24
+ "@types/parse5": "^7.0.0",
25
+ "@types/postcss-load-config": "^3.0.1",
26
+ "typescript": "^5.0.4"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/Krutsch/html-bundle.git"
31
+ },
32
+ "bugs": "https://github.com/Krutsch/html-bundle/issues",
33
+ "dependencies": {
34
+ "@fastify/static": "^6.10.1",
35
+ "@web/parse5-utils": "^2.0.0",
36
+ "await-spawn": "^4.0.2",
37
+ "chokidar": "^3.5.3",
38
+ "critters": "^0.0.16",
39
+ "cssnano": "^6.0.0",
40
+ "esbuild": "^0.17.18",
41
+ "fastify": "^4.17.0",
42
+ "glob": "^10.2.2",
43
+ "html-minifier-terser": "^7.2.0",
44
+ "hydro-js": "^1.5.14",
45
+ "parse5": "^7.1.2",
46
+ "postcss": "^8.4.23",
47
+ "postcss-load-config": "^4.0.1"
48
+ }
49
+ }
package/src/bundle.mts CHANGED
@@ -6,7 +6,8 @@ import { performance } from "perf_hooks";
6
6
  import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
7
7
  import { execFile } from "child_process";
8
8
  import { promisify } from "util";
9
- import glob from "glob";
9
+ import { sep } from "path";
10
+ import { glob } from "glob";
10
11
  import postcss from "postcss";
11
12
  import esbuild from "esbuild";
12
13
  import Critters from "critters";
@@ -53,19 +54,14 @@ if (bundleConfig.deletePrev) {
53
54
  await rm(bundleConfig.build, { force: true, recursive: true });
54
55
  }
55
56
 
56
- glob(`${bundleConfig.src}/**/*`, build);
57
-
58
- async function build(err: any, files: string[], firstRun = true) {
59
- if (err) {
60
- console.error(err);
61
- process.exit(1);
62
- }
63
-
57
+ async function build(files: string[], firstRun = true) {
64
58
  if (isHMR && firstRun) {
65
59
  fastify = await createDefaultServer(isSecure);
66
60
  await fastify.listen({ port: bundleConfig.port });
67
61
  console.log(
68
- `💻 Sever listening on http${isSecure ? "s" : ""}://localhost:5000.`
62
+ `💻 Sever listening on http${isSecure ? "s" : ""}://localhost:${
63
+ bundleConfig.port
64
+ }.`
69
65
  );
70
66
  }
71
67
 
@@ -130,13 +126,13 @@ async function build(err: any, files: string[], firstRun = true) {
130
126
  );
131
127
  tsConfigWatcher.on("change", async () => {
132
128
  timer = performance.now();
133
- await build(null, files, false);
129
+ await build(files, false);
134
130
  });
135
131
  }
136
132
 
137
133
  const watcher = watch(bundleConfig.src);
138
134
  watcher.on("add", async (file) => {
139
- file = String.raw`${file}`.replace(/\\/g, "/"); // glob and chokidar diff
135
+ file = String.raw`${file}`.replace(/\\/g, sep); // glob and chokidar diff
140
136
  if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
141
137
  return;
142
138
  }
@@ -149,7 +145,7 @@ async function build(err: any, files: string[], firstRun = true) {
149
145
  if (INLINE_BUNDLE_FILE.test(file)) {
150
146
  return;
151
147
  }
152
- file = String.raw`${file}`.replace(/\\/g, "/");
148
+ file = String.raw`${file}`.replace(/\\/g, sep);
153
149
 
154
150
  await rebuild(file);
155
151
 
@@ -159,7 +155,7 @@ async function build(err: any, files: string[], firstRun = true) {
159
155
  if (INLINE_BUNDLE_FILE.test(file)) {
160
156
  return;
161
157
  }
162
- file = String.raw`${file}`.replace(/\\/g, "/");
158
+ file = String.raw`${file}`.replace(/\\/g, sep);
163
159
 
164
160
  inlineFiles.delete(file);
165
161
  const buildFile = getBuildPath(file)
@@ -167,7 +163,7 @@ async function build(err: any, files: string[], firstRun = true) {
167
163
  .replace(".jsx", ".js");
168
164
  await rm(buildFile);
169
165
 
170
- const bfDir = buildFile.split("/").slice(0, -1).join("/");
166
+ const bfDir = buildFile.split(sep).slice(0, -1).join(sep);
171
167
  const stats = await readdir(bfDir);
172
168
  if (!stats.length) await rm(bfDir);
173
169
 
@@ -230,7 +226,6 @@ async function minifyCode(): Promise<unknown> {
230
226
  entryPoints: Array.from(inlineFiles),
231
227
  charset: "utf8",
232
228
  format: "esm",
233
- incremental: isHMR,
234
229
  sourcemap: isHMR,
235
230
  splitting: true,
236
231
  define: {
@@ -401,3 +396,11 @@ async function rebuildCSS(files: string[], config?: string) {
401
396
 
402
397
  if (config) console.log(`⚡ modified ${config}.config`);
403
398
  }
399
+
400
+ try {
401
+ const files = await glob(`${bundleConfig.src}/**/*`);
402
+ await build(files);
403
+ } catch (err) {
404
+ console.error(err);
405
+ process.exit(1);
406
+ }
package/src/utils.mts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Node, ParentNode } from "@web/parse5-utils";
1
+ import type { Node } from "@web/parse5-utils";
2
2
  import type { FastifyServerOptions } from "fastify";
3
3
  import { copyFile, mkdir, readFile } from "fs/promises";
4
4
  import path from "path";
@@ -22,12 +22,15 @@ export function fileCopy(file: string) {
22
22
 
23
23
  export function createDir(file: string) {
24
24
  const buildPath = getBuildPath(file);
25
- const dir = buildPath.split("/").slice(0, -1).join("/");
25
+ const dir = buildPath.split(path.sep).slice(0, -1).join(path.sep);
26
26
  return mkdir(dir, { recursive: true });
27
27
  }
28
28
 
29
29
  export function getBuildPath(file: string) {
30
- return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
30
+ return file.replace(
31
+ `${bundleConfig.src}${path.sep}`,
32
+ `${bundleConfig.build}${path.sep}`
33
+ );
31
34
  }
32
35
 
33
36
  const CONNECTIONS: Array<any> = []; // In order to send the HMR information
@@ -48,13 +51,15 @@ export async function createDefaultServer(isSecure: boolean) {
48
51
  );
49
52
  fastify.setNotFoundHandler(async (_req, reply) => {
50
53
  const file = await readFile(
51
- path.join(process.cwd(), bundleConfig.build, "/index.html"),
54
+ path.join(process.cwd(), bundleConfig.build, `${path.sep}index.html`),
52
55
  {
53
56
  encoding: "utf-8",
54
57
  }
55
58
  );
56
59
  reply.header("Content-Type", "text/html; charset=UTF-8");
57
- return reply.send(addHMRCode(file, `${bundleConfig.src}/index.html`));
60
+ return reply.send(
61
+ addHMRCode(file, `${bundleConfig.src}${path.sep}index.html`)
62
+ );
58
63
  });
59
64
  fastify.register(fastifyStatic, {
60
65
  root: path.join(process.cwd(), bundleConfig.build),