html-bundle 6.1.8 → 6.2.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/README.md CHANGED
@@ -50,6 +50,17 @@ $ npm run build
50
50
  `--isCritical`: uses critical to extract and inline critical-path CSS to HTML.<br>
51
51
  `--handler`: path to your custom handler. Here, you can handle all non-supported files. You can get the filename via `process.argv[2]`.
52
52
 
53
+ ## import
54
+ It is also possible to start the server by importing the package. This could be useful, if you intend to add routes for local development.
55
+ ```js
56
+ import router from "html-bundle";
57
+
58
+ router.get("/test", (_req, reply) => {
59
+ return reply.send("hi");
60
+ });
61
+ ```
62
+
63
+
53
64
  ## Optional Config
54
65
 
55
66
  _The CLI flags can also be set by the config. Flags set by the CLI will override the config._
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import type { Router } from "express-serve-static-core";
3
+ import { type BuildOptions } from "esbuild";
4
+ import { type Options } from "beasties";
5
+ import { type Options as MinifyOptions } from "html-minifier-terser";
6
+ declare let router: Router | undefined;
7
+ export default router;
8
+ export type Config = {
9
+ build: string;
10
+ src: string;
11
+ port: number;
12
+ secure: boolean;
13
+ esbuild?: BuildOptions;
14
+ "html-minifier-terser"?: MinifyOptions;
15
+ critical?: Options;
16
+ deletePrev?: boolean;
17
+ isCritical?: boolean;
18
+ hmr?: boolean;
19
+ handler?: string;
20
+ host?: string;
21
+ key?: Buffer;
22
+ cert?: Buffer;
23
+ };
package/dist/bundle.mjs CHANGED
@@ -29,7 +29,7 @@ process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case oth
29
29
  let timer = performance.now();
30
30
  let { plugins, options, file: postcssFile } = await getPostCSSConfig();
31
31
  let CSSprocessor = postcss(plugins);
32
- let fastify;
32
+ let router;
33
33
  const inlineFiles = new Set();
34
34
  const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
35
35
  const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
@@ -79,8 +79,9 @@ async function build(files, firstRun = true) {
79
79
  }
80
80
  console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
