html-bundle 5.5.0 → 6.0.1-beta

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/utils.mjs ADDED
@@ -0,0 +1,166 @@
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("/events", (_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) => CONNECTIONS.forEach((rep) => {
49
+ rep.write(`data: ${JSON.stringify(data)}\n\n`);
50
+ });
51
+ });
52
+ return fastify;
53
+ }
54
+ export function getPostCSSConfig() {
55
+ try {
56
+ return postcssrc({});
57
+ }
58
+ catch {
59
+ return { plugins: [cssnano], options: {}, file: "" };
60
+ }
61
+ }
62
+ async function getBundleConfig() {
63
+ const base = {
64
+ build: "build",
65
+ src: "src",
66
+ port: 5000,
67
+ esbuild: {},
68
+ "html-minifier-terser": {},
69
+ critical: {},
70
+ };
71
+ try {
72
+ const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
73
+ const config = await import(`file://${cfgPath}`);
74
+ return { ...base, ...config.default };
75
+ }
76
+ catch {
77
+ return base;
78
+ }
79
+ }
80
+ const htmlIdMap = new Map();
81
+ export function addHMRCode(html, file, ast) {
82
+ if (!htmlIdMap.has(file)) {
83
+ htmlIdMap.set(file, randomText());
84
+ }
85
+ const script = createScript({ type: "module" }, getHMRCode(file, htmlIdMap.get(file), bundleConfig.src));
86
+ let DOM;
87
+ if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
88
+ DOM = ast || parse(html);
89
+ const headNode = findElement(DOM, (e) => getTagName(e) === "head");
90
+ appendChild(headNode, script);
91
+ }
92
+ else {
93
+ DOM = ast || parseFragment(html);
94
+ appendChild(DOM, script);
95
+ }
96
+ //@ts-ignore
97
+ DOM.childNodes.forEach((node) => node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) }));
98
+ return serialize(DOM);
99
+ }
100
+ function randomText() {
101
+ return Math.random().toString(32).slice(2);
102
+ }
103
+ function getHMRCode(file, id, src) {
104
+ return `import { render, html, $, $$, setInsertDiffing } from "hydro-js";
105
+ if (!window.eventsource${id}) {
106
+ setInsertDiffing(true);
107
+ window.eventsource${id} = new EventSource("/events");
108
+ window.eventsource${id}.addEventListener("message", ({ data }) => {
109
+ const dataObj = JSON.parse(data);
110
+ const file = "${file}";
111
+
112
+ if (file === dataObj.file && "html" in dataObj) {
113
+ if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
114
+ document.head.remove(); // Don't try to diff the head – just re-run the scripts
115
+ render(html\`\${dataObj.html}\`, document.documentElement);
116
+ } else {
117
+ const hmrID = "${id}";
118
+ const newHTML = html\`\${dataObj.html}\`;
119
+ const hmrElems = Array.from(newHTML.childNodes);
120
+ const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
121
+ // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
122
+ hmrWheres.forEach((where, index) => {
123
+ if (index < hmrElems.length) {
124
+ render(hmrElems[index], where, false);
125
+ } else {
126
+ where.remove();
127
+ }
128
+ });
129
+ for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
130
+ if (hmrWheres.length) {
131
+ const template = document.createElement('template');
132
+ hmrElems[hmrWheres.length - 1].after(template);
133
+ render(hmrElems[rest], template, false);
134
+ template.remove();
135
+ } else {
136
+ render(hmrElems[rest], false, false)
137
+ }
138
+ }
139
+ }
140
+
141
+ setTimeout(() => dispatchEvent(new Event("popstate")));
142
+ } else if (dataObj.file.endsWith("css")) {
143
+ updateElem("link");
144
+ } else if (dataObj.file.endsWith("js")) {
145
+ updateElem("script")
146
+ }
147
+
148
+ function updateElem(type) {
149
+ const hmrId = "${id}";
150
+ const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
151
+ const attr = type === "script" ? "src" : "href";
152
+ const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
153
+
154
+ if (elem) {
155
+ const clone = document.createElement(type);
156
+ for (const key of elem.getAttributeNames()) {
157
+ clone.setAttribute(key, elem.getAttribute(key));
158
+ }
159
+ clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
160
+ render(clone, elem, false);
161
+ }
162
+ }
163
+ });
164
+ }
165
+ `;
166
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "html-bundle",
3
- "version": "5.5.0",
3
+ "version": "6.0.1-beta",
4
4
  "description": "A very simple bundler for HTML SFC",
5
- "bin": "./dist/bundle.js",
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,381 @@
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
+ const 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|m?jsx?|m?tsx?)$/;
45
+ const execFilePromise = promisify(execFile);
46
+
47
+ await rm(bundleConfig.build, { force: true, recursive: true });
48
+
49
+ glob(`${bundleConfig.src}/**/*.*`, build);
50
+
51
+ async function build(err: any, files: string[]) {
52
+ if (err) {
53
+ console.error(err);
54
+ process.exit(1);
55
+ }
56
+
57
+ if (isHMR) {
58
+ fastify = await createDefaultServer(isSecure);
59
+ fastify.listen(bundleConfig.port);
60
+ console.log(`💻 Sever listening on port ${bundleConfig.port}.`);
61
+ }
62
+
63
+ for (const file of files) {
64
+ await createDir(file);
65
+
66
+ if (!SUPPORTED_FILES.test(file)) {
67
+ if (handlerFile) {
68
+ const { stdout } = await execFilePromise("node", [handlerFile, file]);
69
+ console.log("📋 Logging Handler: ", String(stdout));
70
+ } else {
71
+ await fileCopy(file);
72
+ }
73
+ } else {
74
+ if (file.endsWith(".html")) {
75
+ await writeInlineScripts(file);
76
+ } else if (file.endsWith(".css")) {
77
+ await minifyCSS(file, getBuildPath(file));
78
+ } else {
79
+ inlineFiles.add(file);
80
+ }
81
+ }
82
+ }
83
+ await minifyCode();
84
+ for (const file of inlineFiles) {
85
+ if (INLINE_BUNDLE_FILE.test(file)) {
86
+ inlineFiles.delete(file);
87
+ await rm(file);
88
+ }
89
+ }
90
+ for (const file of files) {
91
+ if (file.endsWith(".html")) {
92
+ await minifyHTML(file, getBuildPath(file));
93
+ }
94
+ }
95
+
96
+ console.log(
97
+ `🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`
98
+ );
99
+
100
+ if (isHMR) {
101
+ console.log(`⌛ Waiting for file changes ...`);
102
+
103
+ if (postcssFile) {
104
+ const postCSSWatcher = watch(postcssFile);
105
+ const tailwindCSSWatcher = watch(
106
+ postcssFile.replace("postcss", "tailwind")
107
+ ); // Assuming that the file ext is the same
108
+
109
+ const cssFiles = files.filter((file) => file.endsWith(".css"));
110
+ postCSSWatcher.on(
111
+ "change",
112
+ async () => await rebuildCSS(cssFiles, "postcss")
113
+ );
114
+ tailwindCSSWatcher.on(
115
+ "change",
116
+ async () => await rebuildCSS(cssFiles, "tailwind")
117
+ );
118
+ }
119
+
120
+ const watcher = watch(bundleConfig.src);
121
+ let addCount = 0; // The add watcher will add all the files initially - do not rebuild them
122
+ watcher.on("add", async (file) => {
123
+ if (addCount++ <= files.length || INLINE_BUNDLE_FILE.test(file)) {
124
+ return;
125
+ }
126
+ file = String.raw`${file}`.replace(/\\/g, "/"); // glob and chokidar diff
127
+
128
+ await rebuild(file);
129
+
130
+ console.log(`⚡ added ${file} to the build`);
131
+ });
132
+ watcher.on("change", async (file) => {
133
+ if (INLINE_BUNDLE_FILE.test(file)) {
134
+ return;
135
+ }
136
+ file = String.raw`${file}`.replace(/\\/g, "/");
137
+
138
+ await rebuild(file);
139
+
140
+ console.log(`⚡ modified ${file} on the build`);
141
+ });
142
+ watcher.on("unlink", async (file) => {
143
+ if (INLINE_BUNDLE_FILE.test(file)) {
144
+ return;
145
+ }
146
+ file = String.raw`${file}`.replace(/\\/g, "/");
147
+
148
+ inlineFiles.delete(file);
149
+ const buildFile = getBuildPath(file)
150
+ .replace(".ts", ".js")
151
+ .replace(".jsx", ".js");
152
+ await rm(buildFile);
153
+
154
+ const bfDir = buildFile.split("/").slice(0, -1).join("/");
155
+ const stats = await readdir(bfDir);
156
+ if (!stats.length) await rm(bfDir);
157
+
158
+ console.log(`⚡ deleted ${file} from the build`);
159
+ });
160
+
161
+ async function rebuild(file: string) {
162
+ // Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
163
+ await rebuildCSS(files.filter((file) => file.endsWith(".css")));
164
+
165
+ let html;
166
+ if (file.endsWith(".html")) {
167
+ // To refill the inlineFiles needed to build JS
168
+ for (const htmlFile of files.filter((file) => file.endsWith("html"))) {
169
+ await writeInlineScripts(htmlFile);
170
+ }
171
+ await minifyCode();
172
+ for (const file of inlineFiles) {
173
+ if (INLINE_BUNDLE_FILE.test(file)) {
174
+ inlineFiles.delete(file);
175
+ await rm(file);
176
+ }
177
+ }
178
+ html = await minifyHTML(file, getBuildPath(file));
179
+ } else if (/(m?jsx?|m?tsx?)$/.test(file)) {
180
+ await minifyCode();
181
+ } else {
182
+ const { stdout } = await execFilePromise("node", [handlerFile, file]);
183
+ console.log("📋 Logging Handler: ", String(stdout));
184
+ }
185
+
186
+ serverSentEvents!({ file, html });
187
+ }
188
+ }
189
+ }
190
+
191
+ async function minifyCSS(file: string, buildFile: string) {
192
+ try {
193
+ const fileText = await readFile(file, { encoding: "utf-8" });
194
+ const result = await CSSprocessor.process(fileText, {
195
+ ...options,
196
+ from: file,
197
+ to: buildFile,
198
+ });
199
+ await writeFile(buildFile, result.css);
200
+ } catch (err) {
201
+ console.error(err);
202
+ }
203
+ }
204
+
205
+ async function minifyCode(): Promise<unknown> {
206
+ try {
207
+ return await esbuild.build({
208
+ entryPoints: Array.from(inlineFiles),
209
+ charset: "utf8",
210
+ format: "esm",
211
+ incremental: isHMR,
212
+ sourcemap: isHMR,
213
+ splitting: true,
214
+ define: {
215
+ "process.env.NODE_ENV": process.env.NODE_ENV,
216
+ },
217
+ loader: { ".js": "jsx", ".ts": "tsx" },
218
+ bundle: true,
219
+ minify: true,
220
+ outdir: bundleConfig.build,
221
+ outbase: bundleConfig.src,
222
+ ...bundleConfig.esbuild,
223
+ });
224
+ // Stop app from crashing.
225
+ } catch (err: any) {
226
+ if (!isHMR) {
227
+ console.error(err);
228
+ }
229
+
230
+ let missingPkg = false;
231
+ if (err?.errors) {
232
+ for (const error of err.errors) {
233
+ if (error.text?.startsWith("Could not resolve")) {
234
+ missingPkg = true;
235
+ const packageNameRegex = /(?<=").*(?=")/;
236
+ const [pkgName] = error.text.match(packageNameRegex);
237
+ console.log(`📦 Package ${pkgName} was installed for you`);
238
+
239
+ await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
240
+ "install",
241
+ pkgName,
242
+ ]);
243
+ }
244
+ }
245
+
246
+ if (missingPkg) {
247
+ missingPkg = false;
248
+ return minifyCode();
249
+ }
250
+ }
251
+ }
252
+ }
253
+
254
+ const htmlFilesCache = new Map();
255
+ async function writeInlineScripts(file: string) {
256
+ let fileText = await readFile(file, { encoding: "utf-8" });
257
+
258
+ let DOM;
259
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
260
+ DOM = parse(fileText);
261
+ } else {
262
+ DOM = parseFragment(fileText);
263
+ }
264
+
265
+ if (isHMR) {
266
+ fileText = addHMRCode(fileText, file, DOM);
267
+ }
268
+ htmlFilesCache.set(file, [fileText, DOM]);
269
+
270
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
271
+ for (let index = 0; index < scripts.length; index++) {
272
+ const script = scripts[index];
273
+ const scriptTextNode = script.childNodes[0] as TextNode;
274
+ const isReferencedScript = script.attrs.find((a) => a.name === "src");
275
+ const scriptContent = scriptTextNode?.value;
276
+ if (!scriptContent || isReferencedScript) continue;
277
+
278
+ const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
279
+ inlineFiles.add(jsFile);
280
+ await writeFile(jsFile, scriptContent);
281
+ }
282
+ }
283
+
284
+ async function minifyHTML(file: string, buildFile: string) {
285
+ let fileText, DOM;
286
+
287
+ if (htmlFilesCache.has(file)) {
288
+ const cache = htmlFilesCache.get(file);
289
+ fileText = cache[0];
290
+ DOM = cache[1];
291
+ } else {
292
+ fileText = await readFile(file, { encoding: "utf-8" });
293
+
294
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
295
+ DOM = parse(fileText);
296
+ } else {
297
+ DOM = parseFragment(fileText);
298
+ }
299
+ }
300
+
301
+ // Minify Code
302
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
303
+ for (let index = 0; index < scripts.length; index++) {
304
+ const script = scripts[index];
305
+ const scriptTextNode = script.childNodes[0] as TextNode;
306
+ const isReferencedScript = script.attrs.find((a) => a.name === "src");
307
+ if (!scriptTextNode?.value || isReferencedScript) continue;
308
+
309
+ // Use bundled file
310
+ const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
311
+
312
+ const scriptContent = await readFile(buildInlineScript, {
313
+ encoding: "utf-8",
314
+ });
315
+ await rm(buildInlineScript);
316
+ scriptTextNode.value = scriptContent.replace(
317
+ TEMPLATE_LITERAL_MINIFIER,
318
+ " "
319
+ );
320
+ }
321
+
322
+ // Minify Inline Style
323
+ const styles = findElements(DOM, (e) => getTagName(e) === "style");
324
+ for (const style of styles) {
325
+ const node = style.childNodes[0] as TextNode;
326
+ const styleContent = node?.value;
327
+ if (!styleContent) continue;
328
+
329
+ const { css } = await CSSprocessor.process(styleContent, {
330
+ ...options,
331
+ from: undefined,
332
+ });
333
+ node.value = css;
334
+ }
335
+
336
+ fileText = serialize(DOM);
337
+
338
+ // Minify HTML
339
+ fileText = await minify(fileText, {
340
+ collapseWhitespace: true,
341
+ removeComments: true,
342
+ ...bundleConfig["html-minifier-terser"],
343
+ });
344
+
345
+ if (!isCritical) {
346
+ await writeFile(buildFile, fileText);
347
+ return fileText;
348
+ } else {
349
+ const buildFileArr = buildFile.split("/");
350
+ const fileWithBase = buildFileArr.pop();
351
+ const buildDir = buildFileArr.join("/");
352
+
353
+ // critical is generating the files on the fs
354
+ try {
355
+ const { html } = await critical.generate({
356
+ base: buildDir,
357
+ html: fileText,
358
+ target: fileWithBase,
359
+ inline: !isSecure,
360
+ extract: true,
361
+ rebase: () => {},
362
+ ...bundleConfig.critical,
363
+ });
364
+ return html;
365
+ } catch (err) {
366
+ console.error(err);
367
+ }
368
+ }
369
+ }
370
+
371
+ async function rebuildCSS(files: string[], config?: string) {
372
+ const newConfig = await getPostCSSConfig();
373
+ plugins = newConfig.plugins;
374
+ options = newConfig.options;
375
+ CSSprocessor = postcss(plugins as AcceptedPlugin[]);
376
+ for (const file of files) {
377
+ await minifyCSS(file, getBuildPath(file));
378
+ }
379
+
380
+ if (config) console.log(`⚡ modified ${config}.config`);
381
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ declare module "await-spawn" {
2
+ export default (cmd: string, args: string[]): Promise<unknown> => {};
3
+ }