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 CHANGED
@@ -1,8 +1,20 @@
1
1
  # html-bundle
2
2
 
3
- > A very simple zero-config bundler primarily for HTML files. The idea is to use HTML as Single File Components, because HTML can already include `<style>` and `<script>` elements. Additionally, `TypeScript` and `JSX` can be used as inline or referenced script in HTML.
3
+ <p align="center">
4
+ <img src="./logo.jpg" style="width:500px;" />
5
+ </p>
4
6
 
5
- ![Demo](./example.gif)
7
+ A (primarily) zero-config bundler for HTML files. The idea is to use HTML as Single File Components, because HTML can already include `<style>` and `<script>` elements.
8
+
9
+ ## Features
10
+
11
+ - 🦾 TypeScript (reference it as .js or write inline TS)
12
+ - 📦 Automatic Package Installation
13
+ - 💨 HMR and automatic reconnect
14
+ - ⚡ [ESBuild](https://github.com/evanw/esbuild)
15
+ - 🦔 [Critical CSS](https://github.com/evanw/esbuild)
16
+ - 🚋 Watcher on PostCSS and Tailwind CSS and TS Config
17
+ - 🛡️ Almost no need to restart
6
18
 
7
19
  ## Installation and Usage
8
20
 
@@ -20,19 +32,7 @@ Add an entry to script in package.json (see flags below).
20
32
  }
21
33
  ```
22
34
 
23
- or ideally
24
-
25
- ```json
26
- {
27
- "scripts": {
28
- "dev": "html-bundle --hmr --secure",
29
- "build": "html-bundle --critical",
30
- "serve": "html-bundle --serveOnly --secure"
31
- }
32
- }
33
- ```
34
-
35
- Add a `postcss.config.cjs` file and run the build command.
35
+ Add a `postcss.config.js` file and run the build command.
36
36
  <em>If you do not create this config file, a minimal in-memory config file will be created with `cssnano` as plugin.</em>
37
37
 
38
38
  ```properties
@@ -41,22 +41,34 @@ $ npm run build
41
41
 
42
42
  ## CLI
43
43
 
44
- `--serveOnly`: boots up a static server for the build folder (fastify)<br>
44
+ `--hmr`: boots up a static server and enables Hot Module Replacement. **This generates a development build and works best when not triggered from the main index.html**<br>
45
45
  `--secure`: creates a secure HTTP2 over HTTPS instance. This requires the files `localhost.pem` and `localhost-key.pem` in the root folder. You can generate them with [mkcert](https://github.com/FiloSottile/mkcert) for instance.<br>
46
- `--hmr`: boots up a static server and enables Hot Module Replacement. This works at its best with non-root HTML files without file references.<br>
47
- `--critical`: uses [critical](https://www.npmjs.com/package/critical) to extract and inline critical-path CSS to HTML.<br>
48
- `--csp`: disables inline option from `critical`.
46
+ `--critical`: uses critical to extract and inline critical-path CSS to HTML.<br>
47
+ `--handler`: path to your custom handler. Here, you can handle all non-supported files. You can get the filename via `process.argv[2]`.
48
+
49
+ ## Optional Config
50
+
51
+ _The CLI flags can also be set by the config. Flags set by the CLI will override the config._
52
+ Generate the config in the root and call it "bundle.config.js"
53
+
54
+ **src:** input path. Default to "src"<br>
55
+ **build:** output path. Defaults to "build"<br>
56
+ **port:** For the HMR Server. Defaults to 5000<br>
57
+ **deletePrev:** Whether to delelte the build folder. Defaults to true<br>
58
+ **esbuild:** Your additional config<br>
59
+ **html-minifier-terser:** Your additional config<br>
60
+ **critical:** Your additional config<br>
49
61
 
50
62
  ## Concept
51
63
 
52
- The bundler always globs all HTML, CSS and TS/JS files from the `src/` directory and processes them to the `build/` directory. PostCSS is being used for CSS files and inline styles, html-minifier for HTML and esbuild to bundle, minify, etc. for inline and referenced TS/JS. There are no <strong>regexes</strong>, just <strong>AST</strong> transformations. Server-sent events and [hydro-js](https://github.com/Krutsch/hydro-js) are used for HMR.
64
+ The bundler always globs all HTML, CSS and TS/JS files from the `src` (config) directory and processes them to the `build` (config) directory. PostCSS is being used for CSS files and inline styles, html-minifier-terser for HTML and esbuild to bundle, minify, etc. for inline and referenced TS/JS. Server-sent events and [hydro-js](https://github.com/Krutsch/hydro-js) are used for HMR. This will install hydro-js to your dependencies. In order to trigger SPA Routers, the popstate event is being triggered after HMR Operations.
53
65
 
54
66
  ## Example hydro-js
55
67
 
56
- Have a look at [hydro-starter](https://github.com/Krutsch/hydro-starter).<br>
68
+ Get the idea from [hydro-starter](https://github.com/Krutsch/hydro-starter).<br>
57
69
  Set `"jsxFactory": "h"` in `tsconfig.json` for JSX.
58
70
 
59
- #### Input
71
+ ### Input
60
72
 
61
73
  ```html
62
74
  <!DOCTYPE html>
@@ -67,13 +79,14 @@ Set `"jsxFactory": "h"` in `tsconfig.json` for JSX.
67
79
  <title>Example</title>
68
80
  <meta name="Description" content="Example for html-bundle" />
69
81
  <script type="module">
70
- import { render, h } from "hydro-js";
82
+ import { render, h, reactive } from "hydro-js";
71
83
 
72
- function Example() {
73
- return <main id="app">Testing html-bundle</main>;
84
+ function Example({ name }) {
85
+ return <main id="app">Hi {name}</main>;
74
86
  }
75
87
 
76
- render(<Example />, "#app");
88
+ const name = reactive("Tester");
89
+ render(<Example name={name} />, "#app");
77
90
  </script>
78
91
  <style>
79
92
  body {
@@ -91,7 +104,7 @@ Set `"jsxFactory": "h"` in `tsconfig.json` for JSX.
91
104
 
92
105
  ![Output](output.JPG)
93
106
 
94
- ## Example Vue.js
107
+ ## Example Vue.js@next
95
108
 
96
109
  Set `"jsxFactory": "h"` in `tsconfig.json`.
97
110
 
@@ -127,7 +140,7 @@ Set `"jsxFactory": "h"` in `tsconfig.json`.
127
140
 
128
141
  ## Example React
129
142
 
130
- Set `"jsxFactory": "React.createElement"` in `tsconfig.json`.
143
+ Set `"jsxFactory": "h"` in `tsconfig.json`.
131
144
 
132
145
  ```html
133
146
  <!DOCTYPE html>
@@ -140,6 +153,7 @@ Set `"jsxFactory": "React.createElement"` in `tsconfig.json`.
140
153
  <script type="module">
141
154
  import React, { useState } from "react";
142
155
  import { render } from "react-dom";
156
+ const h = React.createElement;
143
157
 
144
158
  function Example() {
145
159
  const [count, setCount] = useState(0);
@@ -152,10 +166,14 @@ Set `"jsxFactory": "React.createElement"` in `tsconfig.json`.
152
166
  );
153
167
  }
154
168
 
155
- render(<Example />, document.getElementById("root"));
169
+ render(<Example />, document.getElementById("app"));
156
170
  </script>
157
171
  <body>
158
- <div id="root"></div>
172
+ <div id="app"></div>
159
173
  </body>
160
174
  </html>
161
175
  ```
176
+
177
+ ### Demo
178
+
179
+ ![Demo](./example.gif)
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env node
2
+ import { performance } from "perf_hooks";
3
+ import { readFile, rm, writeFile, readdir } 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 critical from "critical";
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("--critical") || bundleConfig.critical;
18
+ const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
19
+ const handlerFile = process.argv.includes("--handler")
20
+ ? process.argv[process.argv.indexOf("--handler") + 1]
21
+ : bundleConfig.handler;
22
+ process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
23
+ let timer = performance.now();
24
+ let { plugins, options, file: postcssFile } = await getPostCSSConfig();
25
+ let CSSprocessor = postcss(plugins);
26
+ let fastify;
27
+ const inlineFiles = new Set();
28
+ const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
29
+ const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
30
+ const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
31
+ const execFilePromise = promisify(execFile);
32
+ if (bundleConfig.deletePrev) {
33
+ await rm(bundleConfig.build, { force: true, recursive: true });
34
+ }
35
+ glob(`${bundleConfig.src}/**/*.*`, build);
36
+ async function build(err, files, firstRun = true) {
37
+ if (err) {
38
+ console.error(err);
39
+ process.exit(1);
40
+ }
41
+ if (isHMR && firstRun) {
42
+ fastify = await createDefaultServer(isSecure);
43
+ fastify.listen(bundleConfig.port);
44
+ console.log(`💻 Sever listening on port ${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
+ await fileCopy(file);
56
+ }
57
+ }
58
+ else {
59
+ if (file.endsWith(".html")) {
60
+ await writeInlineScripts(file);
61
+ }
62
+ else if (file.endsWith(".css")) {
63
+ await minifyCSS(file, getBuildPath(file));
64
+ }
65
+ else {
66
+ inlineFiles.add(file);
67
+ }
68
+ }
69
+ }
70
+ await minifyCode();
71
+ for (const file of inlineFiles) {
72
+ if (INLINE_BUNDLE_FILE.test(file)) {
73
+ inlineFiles.delete(file);
74
+ await rm(file);
75
+ }
76
+ }
77
+ for (const file of files) {
78
+ if (file.endsWith(".html")) {
79
+ await minifyHTML(file, getBuildPath(file));
80
+ }
81
+ }
82
+ console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
83
+ if (isHMR && firstRun) {
84
+ console.log(`⌛ Waiting for file changes ...`);
85
+ if (postcssFile) {
86
+ const postCSSWatcher = watch(postcssFile);
87
+ const tailwindCSSWatcher = watch(postcssFile.replace("postcss", "tailwind")); // Assuming that the file ext is the same
88
+ const tsConfigWatcher = watch(postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json");
89
+ const cssFiles = files.filter((file) => file.endsWith(".css"));
90
+ postCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "postcss"));
91
+ tailwindCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "tailwind"));
92
+ tsConfigWatcher.on("change", async () => {
93
+ timer = performance.now();
94
+ await build(null, files, false);
95
+ });
96
+ }
97
+ const watcher = watch(bundleConfig.src);
98
+ let addCount = 0; // The add watcher will add all the files initially - do not rebuild them
99
+ watcher.on("add", async (file) => {
100
+ if (addCount++ <= files.length || INLINE_BUNDLE_FILE.test(file)) {
101
+ return;
102
+ }
103
+ file = String.raw `${file}`.replace(/\\/g, "/"); // glob and chokidar diff
104
+ await rebuild(file);
105
+ console.log(`⚡ added ${file} to the build`);
106
+ });
107
+ watcher.on("change", async (file) => {
108
+ if (INLINE_BUNDLE_FILE.test(file)) {
109
+ return;
110
+ }
111
+ file = String.raw `${file}`.replace(/\\/g, "/");
112
+ await rebuild(file);
113
+ console.log(`⚡ modified ${file} on the build`);
114
+ });
115
+ watcher.on("unlink", async (file) => {
116
+ if (INLINE_BUNDLE_FILE.test(file)) {
117
+ return;
118
+ }
119
+ file = String.raw `${file}`.replace(/\\/g, "/");
120
+ inlineFiles.delete(file);
121
+ const buildFile = getBuildPath(file)
122
+ .replace(".ts", ".js")
123
+ .replace(".jsx", ".js");
124
+ await rm(buildFile);
125
+ const bfDir = buildFile.split("/").slice(0, -1).join("/");
126
+ const stats = await readdir(bfDir);
127
+ if (!stats.length)
128
+ await rm(bfDir);
129
+ console.log(`⚡ deleted ${file} from the build`);
130
+ });
131
+ async function rebuild(file) {
132
+ // Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
133
+ await rebuildCSS(files.filter((file) => file.endsWith(".css")));
134
+ let html;
135
+ if (file.endsWith(".html")) {
136
+ // To refill the inlineFiles needed to build JS
137
+ for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
138
+ await writeInlineScripts(htmlFile);
139
+ }
140
+ await minifyCode();
141
+ for (const file of inlineFiles) {
142
+ if (INLINE_BUNDLE_FILE.test(file)) {
143
+ inlineFiles.delete(file);
144
+ await rm(file);
145
+ }
146
+ }
147
+ html = await minifyHTML(file, getBuildPath(file));
148
+ }
149
+ else if (/\.(jsx?|tsx?)$/.test(file)) {
150
+ inlineFiles.add(file);
151
+ await minifyCode();
152
+ }
153
+ else {
154
+ const { stdout } = await execFilePromise("node", [handlerFile, file]);
155
+ if (String(stdout))
156
+ console.log("📋 Logging Handler: ", String(stdout));
157
+ }
158
+ serverSentEvents?.({ file, html });
159
+ }
160
+ }
161
+ }
162
+ async function minifyCSS(file, buildFile) {
163
+ try {
164
+ const fileText = await readFile(file, { encoding: "utf-8" });
165
+ const result = await CSSprocessor.process(fileText, {
166
+ ...options,
167
+ from: file,
168
+ to: buildFile,
169
+ });
170
+ await writeFile(buildFile, result.css);
171
+ }
172
+ catch (err) {
173
+ console.error(err);
174
+ }
175
+ }
176
+ async function minifyCode() {
177
+ try {
178
+ return await esbuild.build({
179
+ entryPoints: Array.from(inlineFiles),
180
+ charset: "utf8",
181
+ format: "esm",
182
+ incremental: isHMR,
183
+ sourcemap: isHMR,
184
+ splitting: true,
185
+ define: {
186
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
187
+ },
188
+ loader: { ".js": "jsx", ".ts": "tsx" },
189
+ bundle: true,
190
+ minify: true,
191
+ outdir: bundleConfig.build,
192
+ outbase: bundleConfig.src,
193
+ ...bundleConfig.esbuild,
194
+ });
195
+ // Stop app from crashing.
196
+ }
197
+ catch (err) {
198
+ if (!isHMR) {
199
+ console.error(err);
200
+ }
201
+ let missingPkg = false;
202
+ if (err?.errors) {
203
+ for (const error of err.errors) {
204
+ if (error.text?.startsWith("Could not resolve")) {
205
+ missingPkg = true;
206
+ const packageNameRegex = /(?<=").*(?=")/;
207
+ const [pkgName] = error.text.match(packageNameRegex);
208
+ console.log(`📦 Package ${pkgName} was installed for you`);
209
+ await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
210
+ "install",
211
+ pkgName,
212
+ ]);
213
+ }
214
+ }
215
+ if (missingPkg) {
216
+ missingPkg = false;
217
+ return minifyCode();
218
+ }
219
+ }
220
+ }
221
+ }
222
+ const htmlFilesCache = new Map();
223
+ async function writeInlineScripts(file) {
224
+ let fileText = await readFile(file, { encoding: "utf-8" });
225
+ let DOM;
226
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
227
+ DOM = parse(fileText);
228
+ }
229
+ else {
230
+ DOM = parseFragment(fileText);
231
+ }
232
+ if (isHMR) {
233
+ fileText = addHMRCode(fileText, file, DOM);
234
+ }
235
+ htmlFilesCache.set(file, [fileText, DOM]);
236
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
237
+ for (let index = 0; index < scripts.length; index++) {
238
+ const script = scripts[index];
239
+ const scriptTextNode = script.childNodes[0];
240
+ const isReferencedScript = script.attrs.find((a) => a.name === "src");
241
+ const scriptContent = scriptTextNode?.value;
242
+ if (!scriptContent || isReferencedScript)
243
+ continue;
244
+ const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
245
+ inlineFiles.add(jsFile);
246
+ await writeFile(jsFile, scriptContent);
247
+ }
248
+ }
249
+ async function minifyHTML(file, buildFile) {
250
+ let fileText, DOM;
251
+ if (htmlFilesCache.has(file)) {
252
+ const cache = htmlFilesCache.get(file);
253
+ fileText = cache[0];
254
+ DOM = cache[1];
255
+ }
256
+ else {
257
+ fileText = await readFile(file, { encoding: "utf-8" });
258
+ if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
259
+ DOM = parse(fileText);
260
+ }
261
+ else {
262
+ DOM = parseFragment(fileText);
263
+ }
264
+ }
265
+ // Minify Code
266
+ const scripts = findElements(DOM, (e) => getTagName(e) === "script");
267
+ for (let index = 0; index < scripts.length; index++) {
268
+ const script = scripts[index];
269
+ const scriptTextNode = script.childNodes[0];
270
+ const isReferencedScript = script.attrs.find((a) => a.name === "src");
271
+ if (!scriptTextNode?.value || isReferencedScript)
272
+ continue;
273
+ // Use bundled file
274
+ const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
275
+ const scriptContent = await readFile(buildInlineScript, {
276
+ encoding: "utf-8",
277
+ });
278
+ await rm(buildInlineScript);
279
+ scriptTextNode.value = scriptContent.replace(TEMPLATE_LITERAL_MINIFIER, " ");
280
+ }
281
+ // Minify Inline Style
282
+ const styles = findElements(DOM, (e) => getTagName(e) === "style");
283
+ for (const style of styles) {
284
+ const node = style.childNodes[0];
285
+ const styleContent = node?.value;
286
+ if (!styleContent)
287
+ continue;
288
+ const { css } = await CSSprocessor.process(styleContent, {
289
+ ...options,
290
+ from: undefined,
291
+ });
292
+ node.value = css;
293
+ }
294
+ fileText = serialize(DOM);
295
+ // Minify HTML
296
+ try {
297
+ fileText = await minify(fileText, {
298
+ collapseWhitespace: true,
299
+ removeComments: true,
300
+ ...bundleConfig["html-minifier-terser"],
301
+ });
302
+ }
303
+ catch (e) {
304
+ console.error(e);
305
+ }
306
+ if (!isCritical) {
307
+ await writeFile(buildFile, fileText);
308
+ return fileText;
309
+ }
310
+ else {
311
+ const buildFileArr = buildFile.split("/");
312
+ const fileWithBase = buildFileArr.pop();
313
+ const buildDir = buildFileArr.join("/");
314
+ // critical is generating the files on the fs
315
+ try {
316
+ const { html } = await critical.generate({
317
+ base: buildDir,
318
+ html: fileText,
319
+ target: fileWithBase,
320
+ inline: !isSecure,
321
+ extract: true,
322
+ rebase: () => { },
323
+ ...bundleConfig.critical,
324
+ });
325
+ return html;
326
+ }
327
+ catch (err) {
328
+ console.error(err);
329
+ }
330
+ }
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
+ }
package/dist/utils.mjs ADDED
@@ -0,0 +1,195 @@
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) {
110
+ return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
111
+ window.isHMR = true;
112
+ if (!window.eventsource${id}) {
113
+ window.eventsource${id} = new EventSource("/hmr");
114
+ window.eventsource${id}.addEventListener('error', (e) => {
115
+ setTimeout(() => {
116
+ window.eventsource${id} = new EventSource("/hmr");
117
+ }, 1000);
118
+ });
119
+ window.eventsource${id}.addEventListener("message", ({ data }) => {
120
+ const dataObj = JSON.parse(data);
121
+ const file = "${file}";
122
+
123
+ if (file === dataObj.file && "html" in dataObj) {
124
+ let newHTML;
125
+ try {
126
+ newHTML = html\`\${dataObj.html}\`
127
+ } catch {
128
+ setShouldSetReactivity(false);
129
+ newHTML = html\`\${dataObj.html}\`
130
+ setShouldSetReactivity(true);
131
+ }
132
+
133
+ if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
134
+ document.head.remove(); // Don't try to diff the head – just re-run the scripts
135
+ render(newHTML, document.documentElement, false);
136
+ } else {
137
+ const hmrID = "${id}";
138
+ const hmrElems = Array.from(newHTML.childNodes);
139
+ const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
140
+ // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
141
+ hmrWheres.forEach((where, index) => {
142
+ if (index < hmrElems.length) {
143
+ render(hmrElems[index], where, false);
144
+ } else {
145
+ where.remove();
146
+ }
147
+ });
148
+ for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
149
+ if (hmrWheres.length) {
150
+ const template = document.createElement('template');
151
+ hmrElems[hmrWheres.length - 1].after(template);
152
+ render(hmrElems[rest], template, false);
153
+ template.remove();
154
+ } else {
155
+ render(hmrElems[rest], false, false)
156
+ }
157
+ }
158
+ }
159
+
160
+ if (dataObj.file === \`${src}/index.html\`) {
161
+ dispatchEvent(new Event("popstate"));
162
+ }
163
+ } else if (dataObj.file.endsWith(".css")) {
164
+ updateElem("link");
165
+ } else if (dataObj.file.endsWith(".js")) {
166
+ updateElem("script")
167
+ }
168
+
169
+ function updateElem(type) {
170
+ const hmrId = "${id}";
171
+ const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
172
+ const attr = type === "script" ? "src" : "href";
173
+ const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
174
+
175
+ if (elem) {
176
+ updateOne(type, attr, elem)
177
+ } else {
178
+ for(const e of $$(\`[data-hmr="\${hmrId}"] \${type}\`)) {
179
+ updateOne(type, attr, e);
180
+ }
181
+ }
182
+ }
183
+
184
+ function updateOne(type, attr, elem) {
185
+ const clone = document.createElement(type);
186
+ for (const key of elem.getAttributeNames()) {
187
+ clone.setAttribute(key, elem.getAttribute(key));
188
+ }
189
+ clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
190
+ render(clone, elem, false);
191
+ }
192
+ });
193
+ }
194
+ `;
195
+ }
package/logo.jpg ADDED
Binary file