81
81
  if (isHMR && firstRun) {
82
- fastify = await createDefaultServer(isSecure);
83
- await fastify.listen({ port: bundleConfig.port, host: bundleConfig.host });
82
+ const [dynamicRouter, server] = await createDefaultServer(isSecure);
83
+ router = dynamicRouter;
84
+ server.listen({ port: bundleConfig.port, host: bundleConfig.host });
84
85
  console.log(`💻 Server listening on http${isSecure ? "s" : ""}://${bundleConfig.host === "::" ? "localhost" : bundleConfig.host}:${bundleConfig.port} and is shared in the local network.`);
85
86
  console.log(`⌛ Waiting for file changes ...`);
86
87
  const chokidarOptions = { awaitWriteFinish: false };
@@ -289,7 +290,8 @@ async function minifyHTML(file, buildFile) {
289
290
  const type = script.attrs.find((a) => a.name === "type");
290
291
  if (!scriptTextNode?.value ||
291
292
  isReferencedScript ||
292
- type?.value === "importmap")
293
+ type?.value === "importmap" ||
294
+ type?.value === "application/ld+json")
293
295
  continue;
294
296
  // Use bundled file
295
297
  const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
@@ -368,3 +370,4 @@ catch (err) {
368
370
  console.error(err);
369
371
  process.exit(1);
370
372
  }
373
+ export default router;
@@ -0,0 +1,22 @@
1
+ import type { Config } from "./bundle.mjs";
2
+ import type { Router } from "express-serve-static-core";
3
+ import { type Server } from "http";
4
+ import { type Server as HTTPSServer } from "https";
5
+ import postcssrc from "postcss-load-config";
6
+ import cssnano from "cssnano";
7
+ import { parse, parseFragment } from "parse5";
8
+ export declare const bundleConfig: Config;
9
+ export declare function fileCopy(file: string): Promise<void>;
10
+ export declare function createDir(file: string): Promise<string | undefined>;
11
+ export declare function getBuildPath(file: string): string;
12
+ export declare let serverSentEvents: undefined | (({ file, html }: {
13
+ file: string;
14
+ html?: string;
15
+ }) => void);
16
+ export declare function createDefaultServer(isSecure: boolean): Promise<[Router, Server | HTTPSServer]>;
17
+ export declare function getPostCSSConfig(): Promise<postcssrc.Result | {
18
+ plugins: (typeof cssnano)[];
19
+ options: {};
20
+ file: string;
21
+ }>;
22
+ export declare function addHMRCode(html: string, file: string, ast?: ReturnType<typeof parse | typeof parseFragment>): string;
package/dist/utils.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { copyFile, mkdir, readFile } from "fs/promises";
2
2
  import path from "path";
3
- import Fastify from "fastify";
4
- import fastifyStatic from "@fastify/static";
3
+ import http from "http";
4
+ import https from "https";
5
+ import express from "express";
5
6
  import postcssrc from "postcss-load-config";
6
7
  import cssnano from "cssnano";
7
8
  import { parse, parseFragment, serialize } from "parse5";
@@ -21,32 +22,15 @@ export function getBuildPath(file) {
21
22
  const CONNECTIONS = []; // In order to send the HMR information
22
23
  export let serverSentEvents;
23
24
  export async function createDefaultServer(isSecure) {
24
- const fastify = Fastify(isSecure
25
- ? {
26
- http2: true,
27
- https: {
28
- key: bundleConfig.key ||
29
- (await readFile(path.join(process.cwd(), "localhost-key.pem"))),
30
- cert: bundleConfig.cert ||
31
- (await readFile(path.join(process.cwd(), "localhost.pem"))),
32
- },
33
- }
34
- : void 0);
35
- fastify.setNotFoundHandler(async (_req, reply) => {
36
- reply.type("text/html");
37
- const file = await readFile(path.join(process.cwd(), bundleConfig.build, "/index.html"), {
38
- encoding: "utf-8",
39
- });
40
- return reply.send(file);
41
- });
42
- fastify.register(fastifyStatic, {
43
- root: path.join(process.cwd(), bundleConfig.build),
44
- });
45
- fastify.get("/hmr", (_req, reply) => {
46
- reply.raw.setHeader("Content-Type", "text/event-stream");
47
- reply.raw.setHeader("Cache-Control", "no-cache");
48
- !isSecure && reply.raw.setHeader("Connection", "keep-alive");
49
- CONNECTIONS.push(reply.raw);
25
+ const router = express.Router();
26
+ const app = express();
27
+ app.use(router);
28
+ app.use(express.static(path.join(process.cwd(), bundleConfig.build)));
29
+ router.get("/hmr", (_req, reply) => {
30
+ reply.setHeader("Content-Type", "text/event-stream");
31
+ reply.setHeader("Cache-Control", "no-cache");
32
+ !isSecure && reply.setHeader("Connection", "keep-alive");
33
+ CONNECTIONS.push(reply);
50
34
  serverSentEvents = (data) => {
51
35
  if (/\.(jsx?|tsx?)$/.test(data.file)) {
52
36
  data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
@@ -56,7 +40,24 @@ export async function createDefaultServer(isSecure) {
56
40
  });
57
41
  };
58
42
  });
59
- return fastify;
43
+ app.use(async (_req, res) => {
44
+ res.setHeader("Content-Type", "text/html");
45
+ const file = await readFile(path.join(process.cwd(), bundleConfig.build, "index.html"), {
46
+ encoding: "utf-8",
47
+ });
48
+ res.send(file);
49
+ });
50
+ return [
51
+ router,
52
+ isSecure
53
+ ? https.createServer({
54
+ key: bundleConfig.key ||
55
+ (await readFile(path.join(process.cwd(), "localhost-key.pem"))),
56
+ cert: bundleConfig.cert ||
57
+ (await readFile(path.join(process.cwd(), "localhost.pem"))),
58
+ }, app)
59
+ : http.createServer({}, app),
60
+ ];
60
61
  }
61
62
  export async function getPostCSSConfig() {
62
63
  try {
package/package.json CHANGED
@@ -1,9 +1,15 @@
1
1
  {
2
2
  "name": "html-bundle",
3
- "version": "6.1.8",
3
+ "version": "6.2.1",
4
4
  "description": "A very simple bundler for HTML SFC",
5
5
  "bin": "./dist/bundle.mjs",
6
- "types": "./src/config.d.ts",
6
+ "main": "./dist/bundle.mjs",
7
+ "module": "./dist/bundle.mjs",
8
+ "exports": {
9
+ "import": "./dist/bundle.mjs",
10
+ "default": "./dist/bundle.mjs"
11
+ },
12
+ "types": "./dist/bundle.d.mts",
7
13
  "scripts": {
8
14
  "start": "tsc",
9
15
  "update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
@@ -16,15 +22,16 @@
16
22
  "esbuild",
17
23
  "hydro-js"
18
24
  ],
19
- "author": "Fabian Klingenberg <klingenberg.fabian@gmx.de> (https://klingenberg.netlify.app/)",
25
+ "author": "Fabian Klingenberg <klingenberg.fabian@gmx.de> (https://klingenberg.works/)",
20
26
  "license": "MIT",
21
27
  "devDependencies": {
22
28
  "@types/cssnano": "^5.1.3",
23
- "@types/glob": "^8.1.0",
29
+ "@types/express": "~5.0.2",
30
+ "@types/glob": "^9.0.0",
24
31
  "@types/html-minifier-terser": "^7.0.2",
25
32
  "@types/parse5": "^7.0.0",
26
33
  "@types/postcss-load-config": "^3.0.1",
27
- "typescript": "^5.6.3"
34
+ "typescript": "^5.8.3"
28
35
  },
29
36
  "repository": {
30
37
  "type": "git",
@@ -32,19 +39,18 @@
32
39
  },
33
40
  "bugs": "https://github.com/Krutsch/html-bundle/issues",
34
41
  "dependencies": {
35
- "@fastify/static": "^8.0.2",
36
42
  "@web/parse5-utils": "^2.1.0",
37
43
  "await-spawn": "^4.0.2",
38
- "beasties": "^0.1.0",
39
- "chokidar": "^4.0.1",
40
- "cssnano": "^7.0.6",
41
- "esbuild": "^0.24.0",
42
- "fastify": "^5.0.0",
43
- "glob": "^11.0.0",
44
+ "beasties": "^0.4.0",
45
+ "chokidar": "^5.0.0",
46
+ "cssnano": "^7.0.7",
47
+ "esbuild": "^0.27.0",
48
+ "express": "^5.1.0",
49
+ "glob": "^13.0.0",
44
50
  "html-minifier-terser": "^7.2.0",
45
- "hydro-js": "^1.5.22",
46
- "parse5": "^7.2.0",
47
- "postcss": "^8.4.47",
51
+ "hydro-js": "^1.8.8",
52
+ "parse5": "^8.0.0",
53
+ "postcss": "^8.5.4",
48
54
  "postcss-load-config": "^6.0.1"
49
55
  }
50
56
  }
package/src/bundle.mts CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  import type { Node, TextNode } from "@web/parse5-utils";
4
4
  import type { AcceptedPlugin } from "postcss";
5
+ import type { Router } from "express-serve-static-core";
5
6
  import { performance } from "perf_hooks";
6
7
  import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
7
8
  import { execFile } from "child_process";
@@ -9,9 +10,10 @@ import { promisify } from "util";
9
10
  import { sep } from "path";
10
11
  import { glob } from "glob";
11
12
  import postcss from "postcss";
12
- import esbuild from "esbuild";
13
- import Beasties from "beasties";
14
- import { minify } from "html-minifier-terser";
13
+ import express from "express";
14
+ import esbuild, { type BuildOptions } from "esbuild";
15
+ import Beasties, { type Options } from "beasties";
16
+ import { minify, type Options as MinifyOptions } from "html-minifier-terser";
15
17
  import { watch } from "chokidar";
16
18
  import { serialize, parse, parseFragment } from "parse5";
17
19
  import { getTagName, findElements } from "@web/parse5-utils";
@@ -44,7 +46,7 @@ process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case oth
44
46
  let timer = performance.now();
45
47
  let { plugins, options, file: postcssFile } = await getPostCSSConfig();
46
48
  let CSSprocessor = postcss(plugins as AcceptedPlugin[]);
47
- let fastify;
49
+ let router: Router | undefined;
48
50
  const inlineFiles = new Set<string>();
49
51
  const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
50
52
  const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
@@ -92,16 +94,17 @@ async function build(files: string[], firstRun = true) {
92
94
  }
93
95
 
94
96
  console.log(
95
- `🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`
97
+ `🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`,
96
98
  );
97
99
 
98
100
  if (isHMR && firstRun) {
99
- fastify = await createDefaultServer(isSecure);
100
- await fastify.listen({ port: bundleConfig.port, host: bundleConfig.host });
101
+ const [dynamicRouter, server] = await createDefaultServer(isSecure);
102
+ router = dynamicRouter;
103
+ server.listen({ port: bundleConfig.port, host: bundleConfig.host });
101
104
  console.log(
102
105
  `💻 Server listening on http${isSecure ? "s" : ""}://${
103
106
  bundleConfig.host === "::" ? "localhost" : bundleConfig.host
104
- }:${bundleConfig.port} and is shared in the local network.`
107
+ }:${bundleConfig.port} and is shared in the local network.`,
105
108
  );
106
109
 
107
110
  console.log(`⌛ Waiting for file changes ...`);
@@ -111,21 +114,21 @@ async function build(files: string[], firstRun = true) {
111
114
  const postCSSWatcher = watch(postcssFile, chokidarOptions);
112
115
  const tailwindCSSWatcher = watch(
113
116
  postcssFile.replace("postcss", "tailwind"),
114
- chokidarOptions
117
+ chokidarOptions,
115
118
  ); // Assuming that the file ext is the same
116
119
  const tsConfigWatcher = watch(
117
120
  postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json",
118
- chokidarOptions
121
+ chokidarOptions,
119
122
  );
120
123
 
121
124
  const cssFiles = files.filter((file) => file.endsWith(".css"));
122
125
  postCSSWatcher.on(
123
126
  "change",
124
- async () => await rebuildCSS(cssFiles, "postcss")
127
+ async () => await rebuildCSS(cssFiles, "postcss"),
125
128
  );
126
129
  tailwindCSSWatcher.on(
127
130
  "change",
128
- async () => await rebuildCSS(cssFiles, "tailwind")
131
+ async () => await rebuildCSS(cssFiles, "tailwind"),
129
132
  );
130
133
  tsConfigWatcher.on("change", async () => {
131
134
  timer = performance.now();
@@ -302,7 +305,7 @@ async function writeInlineScripts(file: string) {
302
305
  const script = scripts[index];
303
306
  const scriptTextNode = script.childNodes[0] as TextNode;
304
307
  const isReferencedScript = script.attrs.find(
305
- (a: { name: string }) => a.name === "src"
308
+ (a: { name: string }) => a.name === "src",
306
309
  );
307
310
  const type = script.attrs.find((a: { name: string }) => a.name === "type");
308
311
  const scriptContent = scriptTextNode?.value;
@@ -338,13 +341,14 @@ async function minifyHTML(file: string, buildFile: string) {
338
341
  const script = scripts[index];
339
342
  const scriptTextNode = script.childNodes[0] as TextNode;
340
343
  const isReferencedScript = script.attrs.find(
341
- (a: { name: string }) => a.name === "src"
344
+ (a: { name: string }) => a.name === "src",
342
345
  );
343
346
  const type = script.attrs.find((a: { name: string }) => a.name === "type");
344
347
  if (
345
348
  !scriptTextNode?.value ||
346
349
  isReferencedScript ||
347
- type?.value === "importmap"
350
+ type?.value === "importmap" ||
351
+ type?.value === "application/ld+json"
348
352
  )
349
353
  continue;
350
354
 
@@ -358,7 +362,7 @@ async function minifyHTML(file: string, buildFile: string) {
358
362
  await rm(buildInlineScript);
359
363
  scriptTextNode.value = scriptContent.replace(
360
364
  TEMPLATE_LITERAL_MINIFIER,
361
- " "
365
+ " ",
362
366
  );
363
367
  } catch {}
364
368
  }
@@ -431,3 +435,22 @@ try {
431
435
  console.error(err);
432
436
  process.exit(1);
433
437
  }
438
+
439
+ export default router;
440
+
441
+ export type Config = {
442
+ build: string;
443
+ src: string;
444
+ port: number;
445
+ secure: boolean;
446
+ esbuild?: BuildOptions;
447
+ "html-minifier-terser"?: MinifyOptions;
448
+ critical?: Options;
449
+ deletePrev?: boolean;
450
+ isCritical?: boolean;
451
+ hmr?: boolean;
452
+ handler?: string;
453
+ host?: string;
454
+ key?: Buffer;
455
+ cert?: Buffer;
456
+ };
package/src/utils.mts CHANGED
@@ -1,9 +1,11 @@
1
1
  import type { Node } from "@web/parse5-utils";
2
- import type { FastifyServerOptions } from "fastify";
2
+ import type { Config } from "./bundle.mjs";
3
+ import type { Router } from "express-serve-static-core";
3
4
  import { copyFile, mkdir, readFile } from "fs/promises";
4
5
  import path from "path";
5
- import Fastify from "fastify";
6
- import fastifyStatic from "@fastify/static";
6
+ import http, { type Server } from "http";
7
+ import https, { type Server as HTTPSServer } from "https";
8
+ import express from "express";
7
9
  import postcssrc from "postcss-load-config";
8
10
  import cssnano from "cssnano";
9
11
  import { parse, parseFragment, serialize } from "parse5";
@@ -13,7 +15,6 @@ import {
13
15
  findElement,
14
16
  appendChild,
15
17
  } from "@web/parse5-utils";
16
- import { Config } from "./config";
17
18
 
18
19
  export const bundleConfig = await getBundleConfig();
19
20
 
@@ -35,42 +36,19 @@ const CONNECTIONS: Array<any> = []; // In order to send the HMR information
35
36
  export let serverSentEvents:
36
37
  | undefined
37
38
  | (({ file, html }: { file: string; html?: string }) => void);
38
- export async function createDefaultServer(isSecure: boolean) {
39
- const fastify = Fastify(
40
- isSecure
41
- ? ({
42
- http2: true,
43
- https: {
44
- key:
45
- bundleConfig.key ||
46
- (await readFile(path.join(process.cwd(), "localhost-key.pem"))),
47
- cert:
48
- bundleConfig.cert ||
49
- (await readFile(path.join(process.cwd(), "localhost.pem"))),
50
- },
51
- } as FastifyServerOptions)
52
- : void 0
53
- );
54
- fastify.setNotFoundHandler(async (_req, reply) => {
55
- reply.type("text/html");
56
- const file = await readFile(
57
- path.join(process.cwd(), bundleConfig.build, "/index.html"),
58
- {
59
- encoding: "utf-8",
60
- }
61
- );
62
- return reply.send(file);
63
- });
64
- fastify.register(fastifyStatic, {
65
- root: path.join(process.cwd(), bundleConfig.build),
66
- });
67
- fastify.get("/hmr", (_req, reply) => {
68
- reply.raw.setHeader("Content-Type", "text/event-stream");
69
- reply.raw.setHeader("Cache-Control", "no-cache");
70
- !isSecure && reply.raw.setHeader("Connection", "keep-alive");
71
-
72
- CONNECTIONS.push(reply.raw);
39
+ export async function createDefaultServer(
40
+ isSecure: boolean
41
+ ): Promise<[Router, Server | HTTPSServer]> {
42
+ const router = express.Router();
43
+ const app = express();
44
+ app.use(router);
45
+ app.use(express.static(path.join(process.cwd(), bundleConfig.build)));
73
46
 
47
+ router.get("/hmr", (_req, reply) => {
48
+ reply.setHeader("Content-Type", "text/event-stream");
49
+ reply.setHeader("Cache-Control", "no-cache");
50
+ !isSecure && reply.setHeader("Connection", "keep-alive");
51
+ CONNECTIONS.push(reply);
74
52
  serverSentEvents = (data) => {
75
53
  if (/\.(jsx?|tsx?)$/.test(data.file)) {
76
54
  data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
@@ -80,7 +58,34 @@ export async function createDefaultServer(isSecure: boolean) {
80
58
  });
81
59
  };
82
60
  });
83
- return fastify;
61
+
62
+ app.use(async (_req, res) => {
63
+ res.setHeader("Content-Type", "text/html");
64
+ const file = await readFile(
65
+ path.join(process.cwd(), bundleConfig.build, "index.html"),
66
+ {
67
+ encoding: "utf-8",
68
+ }
69
+ );
70
+ res.send(file);
71
+ });
72
+
73
+ return [
74
+ router,
75
+ isSecure
76
+ ? https.createServer(
77
+ {
78
+ key:
79
+ bundleConfig.key ||
80
+ (await readFile(path.join(process.cwd(), "localhost-key.pem"))),
81
+ cert:
82
+ bundleConfig.cert ||
83
+ (await readFile(path.join(process.cwd(), "localhost.pem"))),
84
+ },
85
+ app
86
+ )
87
+ : http.createServer({}, app),
88
+ ];
84
89
  }
85
90
 
86
91
  export async function getPostCSSConfig() {
package/tsconfig.json CHANGED
@@ -6,6 +6,7 @@
6
6
  "outDir": "./dist",
7
7
  "rootDir": "./src",
8
8
  "strict": true,
9
+ "declaration": true,
9
10
  "skipLibCheck": true,
10
11
  "moduleResolution": "node",
11
12
  "esModuleInterop": true,
package/src/config.d.ts DELETED
@@ -1,16 +0,0 @@
1
- export type Config = {
2
- build: string;
3
- src: string;
4
- port: number;
5
- secure: boolean;
6
- esbuild?: BuildOptions;
7
- "html-minifier-terser"?: HTMLOptions;
8
- critical?: Options;
9
- deletePrev?: boolean;
10
- isCritical?: boolean;
11
- hmr?: boolean;
12
- handler?: string;
13
- host?: string;
14
- key?: Buffer;
15
- cert?: Buffer;
16
- };