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/src/utils.mts ADDED
@@ -0,0 +1,203 @@
1
+ import type { FastifyServerOptions } from "fastify";
2
+ import { copyFile, mkdir, readFile } from "fs/promises";
3
+ import path from "path";
4
+ import Fastify from "fastify";
5
+ import fastifyStatic from "fastify-static";
6
+ import postcssrc from "postcss-load-config";
7
+ import cssnano from "cssnano";
8
+ import { parse, parseFragment, serialize } from "parse5";
9
+ import {
10
+ createScript,
11
+ getTagName,
12
+ findElement,
13
+ appendChild,
14
+ } from "@web/parse5-utils";
15
+
16
+ export const bundleConfig = await getBundleConfig();
17
+
18
+ export function fileCopy(file: string) {
19
+ return copyFile(file, getBuildPath(file));
20
+ }
21
+
22
+ export function createDir(file: string) {
23
+ const buildPath = getBuildPath(file);
24
+ const dir = buildPath.split("/").slice(0, -1).join("/");
25
+ return mkdir(dir, { recursive: true });
26
+ }
27
+
28
+ export function getBuildPath(file: string) {
29
+ return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
30
+ }
31
+
32
+ const CONNECTIONS: Array<any> = []; // In order to send the HMR information
33
+ export let serverSentEvents:
34
+ | undefined
35
+ | (({ file, html }: { file: string; html?: string }) => void);
36
+ export async function createDefaultServer(isSecure: boolean) {
37
+ const fastify = Fastify(
38
+ isSecure
39
+ ? ({
40
+ http2: true,
41
+ https: {
42
+ key: await readFile(path.join(process.cwd(), "localhost-key.pem")),
43
+ cert: await readFile(path.join(process.cwd(), "localhost.pem")),
44
+ },
45
+ } as FastifyServerOptions)
46
+ : void 0
47
+ );
48
+ fastify.setNotFoundHandler(async (_req, reply) => {
49
+ const file = await readFile(
50
+ path.join(process.cwd(), bundleConfig.build, "/index.html"),
51
+ {
52
+ encoding: "utf-8",
53
+ }
54
+ );
55
+ reply.header("Content-Type", "text/html; charset=UTF-8");
56
+ return reply.send(addHMRCode(file, `${bundleConfig.src}/index.html`));
57
+ });
58
+ fastify.register(fastifyStatic, {
59
+ root: path.join(process.cwd(), bundleConfig.build),
60
+ });
61
+ fastify.get("/events", (_req, reply) => {
62
+ reply.raw.setHeader("Content-Type", "text/event-stream");
63
+ reply.raw.setHeader("Cache-Control", "no-cache");
64
+ !isSecure && reply.raw.setHeader("Connection", "keep-alive");
65
+
66
+ CONNECTIONS.push(reply.raw);
67
+
68
+ serverSentEvents = (data) =>
69
+ CONNECTIONS.forEach((rep) => {
70
+ rep.write(`data: ${JSON.stringify(data)}\n\n`);
71
+ });
72
+ });
73
+ return fastify;
74
+ }
75
+
76
+ export function getPostCSSConfig() {
77
+ try {
78
+ return postcssrc({});
79
+ } catch {
80
+ return { plugins: [cssnano], options: {}, file: "" };
81
+ }
82
+ }
83
+
84
+ async function getBundleConfig() {
85
+ const base = {
86
+ build: "build",
87
+ src: "src",
88
+ port: 5000,
89
+ esbuild: {},
90
+ "html-minifier-terser": {},
91
+ critical: {},
92
+ };
93
+
94
+ try {
95
+ const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
96
+ const config = await import(`file://${cfgPath}`);
97
+ return { ...base, ...config.default };
98
+ } catch {
99
+ return base;
100
+ }
101
+ }
102
+
103
+ const htmlIdMap = new Map();
104
+ export function addHMRCode(
105
+ html: string,
106
+ file: string,
107
+ ast?: ReturnType<typeof parse | typeof parseFragment>
108
+ ) {
109
+ if (!htmlIdMap.has(file)) {
110
+ htmlIdMap.set(file, randomText());
111
+ }
112
+
113
+ const script = createScript(
114
+ { type: "module" },
115
+ getHMRCode(file, htmlIdMap.get(file), bundleConfig.src)
116
+ );
117
+
118
+ let DOM;
119
+ if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
120
+ DOM = ast || parse(html);
121
+ const headNode = findElement(DOM, (e) => getTagName(e) === "head");
122
+ appendChild(headNode, script);
123
+ } else {
124
+ DOM = ast || parseFragment(html);
125
+ appendChild(DOM, script);
126
+ }
127
+
128
+ //@ts-ignore
129
+ DOM.childNodes.forEach((node) =>
130
+ node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) })
131
+ );
132
+
133
+ return serialize(DOM);
134
+ }
135
+
136
+ function randomText() {
137
+ return Math.random().toString(32).slice(2);
138
+ }
139
+
140
+ function getHMRCode(file: string, id: string, src: string) {
141
+ return `import { render, html, $, $$, setInsertDiffing } from "hydro-js";
142
+ if (!window.eventsource${id}) {
143
+ setInsertDiffing(true);
144
+ window.eventsource${id} = new EventSource("/events");
145
+ window.eventsource${id}.addEventListener("message", ({ data }) => {
146
+ const dataObj = JSON.parse(data);
147
+ const file = "${file}";
148
+
149
+ if (file === dataObj.file && "html" in dataObj) {
150
+ if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
151
+ document.head.remove(); // Don't try to diff the head – just re-run the scripts
152
+ render(html\`\${dataObj.html}\`, document.documentElement);
153
+ } else {
154
+ const hmrID = "${id}";
155
+ const newHTML = html\`\${dataObj.html}\`;
156
+ const hmrElems = Array.from(newHTML.childNodes);
157
+ const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
158
+ // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
159
+ hmrWheres.forEach((where, index) => {
160
+ if (index < hmrElems.length) {
161
+ render(hmrElems[index], where, false);
162
+ } else {
163
+ where.remove();
164
+ }
165
+ });
166
+ for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
167
+ if (hmrWheres.length) {
168
+ const template = document.createElement('template');
169
+ hmrElems[hmrWheres.length - 1].after(template);
170
+ render(hmrElems[rest], template, false);
171
+ template.remove();
172
+ } else {
173
+ render(hmrElems[rest], false, false)
174
+ }
175
+ }
176
+ }
177
+
178
+ setTimeout(() => dispatchEvent(new Event("popstate")));
179
+ } else if (dataObj.file.endsWith("css")) {
180
+ updateElem("link");
181
+ } else if (dataObj.file.endsWith("js")) {
182
+ updateElem("script")
183
+ }
184
+
185
+ function updateElem(type) {
186
+ const hmrId = "${id}";
187
+ const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
188
+ const attr = type === "script" ? "src" : "href";
189
+ const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
190
+
191
+ if (elem) {
192
+ const clone = document.createElement(type);
193
+ for (const key of elem.getAttributeNames()) {
194
+ clone.setAttribute(key, elem.getAttribute(key));
195
+ }
196
+ clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
197
+ render(clone, elem, false);
198
+ }
199
+ }
200
+ });
201
+ }
202
+ `;
203
+ }