astro-html-minifier-next 0.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/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+ ===========
3
+
4
+ Copyright (c) 2025 Jonas Geiler
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,6 @@
1
+ # astro-html-minifier-next
2
+
3
+ > Astro integration for [html-minifier-next](https://www.npmjs.com/package/html-minifier-next)
4
+
5
+ Work in progress - Not yet production ready and might introduce many breaking changes!!!
6
+ Please wait for the v1.0.0 release!
@@ -0,0 +1,4 @@
1
+ import type { AstroIntegration } from "astro";
2
+ import { type MinifierOptions as HTMLMinifierOptions } from "html-minifier-next";
3
+ export default function htmlMinifier(options: HTMLMinifierOptions): AstroIntegration;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,OAAO,CAAC;AAC9C,OAAO,EACN,KAAK,eAAe,IAAI,mBAAmB,EAE3C,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,OAAO,UAAU,YAAY,CACnC,OAAO,EAAE,mBAAmB,GAC1B,gBAAgB,CAqHlB"}
package/dist/index.js ADDED
@@ -0,0 +1,101 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { availableParallelism as getAvailableParallelism } from "node:os";
3
+ import { relative as getRelativePath } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { styleText } from "node:util";
6
+ import { minify as minifyHtml, } from "html-minifier-next";
7
+ export default function htmlMinifier(options) {
8
+ // API Reference: https://docs.astro.build/en/reference/integrations-reference/
9
+ return {
10
+ name: "astro-html-minifier-next",
11
+ hooks: {
12
+ "astro:build:done": async ({ logger, dir: distUrl, assets }) => {
13
+ logger.info(styleText(["bgGreen", "black"], " minifying html assets "));
14
+ const totalTimeStart = performance.now(); // --- TIMED BLOCK START ---
15
+ // TODO: Use workers?
16
+ const tasks = [];
17
+ const controller = new AbortController();
18
+ const signal = controller.signal;
19
+ const distPath = fileURLToPath(distUrl);
20
+ for (const assetUrls of assets.values()) {
21
+ for (const assetUrl of assetUrls) {
22
+ const assetPath = fileURLToPath(assetUrl);
23
+ if (assetPath.toLowerCase().endsWith(".html")) {
24
+ tasks.push(async () => {
25
+ const timeStart = performance.now(); // --- TIMED BLOCK START ---
26
+ const html = await readFile(assetPath, {
27
+ encoding: "utf8",
28
+ signal,
29
+ });
30
+ const minifiedHtml = await minifyHtml(html, options);
31
+ const htmlSize = Buffer.byteLength(html, "utf8");
32
+ const minifiedHtmlSize = Buffer.byteLength(minifiedHtml, "utf8");
33
+ if (minifiedHtmlSize >= htmlSize) {
34
+ // No actual file size savings, so we skip writing the file or logging anything.
35
+ return;
36
+ }
37
+ await writeFile(assetPath, minifiedHtml, {
38
+ encoding: "utf8",
39
+ signal,
40
+ });
41
+ const timeEnd = performance.now(); // --- TIMED BLOCK END ---
42
+ // Log a nice summary of the minification savings and the time it took.
43
+ const relativeAssetPath = getRelativePath(distPath, assetPath);
44
+ const savings = htmlSize - minifiedHtmlSize;
45
+ const savingsStr = savings < 1000
46
+ ? `${savings}B`
47
+ : savings < 1000000
48
+ ? `${(savings / 1000).toFixed(1)}kB`
49
+ : `${(savings / 1000000).toFixed(2)}MB`;
50
+ const time = timeEnd - timeStart;
51
+ const timeStr = time < 1000
52
+ ? `${Math.round(time)}ms`
53
+ : `${(time / 1000).toFixed(2)}s`;
54
+ logger.info(styleText("green", " ▶") +
55
+ ` /${relativeAssetPath} ` +
56
+ styleText("dim", `(-${savingsStr}) (+${timeStr})`));
57
+ });
58
+ }
59
+ }
60
+ }
61
+ // We retrieve the available parallelism from the OS, even if we don't actually run the tasks in different threads.
62
+ // It's just used as an indicator of machine capabilities and usually a good value for batching.
63
+ const maxExecutingTasksSize = getAvailableParallelism();
64
+ // This holds the current batch of promises that are waiting to fulfill.
65
+ const executingTasks = new Set();
66
+ // Batch the tasks to avoid minifying too many files at once, which could lead to memory and performance issues.
67
+ for (const task of tasks) {
68
+ const taskPromise = task()
69
+ .then(() => {
70
+ executingTasks.delete(taskPromise);
71
+ })
72
+ .catch((e) => {
73
+ if (!signal.aborted) {
74
+ controller.abort(e);
75
+ }
76
+ throw e;
77
+ });
78
+ executingTasks.add(taskPromise);
79
+ if (executingTasks.size >= maxExecutingTasksSize) {
80
+ // If the amount of executing tasks reaches the limit, we wait until the one of them finishes,
81
+ // and therefore gets deleted from the list, before continuing with the next task.
82
+ await Promise.race(executingTasks);
83
+ }
84
+ if (signal.aborted) {
85
+ throw signal.reason;
86
+ }
87
+ }
88
+ // Wait for any remaining tasks to finish.
89
+ await Promise.all(executingTasks);
90
+ const totalTimeEnd = performance.now(); // --- TIMED BLOCK END ---
91
+ // Log how long processing all assets took.
92
+ const totalTime = totalTimeEnd - totalTimeStart;
93
+ const totalTimeStr = totalTime < 1000
94
+ ? `${Math.round(totalTime)}ms`
95
+ : `${(totalTime / 1000).toFixed(2)}s`;
96
+ logger.info(styleText("green", `✓ Completed in ${totalTimeStr}.`));
97
+ },
98
+ },
99
+ };
100
+ }
101
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,oBAAoB,IAAI,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,QAAQ,IAAI,eAAe,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAEN,MAAM,IAAI,UAAU,GACpB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,OAAO,UAAU,YAAY,CACnC,OAA4B;IAE5B,+EAA+E;IAC/E,OAAO;QACN,IAAI,EAAE,0BAA0B;QAChC,KAAK,EAAE;YACN,kBAAkB,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE;gBAC9D,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,yBAAyB,CAAC,CAAC,CAAC;gBAExE,MAAM,cAAc,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,CAAC,4BAA4B;gBAEtE,qBAAqB;gBACrB,MAAM,KAAK,GAA4B,EAAE,CAAC;gBAC1C,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;gBACzC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;gBACjC,MAAM,QAAQ,GAAG,a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AAM,CAAC,CAAC;oBACT,CAAC,CAAC,CAAC;oBAEJ,cAAc,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;oBAEhC,IAAI,cAAc,CAAC,IAAI,IAAI,qBAAqB,EAAE,CAAC;wBAClD,8FAA8F;wBAC9F,kFAAkF;wBAClF,MAAM,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;oBACpC,CAAC;oBAED,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;wBACpB,MAAM,MAAM,CAAC,MAAM,CAAC;oBACrB,CAAC;gBACF,CAAC;gBAED,0CAA0C;gBAC1C,MAAM,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;gBAElC,MAAM,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,CAAC,0BAA0B;gBAElE,2CAA2C;gBAC3C,MAAM,SAAS,GAAG,YAAY,GAAG,cAAc,CAAC;gBAChD,MAAM,YAAY,GACjB,SAAS,GAAG,IAAI;oBACf,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI;oBAC9B,CAAC,CAAC,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,kBAAkB,YAAY,GAAG,CAAC,CAAC,CAAC;YACpE,CAAC;SACD;KACD,CAAC;AACH,CAAC"}
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "astro-html-minifier-next",
3
+ "version": "0.0.0",
4
+ "description": "Astro integration for html-minifier-next",
5
+ "homepage": "https://github.com/jonasgeiler/astro-html-minifier-next#readme",
6
+ "bugs": "https://github.com/jonasgeiler/astro-html-minifier-next/issues",
7
+ "license": "MIT",
8
+ "author": "Jonas Geiler <npm@jonasgeiler.com> (https://jonasgeiler.com)",
9
+ "funding": "https://github.com/sponsors/jonasgeiler",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/jonasgeiler/astro-html-minifier-next.git"
13
+ },
14
+ "engines": {
15
+ "node": "^20.12.0 || >=21.7.0"
16
+ },
17
+ "peerDependencies": {
18
+ "astro": "^5.0.0"
19
+ },
20
+ "dependencies": {
21
+ "html-minifier-next": "^2.1.8"
22
+ },
23
+ "devDependencies": {
24
+ "@biomejs/biome": "2.2.6",
25
+ "@types/html-minifier-next": "2.1.0",
26
+ "@types/node": "24.7.2",
27
+ "astro": "5.14.5",
28
+ "typescript": "5.9.3"
29
+ },
30
+ "type": "module",
31
+ "files": [
32
+ "src",
33
+ "dist"
34
+ ],
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "default": "./dist/index.js"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "scripts": {
43
+ "dev": "tsc --watch",
44
+ "check": "biome check",
45
+ "fix": "biome check --fix",
46
+ "unsafe-fix": "biome check --unsafe --fix",
47
+ "build": "tsc",
48
+ "version": "node --input-type=module --eval=\"import f from 'node:fs/promises';const j=JSON.parse(await f.readFile('jsr.json','utf8'));j.version=process.env.npm_package_version||j.version;await f.writeFile('jsr.json',JSON.stringify(j,null,2)+'\\n','utf8');console.log('Updated jsr.json for version',j.version)\" && git add jsr.json"
49
+ }
50
+ }
package/src/index.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { availableParallelism as getAvailableParallelism } from "node:os";
3
+ import { relative as getRelativePath } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { styleText } from "node:util";
6
+ import type { AstroIntegration } from "astro";
7
+ import {
8
+ type MinifierOptions as HTMLMinifierOptions,
9
+ minify as minifyHtml,
10
+ } from "html-minifier-next";
11
+
12
+ export default function htmlMinifier(
13
+ options: HTMLMinifierOptions,
14
+ ): AstroIntegration {
15
+ // API Reference: https://docs.astro.build/en/reference/integrations-reference/
16
+ return {
17
+ name: "astro-html-minifier-next",
18
+ hooks: {
19
+ "astro:build:done": async ({ logger, dir: distUrl, assets }) => {
20
+ logger.info(styleText(["bgGreen", "black"], " minifying html assets "));
21
+
22
+ const totalTimeStart = performance.now(); // --- TIMED BLOCK START ---
23
+
24
+ // TODO: Use workers?
25
+ const tasks: (() => Promise<void>)[] = [];
26
+ const controller = new AbortController();
27
+ const signal = controller.signal;
28
+ const distPath = fileURLToPath(distUrl);
29
+ for (const assetUrls of assets.values()) {
30
+ for (const assetUrl of assetUrls) {
31
+ const assetPath = fileURLToPath(assetUrl);
32
+ if (assetPath.toLowerCase().endsWith(".html")) {
33
+ tasks.push(async () => {
34
+ const timeStart = performance.now(); // --- TIMED BLOCK START ---
35
+
36
+ const html = await readFile(assetPath, {
37
+ encoding: "utf8",
38
+ signal,
39
+ });
40
+ const minifiedHtml = await minifyHtml(html, options);
41
+
42
+ const htmlSize = Buffer.byteLength(html, "utf8");
43
+ const minifiedHtmlSize = Buffer.byteLength(
44
+ minifiedHtml,
45
+ "utf8",
46
+ );
47
+ if (minifiedHtmlSize >= htmlSize) {
48
+ // No actual file size savings, so we skip writing the file or logging anything.
49
+ return;
50
+ }
51
+
52
+ await writeFile(assetPath, minifiedHtml, {
53
+ encoding: "utf8",
54
+ signal,
55
+ });
56
+
57
+ const timeEnd = performance.now(); // --- TIMED BLOCK END ---
58
+
59
+ // Log a nice summary of the minification savings and the time it took.
60
+ const relativeAssetPath = getRelativePath(distPath, assetPath);
61
+ const savings = htmlSize - minifiedHtmlSize;
62
+ const savingsStr =
63
+ savings < 1000
64
+ ? `${savings}B`
65
+ : savings < 1000000
66
+ ? `${(savings / 1000).toFixed(1)}kB`
67
+ : `${(savings / 1000000).toFixed(2)}MB`;
68
+ const time = timeEnd - timeStart;
69
+ const timeStr =
70
+ time < 1000
71
+ ? `${Math.round(time)}ms`
72
+ : `${(time / 1000).toFixed(2)}s`;
73
+ logger.info(
74
+ styleText("green", " ▶") +
75
+ ` /${relativeAssetPath} ` +
76
+ styleText("dim", `(-${savingsStr}) (+${timeStr})`),
77
+ );
78
+ });
79
+ }
80
+ }
81
+ }
82
+
83
+ // We retrieve the available parallelism from the OS, even if we don't actually run the tasks in different threads.
84
+ // It's just used as an indicator of machine capabilities and usually a good value for batching.
85
+ const maxExecutingTasksSize = getAvailableParallelism();
86
+
87
+ // This holds the current batch of promises that are waiting to fulfill.
88
+ const executingTasks = new Set<Promise<void>>();
89
+
90
+ // Batch the tasks to avoid minifying too many files at once, which could lead to memory and performance issues.
91
+ for (const task of tasks) {
92
+ const taskPromise = task()
93
+ .then(() => {
94
+ executingTasks.delete(taskPromise);
95
+ })
96
+ .catch((e) => {
97
+ if (!signal.aborted) {
98
+ controller.abort(e);
99
+ }
100
+ throw e;
101
+ });
102
+
103
+ executingTasks.add(taskPromise);
104
+
105
+ if (executingTasks.size >= maxExecutingTasksSize) {
106
+ // If the amount of executing tasks reaches the limit, we wait until the one of them finishes,
107
+ // and therefore gets deleted from the list, before continuing with the next task.
108
+ await Promise.race(executingTasks);
109
+ }
110
+
111
+ if (signal.aborted) {
112
+ throw signal.reason;
113
+ }
114
+ }
115
+
116
+ // Wait for any remaining tasks to finish.
117
+ await Promise.all(executingTasks);
118
+
119
+ const totalTimeEnd = performance.now(); // --- TIMED BLOCK END ---
120
+
121
+ // Log how long processing all assets took.
122
+ const totalTime = totalTimeEnd - totalTimeStart;
123
+ const totalTimeStr =
124
+ totalTime < 1000
125
+ ? `${Math.round(totalTime)}ms`
126
+ : `${(totalTime / 1000).toFixed(2)}s`;
127
+ logger.info(styleText("green", `✓ Completed in ${totalTimeStr}.`));
128
+ },
129
+ },
130
+ };
131
+ }