html-bundle 5.5.2 → 6.0.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/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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "html-bundle",
3
- "version": "5.5.2",
3
+ "version": "6.0.1",
4
4
  "description": "A very simple bundler for HTML SFC",
5
5
  "bin": "./dist/bundle.mjs",
6
6
  "scripts": {
@@ -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",