@ohos-ports/html-minifier-next 8.4.2-beta.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.txt +23 -0
- package/README.md +776 -0
- package/cli.js +1209 -0
- package/dist/types/htmlminifier.d.ts +556 -0
- package/dist/types/htmlminifier.d.ts.map +1 -0
- package/dist/types/htmlparser.d.ts +25 -0
- package/dist/types/htmlparser.d.ts.map +1 -0
- package/dist/types/lib/attributes.d.ts +155 -0
- package/dist/types/lib/attributes.d.ts.map +1 -0
- package/dist/types/lib/constants.d.ts +110 -0
- package/dist/types/lib/constants.d.ts.map +1 -0
- package/dist/types/lib/content.d.ts +51 -0
- package/dist/types/lib/content.d.ts.map +1 -0
- package/dist/types/lib/elements.d.ts +57 -0
- package/dist/types/lib/elements.d.ts.map +1 -0
- package/dist/types/lib/fragments.d.ts +46 -0
- package/dist/types/lib/fragments.d.ts.map +1 -0
- package/dist/types/lib/option-definitions.d.ts +33 -0
- package/dist/types/lib/option-definitions.d.ts.map +1 -0
- package/dist/types/lib/options.d.ts +120 -0
- package/dist/types/lib/options.d.ts.map +1 -0
- package/dist/types/lib/unused-css.d.ts +46 -0
- package/dist/types/lib/unused-css.d.ts.map +1 -0
- package/dist/types/lib/urls.d.ts +15 -0
- package/dist/types/lib/urls.d.ts.map +1 -0
- package/dist/types/lib/utils.d.ts +102 -0
- package/dist/types/lib/utils.d.ts.map +1 -0
- package/dist/types/lib/whitespace.d.ts +45 -0
- package/dist/types/lib/whitespace.d.ts.map +1 -0
- package/dist/types/presets.d.ts +49 -0
- package/dist/types/presets.d.ts.map +1 -0
- package/dist/types/tokenchain.d.ts +26 -0
- package/dist/types/tokenchain.d.ts.map +1 -0
- package/html-minifier-next.schema.json +306 -0
- package/package.json +100 -0
- package/src/htmlminifier.js +2294 -0
- package/src/htmlparser.js +1069 -0
- package/src/lib/attributes.js +928 -0
- package/src/lib/constants.js +285 -0
- package/src/lib/content.js +190 -0
- package/src/lib/elements.js +274 -0
- package/src/lib/file-pool.js +177 -0
- package/src/lib/fragments.js +274 -0
- package/src/lib/option-definitions.js +231 -0
- package/src/lib/options.js +730 -0
- package/src/lib/unused-css.js +379 -0
- package/src/lib/urls.js +155 -0
- package/src/lib/utils.js +861 -0
- package/src/lib/whitespace.js +321 -0
- package/src/presets.js +57 -0
- package/src/tokenchain.js +123 -0
package/cli.js
ADDED
|
@@ -0,0 +1,1209 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* html-minifier-next CLI tool
|
|
5
|
+
*
|
|
6
|
+
* MIT License
|
|
7
|
+
*
|
|
8
|
+
* Copyright 2014–2016 Zoltan Frombach
|
|
9
|
+
* Copyright Juriy “kangax” Zaytsev
|
|
10
|
+
* Copyright 2025 Jens Oliver Meiert
|
|
11
|
+
*
|
|
12
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
13
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
14
|
+
* the Software without restriction, including without limitation the rights to
|
|
15
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
16
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
17
|
+
* subject to the following conditions:
|
|
18
|
+
*
|
|
19
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
* copies or substantial portions of the Software.
|
|
21
|
+
*
|
|
22
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
24
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
25
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
26
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
27
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
28
|
+
*
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import fs from 'fs';
|
|
32
|
+
import path from 'path';
|
|
33
|
+
import { pathToFileURL } from 'url';
|
|
34
|
+
import os from 'os';
|
|
35
|
+
import readline from 'readline';
|
|
36
|
+
import { Command, Option } from 'commander';
|
|
37
|
+
|
|
38
|
+
/** @param {string} str */
|
|
39
|
+
const camelCase = (str) => paramCase(str).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
40
|
+
|
|
41
|
+
// Commander derives its internal option key by applying paramCase then camelCase to the flag name,
|
|
42
|
+
// stripping a leading `no-` first for negated flags (e.g., `--no-foo-bar` → `fooBar`);
|
|
43
|
+
// because option definition keys may differ from the result of that round-trip (e.g.,
|
|
44
|
+
// `minifyURLs` → Commander key `minifyUrls`, `noNewlinesBeforeTagClose` → `newlinesBeforeTagClose`),
|
|
45
|
+
// `commanderOptionKey` uses the same paramCase + camelCase path to compute the key Commander will use
|
|
46
|
+
/** @param {string} key */
|
|
47
|
+
const commanderOptionKey = (key) => {
|
|
48
|
+
const pc = paramCase(key);
|
|
49
|
+
return pc.startsWith('no-') ? camelCase(pc.slice(3)) : camelCase(pc);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Lazy-load HMN to reduce CLI cold-start overhead
|
|
53
|
+
import { getPreset, getPresetNames } from './src/presets.js';
|
|
54
|
+
import { paramCase, parseRegExp } from './src/lib/utils.js';
|
|
55
|
+
import { optionDefinitions } from './src/lib/option-definitions.js';
|
|
56
|
+
|
|
57
|
+
const pkg = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
|
|
58
|
+
|
|
59
|
+
const EXTENSIONS_DEFAULT = ['html', 'htm', 'shtml', 'shtm'];
|
|
60
|
+
const EXTENSIONS_NON_HTML = new Set(['css', 'js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'svg']);
|
|
61
|
+
|
|
62
|
+
const MARK_ERROR = process.stderr.isTTY ? '\x1b[31m' : '';
|
|
63
|
+
const MARK_SUCCESS = process.stderr.isTTY ? '\x1b[32m' : '';
|
|
64
|
+
const MARK_WARNING = process.stderr.isTTY ? '\x1b[33m' : '';
|
|
65
|
+
const MARK_RESET = process.stderr.isTTY ? '\x1b[0m' : '';
|
|
66
|
+
|
|
67
|
+
const program = new Command();
|
|
68
|
+
program.name(pkg.name);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {string} message
|
|
72
|
+
* @returns {never}
|
|
73
|
+
*/
|
|
74
|
+
function fatal(message) {
|
|
75
|
+
console.error(`${MARK_ERROR}${message}${MARK_RESET}`);
|
|
76
|
+
process.exit(1);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// `catch` bindings are `unknown`, and throw values need not be `Error`s
|
|
80
|
+
/** @param {unknown} err */
|
|
81
|
+
const errorMessage = (err) => err instanceof Error ? err.message : String(err);
|
|
82
|
+
|
|
83
|
+
// Handle broken pipe (e.g., when piping to `head`)
|
|
84
|
+
process.stdout.on('error', (/** @type {NodeJS.ErrnoException} */ err) => {
|
|
85
|
+
if (err && err.code === 'EPIPE') {
|
|
86
|
+
process.exit(0);
|
|
87
|
+
}
|
|
88
|
+
fatal('STDOUT error\n' + (err && err.message ? err.message : String(err)));
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* JSON does not support regexes, so, e.g., `JSON.parse()` will not create
|
|
93
|
+
* a RegExp from the JSON value `[ "/matchString/" ]`, which is
|
|
94
|
+
* technically just an array containing a string that begins and end with
|
|
95
|
+
* a forward slash. To get a RegExp from a JSON string, it must be
|
|
96
|
+
* constructed explicitly in JavaScript.
|
|
97
|
+
*
|
|
98
|
+
* The likelihood of actually wanting to match text that is enclosed in
|
|
99
|
+
* forward slashes is probably quite rare, so if forward slashes were
|
|
100
|
+
* included in an argument that requires a regex, the user most likely
|
|
101
|
+
* thought they were part of the syntax for specifying a regex.
|
|
102
|
+
*
|
|
103
|
+
* In the unlikely case that forward slashes are indeed desired in the
|
|
104
|
+
* search string, the user would need to enclose the expression in a
|
|
105
|
+
* second set of slashes:
|
|
106
|
+
*
|
|
107
|
+
* --customAttrSurround "[\"//matchString//\"]"
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
/** @param {string} value */
|
|
111
|
+
function parseJSON(value) {
|
|
112
|
+
if (value) {
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(value);
|
|
115
|
+
} catch {
|
|
116
|
+
if (/^\s*[{[]/.test(value)) {
|
|
117
|
+
fatal('Could not parse JSON value `' + value + '`');
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** @param {string} value */
|
|
125
|
+
function parseJSONArray(value) {
|
|
126
|
+
if (!value) return undefined;
|
|
127
|
+
const parsed = parseJSON(value);
|
|
128
|
+
return Array.isArray(parsed) ? parsed : [parsed];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @param {string} value */
|
|
132
|
+
function parseJSONRegExpArray(value) {
|
|
133
|
+
const values = parseJSONArray(value);
|
|
134
|
+
return values && values.map(parseRegExp);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @param {string} value */
|
|
138
|
+
const parseString = value => value;
|
|
139
|
+
|
|
140
|
+
/** @param {string} optionName */
|
|
141
|
+
const parseValidInt = (optionName) => (/** @type {string} */ value) => {
|
|
142
|
+
const s = String(value).trim();
|
|
143
|
+
// Accept only non-negative whole integers
|
|
144
|
+
if (!/^\d+$/.test(s)) {
|
|
145
|
+
fatal(`Invalid number for \`--${paramCase(optionName)}: "${value}"\``);
|
|
146
|
+
}
|
|
147
|
+
const num = Number(s);
|
|
148
|
+
return num;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
// Map option types to CLI parsers—`int` is resolved by `getParser`, as its
|
|
152
|
+
// parser closes over the option name for error messages
|
|
153
|
+
/** @type {Record<string, (value: string) => any>} */
|
|
154
|
+
const typeParsers = {
|
|
155
|
+
regexp: parseRegExp,
|
|
156
|
+
regexpArray: parseJSONRegExpArray,
|
|
157
|
+
json: parseJSON,
|
|
158
|
+
jsonObject: parseJSON,
|
|
159
|
+
jsonArray: parseJSONArray,
|
|
160
|
+
string: parseString
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* @param {string} key Option definition key, for the `int` parser’s error messages
|
|
165
|
+
* @param {string} type Option definition type
|
|
166
|
+
* @returns {(value: string) => any}
|
|
167
|
+
*/
|
|
168
|
+
function getParser(key, type) {
|
|
169
|
+
const parser = type === 'int' ? parseValidInt(key) : typeParsers[type];
|
|
170
|
+
if (!parser) {
|
|
171
|
+
fatal(`No CLI parser for option \`${key}\` (type \`${type}\`)—add the type to \`typeParsers\` in cli.js`);
|
|
172
|
+
}
|
|
173
|
+
return parser;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Configure command-line flags from shared option definitions
|
|
177
|
+
const mainOptionKeys = Object.keys(optionDefinitions);
|
|
178
|
+
Object.entries(optionDefinitions).forEach(function ([key, { description, descriptionAffirmative, type }]) {
|
|
179
|
+
const flag = paramCase(key);
|
|
180
|
+
if (type === 'invertedBoolean') {
|
|
181
|
+
// The positive form (to re-enable after a preset/config disables it) is hidden from
|
|
182
|
+
// help—the footer note covers the convention; the negative form is the primary use case
|
|
183
|
+
program.addOption(new Option('--' + flag, descriptionAffirmative ?? 'Enable --' + flag).hideHelp());
|
|
184
|
+
program.option('--no-' + flag, description);
|
|
185
|
+
} else if (type === 'boolean') {
|
|
186
|
+
program.option('--' + flag, description);
|
|
187
|
+
// The negation form is hidden from help—the footer note covers the convention;
|
|
188
|
+
// skip options whose flag already starts with `no-` (currently only
|
|
189
|
+
// `noNewlinesBeforeTagClose`), as `--no-no-X` is not usable
|
|
190
|
+
if (!flag.startsWith('no-')) {
|
|
191
|
+
program.addOption(new Option('--no-' + flag, 'Disable --' + flag).hideHelp());
|
|
192
|
+
}
|
|
193
|
+
} else {
|
|
194
|
+
const cliFlag = '--' + flag + (type === 'json' || type === 'jsonObject' ? ' [value]' : ' <value>');
|
|
195
|
+
program.option(cliFlag, description, getParser(key, type));
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
program.option('-i --input <file>', 'Specify input file (alternative to positional argument; pair with `--output` for output)');
|
|
199
|
+
program.option('-o --output <file>', 'Specify output file (reads from `--input` file argument or STDIN; outputs to STDOUT if not specified)');
|
|
200
|
+
program.option('-v --verbose', 'Show detailed processing information (active options, worker thread count, file statistics, and minifier warnings)');
|
|
201
|
+
program.option('-d --dry', 'Dry run: Process and report statistics without writing output');
|
|
202
|
+
program.addHelpText('after', '\nBoolean options support a `--no-<flag>` form to disable them, overriding a preset or config file (e.g., `--preset=comprehensive --no-collapse-whitespace`).');
|
|
203
|
+
|
|
204
|
+
// Lazy import wrapper for HMN
|
|
205
|
+
/** @type {Promise<typeof import('./src/htmlminifier.js').minify> | undefined} */
|
|
206
|
+
let minifyFnPromise;
|
|
207
|
+
async function getMinify() {
|
|
208
|
+
if (!minifyFnPromise) {
|
|
209
|
+
minifyFnPromise = import('./src/htmlminifier.js').then(m => m.minify);
|
|
210
|
+
}
|
|
211
|
+
return minifyFnPromise;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** @param {string} file */
|
|
215
|
+
function readFile(file) {
|
|
216
|
+
try {
|
|
217
|
+
return fs.readFileSync(file, { encoding: 'utf8' });
|
|
218
|
+
} catch (err) {
|
|
219
|
+
fatal('Cannot read ' + file + '\n' + errorMessage(err));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Load config from a file path. Extensions .json, .js, and .mjs are handled
|
|
225
|
+
* directly; for unknown extensions, JSON is tried first, then module import.
|
|
226
|
+
* @param {string} configPath - Path to config file
|
|
227
|
+
* @returns {Promise<Record<string, any>>} Loaded config object
|
|
228
|
+
*/
|
|
229
|
+
async function loadConfigFromPath(configPath) {
|
|
230
|
+
const abs = path.resolve(configPath);
|
|
231
|
+
const ext = path.extname(configPath).toLowerCase();
|
|
232
|
+
|
|
233
|
+
if (ext === '.json') {
|
|
234
|
+
try { return JSON.parse(readFile(abs).replace(/^\uFEFF/, '')); }
|
|
235
|
+
catch (err) { fatal(`Cannot parse config file as JSON: ${errorMessage(err)}`); }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (ext === '.js' || ext === '.mjs') {
|
|
239
|
+
// `import()` handles both ESM and CJS .js files—Node resolves the type via the
|
|
240
|
+
// nearest package.json `type` field, same as it does for regular module loading
|
|
241
|
+
try { const mod = await import(pathToFileURL(abs).href); return 'default' in mod ? mod.default : mod; }
|
|
242
|
+
catch (err) { fatal(`Cannot load config file: ${errorMessage(err)}`); }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Unknown extension: Try JSON, then module import
|
|
246
|
+
/** @type {unknown} */
|
|
247
|
+
let jsonErr;
|
|
248
|
+
try { return JSON.parse(readFile(abs).replace(/^\uFEFF/, '')); }
|
|
249
|
+
catch (err) { jsonErr = err; }
|
|
250
|
+
|
|
251
|
+
try { const mod = await import(pathToFileURL(abs).href); return 'default' in mod ? mod.default : mod; }
|
|
252
|
+
catch (esmErr) {
|
|
253
|
+
fatal(`Cannot read the specified config file.\nAs JSON: ${errorMessage(jsonErr)}\nAs module: ${errorMessage(esmErr)}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Config keys the CLI handles itself, beyond the options in `optionDefinitions`
|
|
258
|
+
const CONFIG_KEYS_EXTRA = new Set(['$schema', 'preset', 'fileExt', 'ignoreDir']);
|
|
259
|
+
|
|
260
|
+
// Default config files, looked up in the working directory in this order when
|
|
261
|
+
// `--config-file` isn’t specified
|
|
262
|
+
const CONFIG_FILES_DEFAULT = ['html-minifier-next.config.json', 'htmlminifier.config.json'];
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Normalize and validate config object by applying parsers and transforming values.
|
|
266
|
+
* @param {Record<string, any>} config - Raw config object
|
|
267
|
+
* @returns {Record<string, any>} Normalized config object
|
|
268
|
+
*/
|
|
269
|
+
function normalizeConfig(config) {
|
|
270
|
+
/** @type {Record<string, any>} */
|
|
271
|
+
const normalized = { ...config };
|
|
272
|
+
|
|
273
|
+
// Warn about unrecognized config keys—catches typos as well as options removed in earlier versions
|
|
274
|
+
Object.keys(normalized).forEach(function (key) {
|
|
275
|
+
if (!Object.hasOwn(optionDefinitions, key) && !CONFIG_KEYS_EXTRA.has(key)) {
|
|
276
|
+
console.error(`Ignoring unknown or deprecated config option \`${key}\` (see \`--help\` or README for available options)`);
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
// Apply parsers to main options
|
|
281
|
+
Object.entries(optionDefinitions).forEach(function ([key, { type }]) {
|
|
282
|
+
if (key in normalized) {
|
|
283
|
+
if (type !== 'boolean' && type !== 'invertedBoolean') {
|
|
284
|
+
const value = normalized[key];
|
|
285
|
+
normalized[key] = getParser(key, type)(typeof value === 'string' ? value : JSON.stringify(value));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
// Handle `fileExt` in config file
|
|
291
|
+
if ('fileExt' in normalized) {
|
|
292
|
+
// Support both string (`html,htm`) and array (`["html", "htm"]`) formats
|
|
293
|
+
if (Array.isArray(normalized.fileExt)) {
|
|
294
|
+
normalized.fileExt = normalized.fileExt.join(',');
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Handle `ignoreDir` in config file
|
|
299
|
+
if ('ignoreDir' in normalized) {
|
|
300
|
+
// Support both string (`libs,vendor`) and array (`["libs", "vendor"]`) formats
|
|
301
|
+
if (Array.isArray(normalized.ignoreDir)) {
|
|
302
|
+
normalized.ignoreDir = normalized.ignoreDir.join(',');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
return normalized;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** @type {Record<string, any>} */
|
|
310
|
+
let config = {};
|
|
311
|
+
program.option('-z, --zero', 'Minify all HTML files in the current folder and its subfolders in place (except node_modules), using comprehensive settings (standalone—flag is ignored when combined with other options)');
|
|
312
|
+
program.option('-I --input-dir <dir>', 'Specify an input directory');
|
|
313
|
+
program.option('-X --ignore-dir <patterns>', 'Exclude directories—relative to input directory—from processing (comma-separated, overrides config file setting)');
|
|
314
|
+
program.option('-O --output-dir <dir>', 'Specify an output directory');
|
|
315
|
+
program.option('-w --workers <n>', 'Number of worker threads for multi-file runs; defaults to half the available cores (at most 6) for runs large enough to justify them', parseValidInt('workers'));
|
|
316
|
+
program.option('-f --file-ext <extensions>', 'Specify file extension(s) to process (comma-separated, overrides config file setting); defaults to `html,htm,shtml,shtm`; use `*` for all files');
|
|
317
|
+
program.option('-p --preset <name>', `Use a preset configuration (${getPresetNames().join(', ')})`);
|
|
318
|
+
program.option('-c --config-file <file>', 'Use a configuration file (defaults to html-minifier-next.config.json in the working directory, if present)');
|
|
319
|
+
program.version(pkg.version, '-V, --version', 'Output the version number');
|
|
320
|
+
program.helpOption('-h, --help', 'Display help for command');
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Progress state shared between the file walk and the indicator; `total` stays
|
|
324
|
+
* `null` until the background count finishes
|
|
325
|
+
* @typedef {{current: number, total: number | null}} Progress
|
|
326
|
+
*/
|
|
327
|
+
|
|
328
|
+
(async () => {
|
|
329
|
+
/** @type {string} */
|
|
330
|
+
let content;
|
|
331
|
+
let filesProvided = false;
|
|
332
|
+
/** @type {string[]} */
|
|
333
|
+
let capturedFiles = [];
|
|
334
|
+
await program.arguments('[files...]').action(function (files) {
|
|
335
|
+
capturedFiles = files;
|
|
336
|
+
filesProvided = files.length > 0;
|
|
337
|
+
// Defer reading files until after check for consumed filenames
|
|
338
|
+
}).parseAsync(process.argv);
|
|
339
|
+
|
|
340
|
+
const programOptions = program.opts();
|
|
341
|
+
|
|
342
|
+
// Check if any `parseJSON` options consumed a filename as their value
|
|
343
|
+
// If so, treat the option as boolean true and add the filename back to the files list
|
|
344
|
+
const jsonOptionKeys = ['minifyCss', 'minifyJs', 'minifyUrls'];
|
|
345
|
+
for (const key of jsonOptionKeys) {
|
|
346
|
+
const value = programOptions[key];
|
|
347
|
+
if (typeof value === 'string' && /\.(html?|shtml?|xhtml?|php|xml|svg|jsx|tsx|vue|ejs|hbs|mustache|twig)$/i.test(value)) {
|
|
348
|
+
// The option consumed a filename—inject it back
|
|
349
|
+
programOptions[key] = true;
|
|
350
|
+
capturedFiles.push(value);
|
|
351
|
+
filesProvided = true;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// If `--input` was specified, treat it as a positional file argument
|
|
356
|
+
if (programOptions.input) {
|
|
357
|
+
capturedFiles.unshift(programOptions.input);
|
|
358
|
+
filesProvided = true;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Handle zero config mode (standalone in-place minification of the current folder)
|
|
362
|
+
if (programOptions.zero) {
|
|
363
|
+
const hasOtherArgs = process.argv.slice(2).some(arg => arg !== '--zero' && arg !== '-z');
|
|
364
|
+
if (hasOtherArgs) {
|
|
365
|
+
console.error('Note: `--zero` was ignored—it can only be used on its own, to minify the current folder at comprehensive settings.');
|
|
366
|
+
} else {
|
|
367
|
+
const cwd = process.cwd();
|
|
368
|
+
const [execPath = '', scriptPath = ''] = process.argv;
|
|
369
|
+
const commandName = process.env.npm_command === 'exec'
|
|
370
|
+
? 'npx html-minifier-next'
|
|
371
|
+
: scriptPath.endsWith('.js')
|
|
372
|
+
? `${path.basename(execPath)} ${scriptPath}`
|
|
373
|
+
: path.basename(scriptPath);
|
|
374
|
+
|
|
375
|
+
process.stderr.write(
|
|
376
|
+
`${MARK_WARNING}Zero-config mode minifies all HTML files in the current folder and its subfolders (${cwd}) in place, using comprehensive settings. If you want to compare results and be able to revert, do this under version control.${MARK_RESET}\n` +
|
|
377
|
+
`Equivalent to: ${commandName} --input-dir=. --output-dir=. --ignore-dir=node_modules --preset=comprehensive\n\n` +
|
|
378
|
+
`Do you want to continue? [y/N] `
|
|
379
|
+
);
|
|
380
|
+
|
|
381
|
+
const answer = await new Promise((resolve) => {
|
|
382
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
383
|
+
rl.once('line', (line) => {
|
|
384
|
+
resolve(line.trim().toLowerCase());
|
|
385
|
+
rl.close();
|
|
386
|
+
});
|
|
387
|
+
rl.once('close', () => resolve(''));
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
if (answer !== 'y') {
|
|
391
|
+
process.stderr.write(`${MARK_ERROR}In-place minification aborted.${MARK_RESET}\n`);
|
|
392
|
+
process.exit(0);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// Apply comprehensive preset for all processing
|
|
396
|
+
programOptions.preset = 'comprehensive';
|
|
397
|
+
|
|
398
|
+
const inputDirResolved = await fs.promises.realpath(cwd).catch(() => cwd);
|
|
399
|
+
const extensions = EXTENSIONS_DEFAULT;
|
|
400
|
+
const ignorePatterns = ['node_modules'];
|
|
401
|
+
|
|
402
|
+
const showProgress = process.stderr.isTTY;
|
|
403
|
+
/** @type {Progress | null} */
|
|
404
|
+
let progress = null;
|
|
405
|
+
if (showProgress) {
|
|
406
|
+
progress = { current: 0, total: null };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const allFiles = await collectFiles(cwd, extensions, undefined, ignorePatterns, inputDirResolved);
|
|
410
|
+
const concurrency = Math.max(1, Math.min(os.cpus().length || 4, 8));
|
|
411
|
+
|
|
412
|
+
if (progress) {
|
|
413
|
+
progress.total = allFiles.length;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
await runWithConcurrency(allFiles, concurrency, async (file) => {
|
|
417
|
+
await processFile(file, file, false, false);
|
|
418
|
+
if (progress) {
|
|
419
|
+
progress.current++;
|
|
420
|
+
updateProgress(progress.current, progress.total);
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
if (progress) {
|
|
425
|
+
clearProgress();
|
|
426
|
+
}
|
|
427
|
+
console.error(`${MARK_SUCCESS}Processed ${allFiles.length.toLocaleString()} file${allFiles.length === 1 ? '' : 's'}.${MARK_RESET}`);
|
|
428
|
+
|
|
429
|
+
process.exit(0);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// Load and normalize config if `--config-file` was specified; otherwise look
|
|
434
|
+
// for a default config file in the working directory
|
|
435
|
+
if (programOptions.configFile) {
|
|
436
|
+
config = await loadConfigFromPath(programOptions.configFile);
|
|
437
|
+
config = normalizeConfig(config);
|
|
438
|
+
} else {
|
|
439
|
+
const configFileDefault = CONFIG_FILES_DEFAULT.find(name => fs.existsSync(path.resolve(name)));
|
|
440
|
+
if (configFileDefault) {
|
|
441
|
+
console.error(`Using config file ${configFileDefault}`);
|
|
442
|
+
config = normalizeConfig(await loadConfigFromPath(configFileDefault));
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function createOptions() {
|
|
447
|
+
/** @type {Record<string, any>} */
|
|
448
|
+
const options = {};
|
|
449
|
+
|
|
450
|
+
// Priority order: preset < config < CLI
|
|
451
|
+
// 1. Apply preset if specified (CLI `--preset` takes priority over config.preset)
|
|
452
|
+
const presetName = programOptions.preset || config.preset;
|
|
453
|
+
if (presetName) {
|
|
454
|
+
const preset = getPreset(presetName);
|
|
455
|
+
if (!preset) {
|
|
456
|
+
fatal(`Unknown preset “${presetName}”. Available presets: ${getPresetNames().join(', ')}`);
|
|
457
|
+
}
|
|
458
|
+
Object.assign(options, preset);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// 2. Apply config file options (overrides preset)
|
|
462
|
+
mainOptionKeys.forEach(function (key) {
|
|
463
|
+
if (key in config) {
|
|
464
|
+
options[key] = config[key];
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
// 3. Apply CLI options (overrides config and preset)
|
|
469
|
+
Object.entries(optionDefinitions).forEach(function ([key, { type }]) {
|
|
470
|
+
const ck = commanderOptionKey(key);
|
|
471
|
+
if (program.getOptionValueSource(ck) === 'cli') {
|
|
472
|
+
const val = programOptions[ck];
|
|
473
|
+
// For boolean options whose param-case name starts with `no-`, Commander treats
|
|
474
|
+
// the flag as a negation and stores the inverted value under the stripped key;
|
|
475
|
+
// invert back so the option definition key gets the intended value
|
|
476
|
+
options[key] = (type === 'boolean' && paramCase(key).startsWith('no-')) ? !val : val;
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
// 4. Surface minifier diagnostics when verbose
|
|
481
|
+
if (programOptions.verbose || programOptions.dry) {
|
|
482
|
+
options.log = createLog();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return options;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Diagnostics name no file of their own, so a run over a directory—where several are in
|
|
490
|
+
* flight at once and lines interleave—says which file each came from
|
|
491
|
+
* @param {string} [fileLabel]
|
|
492
|
+
*/
|
|
493
|
+
function createLog(fileLabel) {
|
|
494
|
+
const where = fileLabel ? ` (${fileLabel})` : '';
|
|
495
|
+
return (/** @type {unknown} */ message) => {
|
|
496
|
+
// The hook carries the minifier’s per-call timing as well, which the run's own
|
|
497
|
+
// per-file statistics already cover
|
|
498
|
+
if (typeof message === 'string' && message.startsWith('minified in: ')) {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
// Only `continueOnMinifyError` passes `Error` objects, always after leaving the
|
|
502
|
+
// offending content unminified—so say that
|
|
503
|
+
if (message instanceof Error) {
|
|
504
|
+
console.error(` ${MARK_WARNING}Warning: Minification failed, content left as-is: ${message.message || message}${where}${MARK_RESET}`);
|
|
505
|
+
} else if (String(message).startsWith('Warning: ') || String(message).startsWith('HTML Minifier Next: ')) {
|
|
506
|
+
console.error(` ${MARK_WARNING}${message}${where}${MARK_RESET}`);
|
|
507
|
+
} else {
|
|
508
|
+
console.error(` ${message}${where}`);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** @param {Record<string, unknown>} minifierOptions */
|
|
514
|
+
function getActiveOptionsDisplay(minifierOptions) {
|
|
515
|
+
const presetName = programOptions.preset || config.preset;
|
|
516
|
+
if (presetName) {
|
|
517
|
+
console.error(`Using preset: ${presetName}`);
|
|
518
|
+
}
|
|
519
|
+
const activeOptions = Object.entries(minifierOptions)
|
|
520
|
+
.filter(([k]) => program.getOptionValueSource(commanderOptionKey(k)) === 'cli')
|
|
521
|
+
.map(([k, v]) => (typeof v === 'boolean' ? (v ? k : `no-${k}`) : k));
|
|
522
|
+
if (activeOptions.length > 0) {
|
|
523
|
+
console.error('CLI options: ' + activeOptions.join(', '));
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* @param {string} original
|
|
529
|
+
* @param {string} minified
|
|
530
|
+
*/
|
|
531
|
+
function calculateStats(original, minified) {
|
|
532
|
+
return calculateSizeStats(Buffer.byteLength(original, 'utf8'), Buffer.byteLength(minified, 'utf8'));
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* @param {number} originalSize
|
|
537
|
+
* @param {number} minifiedSize
|
|
538
|
+
*/
|
|
539
|
+
function calculateSizeStats(originalSize, minifiedSize) {
|
|
540
|
+
const saved = originalSize - minifiedSize;
|
|
541
|
+
const sign = saved >= 0 ? '-' : '+';
|
|
542
|
+
const percentage = originalSize ? ((Math.abs(saved) / originalSize) * 100).toFixed(1) : '0.0';
|
|
543
|
+
return { originalSize, minifiedSize, saved, sign, percentage };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// A run with many files earns back each worker’s isolate/JIT startup cost. A smaller
|
|
547
|
+
// run can do so too when it carries enough bytes to share out, which a file count
|
|
548
|
+
// alone cannot see.
|
|
549
|
+
const FILES_PER_RUN_MIN = 128;
|
|
550
|
+
const PARALLEL_BYTES_MIN = 2 * 1024 * 1024;
|
|
551
|
+
// Each worker warms up its own JIT, so the useful count tops out well short of the cores
|
|
552
|
+
const WORKERS_MAX = 6;
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* A pool for this run, or `null` where one wouldn’t pay or wouldn’t work—in which case
|
|
556
|
+
* the caller minifies in process exactly as before
|
|
557
|
+
* @param {string[]} files
|
|
558
|
+
*/
|
|
559
|
+
async function createPool(files) {
|
|
560
|
+
const fileCount = files.length;
|
|
561
|
+
const requested = programOptions.workers;
|
|
562
|
+
const isVerbose = Boolean(programOptions.verbose || programOptions.dry);
|
|
563
|
+
// Whether the run went wide is worth saying, since the default weighs the file
|
|
564
|
+
// count and the bytes there are to share out, neither of which the caller sees
|
|
565
|
+
const inProcess = () => {
|
|
566
|
+
if (isVerbose) console.error('Worker threads: none (minifying in process)');
|
|
567
|
+
return null;
|
|
568
|
+
};
|
|
569
|
+
// `availableParallelism` reports what this process may actually use, which under a
|
|
570
|
+
// CPU affinity mask—a container, commonly—is less than the machine’s core count
|
|
571
|
+
const isDefault = requested === undefined;
|
|
572
|
+
const size = isDefault
|
|
573
|
+
? Math.max(1, Math.min(Math.floor(os.availableParallelism() / 2), WORKERS_MAX))
|
|
574
|
+
: requested;
|
|
575
|
+
|
|
576
|
+
// The file count only decides the default; asking for workers outright is the
|
|
577
|
+
// caller’s judgment to make, whatever the run looks like
|
|
578
|
+
if (size <= 1) {
|
|
579
|
+
return inProcess();
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
if (isDefault && fileCount < FILES_PER_RUN_MIN) {
|
|
583
|
+
// `stat()` is cheaper than starting workers and is only needed for a run that
|
|
584
|
+
// would otherwise stay in-process. A failed stat leaves normal file processing
|
|
585
|
+
// to report the read error with its usual filename and wording.
|
|
586
|
+
const sizes = await Promise.all(files.map(file => fs.promises.stat(file).then(stat => stat.size, () => 0)));
|
|
587
|
+
// No single file is split across workers, so the largest one sets a floor no
|
|
588
|
+
// pool can beat; what the rest carry is the work there is to share out
|
|
589
|
+
const parallelBytes = sizes.reduce((sum, byteSize) => sum + byteSize, 0) - Math.max(0, ...sizes);
|
|
590
|
+
if (parallelBytes < PARALLEL_BYTES_MIN) {
|
|
591
|
+
return inProcess();
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// `log` is a closure over this process’s console and is rebuilt inside the worker;
|
|
596
|
+
// anything else unclonable (which the CLI itself never produces) stays in process
|
|
597
|
+
const { log, ...options } = createOptions();
|
|
598
|
+
try {
|
|
599
|
+
structuredClone(options);
|
|
600
|
+
} catch {
|
|
601
|
+
return inProcess();
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// A pool this small has nothing to share out and still pays for its workers, so an
|
|
605
|
+
// explicit request for them lands in process as `--workers=1` does
|
|
606
|
+
const poolSize = Math.min(size, fileCount);
|
|
607
|
+
if (poolSize <= 1) {
|
|
608
|
+
return inProcess();
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
try {
|
|
612
|
+
const { createFilePool } = await import('./src/lib/file-pool.js');
|
|
613
|
+
const pool = createFilePool({
|
|
614
|
+
options,
|
|
615
|
+
size: poolSize,
|
|
616
|
+
// `log` is only set when the run asks for diagnostics
|
|
617
|
+
onLog: log
|
|
618
|
+
? (/** @type {string} */ message, /** @type {boolean} */ isError, /** @type {string} */ file) =>
|
|
619
|
+
createLog(path.relative(process.cwd(), file))(isError ? new Error(message) : message)
|
|
620
|
+
: undefined
|
|
621
|
+
});
|
|
622
|
+
if (isVerbose) console.error(`Worker threads: ${poolSize}`);
|
|
623
|
+
return pool;
|
|
624
|
+
} catch {
|
|
625
|
+
return inProcess();
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// Print a one-line-per-cache hits/misses/size summary to STDERR, skipping caches
|
|
630
|
+
// that were never touched (e.g., their minifier is disabled)
|
|
631
|
+
async function printCacheStats() {
|
|
632
|
+
const { getCacheStats } = await import('./src/htmlminifier.js');
|
|
633
|
+
const cacheStats = getCacheStats();
|
|
634
|
+
/** @type {Record<string, string>} */
|
|
635
|
+
const labels = { css: 'CSS', js: 'JS', svg: 'SVG' };
|
|
636
|
+
|
|
637
|
+
/** @type {string[]} */
|
|
638
|
+
const lines = [];
|
|
639
|
+
for (const [key, { gets, hits, size, limit }] of Object.entries(cacheStats)) {
|
|
640
|
+
if (gets === 0) continue;
|
|
641
|
+
const misses = gets - hits;
|
|
642
|
+
lines.push(` ${labels[key]} cache: ${hits.toLocaleString()} hit${hits === 1 ? '' : 's'}, ${misses.toLocaleString()} miss${misses === 1 ? '' : 'es'}, ${size.toLocaleString()}/${limit.toLocaleString()} entries`);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
if (lines.length === 0) return;
|
|
646
|
+
console.error('Cache stats:');
|
|
647
|
+
lines.forEach(line => console.error(line));
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* @param {string} inputFile
|
|
652
|
+
* @param {string} outputFile
|
|
653
|
+
* @param {boolean} [isDryRun]
|
|
654
|
+
* @param {boolean} [isVerbose]
|
|
655
|
+
*/
|
|
656
|
+
async function processFile(inputFile, outputFile, isDryRun = false, isVerbose = false) {
|
|
657
|
+
const data = await fs.promises.readFile(inputFile, { encoding: 'utf8' }).catch(err => {
|
|
658
|
+
fatal('Cannot read ' + inputFile + '\n' + errorMessage(err));
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
let minified;
|
|
662
|
+
try {
|
|
663
|
+
const minify = await getMinify();
|
|
664
|
+
const fileOptions = createOptions();
|
|
665
|
+
if (fileOptions.log) {
|
|
666
|
+
fileOptions.log = createLog(path.relative(process.cwd(), inputFile));
|
|
667
|
+
}
|
|
668
|
+
minified = await minify(data, fileOptions);
|
|
669
|
+
} catch (err) {
|
|
670
|
+
fatal('Minification error on ' + inputFile + '\n' + errorMessage(err));
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
const stats = calculateStats(data, minified);
|
|
674
|
+
|
|
675
|
+
// Show stats if dry run or verbose mode
|
|
676
|
+
if (isDryRun || isVerbose) {
|
|
677
|
+
console.error(` ${MARK_SUCCESS}✓${MARK_RESET} ${path.relative(process.cwd(), inputFile)}: ${stats.originalSize.toLocaleString()} → ${stats.minifiedSize.toLocaleString()} bytes (${stats.sign}${Math.abs(stats.saved).toLocaleString()}, ${stats.percentage}%)`);
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
if (isDryRun) {
|
|
681
|
+
return { originalSize: stats.originalSize, minifiedSize: stats.minifiedSize, saved: stats.saved };
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
await fs.promises.writeFile(outputFile, minified, { encoding: 'utf8' }).catch(err => {
|
|
685
|
+
fatal('Cannot write ' + outputFile + '\n' + err.message);
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
return { originalSize: stats.originalSize, minifiedSize: stats.minifiedSize, saved: stats.saved };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* @param {string} fileExt
|
|
693
|
+
* @returns {string[]}
|
|
694
|
+
*/
|
|
695
|
+
function parseFileExtensions(fileExt) {
|
|
696
|
+
if (!fileExt) return [];
|
|
697
|
+
if (fileExt.trim() === '*') return ['*'];
|
|
698
|
+
const list = fileExt
|
|
699
|
+
.split(',')
|
|
700
|
+
.map(ext => ext.trim().replace(/^\.+/, '').toLowerCase())
|
|
701
|
+
.filter(ext => ext.length > 0);
|
|
702
|
+
return [...new Set(list)];
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* @param {string} filename
|
|
707
|
+
* @param {string[]} fileExtensions
|
|
708
|
+
*/
|
|
709
|
+
function shouldProcessFile(filename, fileExtensions) {
|
|
710
|
+
// Wildcard: process all files
|
|
711
|
+
if (fileExtensions.includes('*')) {
|
|
712
|
+
return true;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
const fileExt = path.extname(filename).replace(/^\.+/, '').toLowerCase();
|
|
716
|
+
return fileExtensions.includes(fileExt);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Parse comma-separated ignore patterns into an array.
|
|
721
|
+
* @param {string} patterns - Comma-separated directory patterns (e.g., "libs,vendor")
|
|
722
|
+
* @returns {string[]} Array of trimmed pattern strings with normalized separators
|
|
723
|
+
*/
|
|
724
|
+
function parseIgnorePatterns(patterns) {
|
|
725
|
+
if (!patterns) return [];
|
|
726
|
+
return patterns
|
|
727
|
+
.split(',')
|
|
728
|
+
.map(p => p.trim().replace(/\\/g, '/').replace(/\/+$/, ''))
|
|
729
|
+
.filter(p => p.length > 0);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Check if a directory should be ignored based on ignore patterns.
|
|
734
|
+
* Supports matching by directory name or relative path.
|
|
735
|
+
* @param {string} dirPath - Absolute path to the directory
|
|
736
|
+
* @param {string[]} ignorePatterns - Array of patterns to match against (with forward slashes)
|
|
737
|
+
* @param {string} baseDir - Base directory for relative path calculation
|
|
738
|
+
* @returns {boolean} True if directory should be ignored
|
|
739
|
+
*/
|
|
740
|
+
function shouldIgnoreDirectory(dirPath, ignorePatterns, baseDir) {
|
|
741
|
+
if (!ignorePatterns || ignorePatterns.length === 0) return false;
|
|
742
|
+
|
|
743
|
+
// Normalize to forward slashes for cross-platform comparison
|
|
744
|
+
const relativePath = path.relative(baseDir, dirPath).replace(/\\/g, '/');
|
|
745
|
+
const dirName = path.basename(dirPath);
|
|
746
|
+
|
|
747
|
+
return ignorePatterns.some(pattern => {
|
|
748
|
+
// Support both exact directory names and relative paths
|
|
749
|
+
return dirName === pattern || relativePath === pattern || relativePath.startsWith(pattern + '/');
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* @param {string} dir
|
|
755
|
+
* @param {string[]} extensions
|
|
756
|
+
* @param {string | undefined} skipRootAbs
|
|
757
|
+
* @param {string[]} ignorePatterns
|
|
758
|
+
* @param {string} baseDir
|
|
759
|
+
* @returns {Promise<number>}
|
|
760
|
+
*/
|
|
761
|
+
async function countFiles(dir, extensions, skipRootAbs, ignorePatterns, baseDir) {
|
|
762
|
+
let count = 0;
|
|
763
|
+
|
|
764
|
+
const files = await fs.promises.readdir(dir).catch(() => []);
|
|
765
|
+
|
|
766
|
+
for (const file of files) {
|
|
767
|
+
const filePath = path.join(dir, file);
|
|
768
|
+
|
|
769
|
+
// Skip anything inside the output root
|
|
770
|
+
if (skipRootAbs) {
|
|
771
|
+
const real = await fs.promises.realpath(filePath).catch(() => undefined);
|
|
772
|
+
if (real && (real === skipRootAbs || real.startsWith(skipRootAbs + path.sep))) {
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const lst = await fs.promises.lstat(filePath).catch(() => null);
|
|
778
|
+
if (!lst || lst.isSymbolicLink()) {
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
if (lst.isDirectory()) {
|
|
783
|
+
// Skip ignored directories
|
|
784
|
+
if (shouldIgnoreDirectory(filePath, ignorePatterns, baseDir)) {
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
count += await countFiles(filePath, extensions, skipRootAbs, ignorePatterns, baseDir);
|
|
788
|
+
} else if (shouldProcessFile(file, extensions)) {
|
|
789
|
+
count++;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
return count;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* @param {number} current
|
|
798
|
+
* @param {number | null} total
|
|
799
|
+
*/
|
|
800
|
+
function updateProgress(current, total) {
|
|
801
|
+
// Clear the line first, then write simple progress
|
|
802
|
+
process.stderr.write(`\r\x1b[K`);
|
|
803
|
+
if (total) {
|
|
804
|
+
const ratio = Math.min(current / total, 1);
|
|
805
|
+
const percentage = (ratio * 100).toFixed(1);
|
|
806
|
+
process.stderr.write(`Processing ${current.toLocaleString()}/${total.toLocaleString()} (${percentage}%)`);
|
|
807
|
+
} else {
|
|
808
|
+
// Indeterminate progress - no total known yet
|
|
809
|
+
process.stderr.write(`Processing ${current.toLocaleString()} files…`);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function clearProgress() {
|
|
814
|
+
process.stderr.write('\r\x1b[K'); // Clear the line
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// Utility: concurrency runner
|
|
818
|
+
/**
|
|
819
|
+
* @template T, R
|
|
820
|
+
* @param {T[]} items
|
|
821
|
+
* @param {number} limit
|
|
822
|
+
* @param {(item: T, index: number) => Promise<R>} worker
|
|
823
|
+
* @returns {Promise<R[]>}
|
|
824
|
+
*/
|
|
825
|
+
async function runWithConcurrency(items, limit, worker) {
|
|
826
|
+
/** @type {R[]} */
|
|
827
|
+
const results = new Array(items.length);
|
|
828
|
+
let next = 0;
|
|
829
|
+
let active = 0;
|
|
830
|
+
return new Promise((resolve, reject) => {
|
|
831
|
+
const launch = () => {
|
|
832
|
+
while (active < limit && next < items.length) {
|
|
833
|
+
const current = next++;
|
|
834
|
+
const item = /** @type {T} */ (items[current]);
|
|
835
|
+
active++;
|
|
836
|
+
Promise.resolve(worker(item, current))
|
|
837
|
+
.then((res) => {
|
|
838
|
+
results[current] = res;
|
|
839
|
+
active--;
|
|
840
|
+
launch();
|
|
841
|
+
})
|
|
842
|
+
.catch(reject);
|
|
843
|
+
}
|
|
844
|
+
if (next >= items.length && active === 0) {
|
|
845
|
+
resolve(results);
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
launch();
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* @param {string} dir
|
|
854
|
+
* @param {string[]} extensions
|
|
855
|
+
* @param {string | undefined} skipRootAbs
|
|
856
|
+
* @param {string[]} ignorePatterns
|
|
857
|
+
* @param {string} baseDir
|
|
858
|
+
* @returns {Promise<string[]>}
|
|
859
|
+
*/
|
|
860
|
+
async function collectFiles(dir, extensions, skipRootAbs, ignorePatterns, baseDir) {
|
|
861
|
+
/** @type {string[]} */
|
|
862
|
+
const out = [];
|
|
863
|
+
const entries = await fs.promises.readdir(dir).catch(() => []);
|
|
864
|
+
for (const name of entries) {
|
|
865
|
+
const filePath = path.join(dir, name);
|
|
866
|
+
if (skipRootAbs) {
|
|
867
|
+
const real = await fs.promises.realpath(filePath).catch(() => undefined);
|
|
868
|
+
if (real && (real === skipRootAbs || real.startsWith(skipRootAbs + path.sep))) continue;
|
|
869
|
+
}
|
|
870
|
+
const lst = await fs.promises.lstat(filePath).catch(() => null);
|
|
871
|
+
if (!lst || lst.isSymbolicLink()) continue;
|
|
872
|
+
if (lst.isDirectory()) {
|
|
873
|
+
if (shouldIgnoreDirectory(filePath, ignorePatterns, baseDir)) continue;
|
|
874
|
+
const sub = await collectFiles(filePath, extensions, skipRootAbs, ignorePatterns, baseDir);
|
|
875
|
+
out.push(...sub);
|
|
876
|
+
} else if (shouldProcessFile(name, extensions)) {
|
|
877
|
+
out.push(filePath);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
return out;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* @param {string} inputDir
|
|
885
|
+
* @param {string} outputDir
|
|
886
|
+
* @param {string | string[]} extensions
|
|
887
|
+
* @param {boolean} [isDryRun]
|
|
888
|
+
* @param {boolean} [isVerbose]
|
|
889
|
+
* @param {string} [skipRootAbs]
|
|
890
|
+
* @param {Progress | null} [progress]
|
|
891
|
+
* @param {string[]} [ignorePatterns]
|
|
892
|
+
* @param {string | null} [baseDir]
|
|
893
|
+
*/
|
|
894
|
+
async function processDirectory(inputDir, outputDir, extensions, isDryRun = false, isVerbose = false, skipRootAbs, progress = null, ignorePatterns = [], baseDir = null) {
|
|
895
|
+
// If first call provided a string, normalize once; otherwise assume pre-parsed array
|
|
896
|
+
if (typeof extensions === 'string') {
|
|
897
|
+
extensions = parseFileExtensions(extensions);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
// Set `baseDir` on first call
|
|
901
|
+
if (baseDir === null) {
|
|
902
|
+
baseDir = inputDir;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// Collect all files first for bounded parallel processing
|
|
906
|
+
const list = await collectFiles(inputDir, extensions, skipRootAbs, ignorePatterns, baseDir);
|
|
907
|
+
const allStats = new Array(list.length);
|
|
908
|
+
|
|
909
|
+
const prepareOutDir = async (/** @type {string} */ inputFile) => {
|
|
910
|
+
const outFile = path.join(outputDir, path.relative(inputDir, inputFile));
|
|
911
|
+
if (!isDryRun) {
|
|
912
|
+
await fs.promises.mkdir(path.dirname(outFile), { recursive: true }).catch(err => {
|
|
913
|
+
fatal('Cannot create directory ' + path.dirname(outFile) + '\n' + errorMessage(err));
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
return outFile;
|
|
917
|
+
};
|
|
918
|
+
|
|
919
|
+
const advanceProgress = () => {
|
|
920
|
+
if (progress) {
|
|
921
|
+
progress.current++;
|
|
922
|
+
updateProgress(progress.current, progress.total);
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
|
|
926
|
+
const pool = await createPool(list);
|
|
927
|
+
if (pool) {
|
|
928
|
+
try {
|
|
929
|
+
await Promise.all(list.map(async (inputFile, idx) => {
|
|
930
|
+
const outFile = await prepareOutDir(inputFile);
|
|
931
|
+
const sizes = await pool.run({ inputFile, outputFile: outFile, dryRun: isDryRun })
|
|
932
|
+
.catch(err => {
|
|
933
|
+
// A worker names the step it failed at, so the wording matches what this
|
|
934
|
+
// file would have got had it been minified in this process
|
|
935
|
+
if (err?.stage === 'read') fatal('Cannot read ' + inputFile + '\n' + errorMessage(err));
|
|
936
|
+
if (err?.stage === 'write') fatal('Cannot write ' + outFile + '\n' + errorMessage(err));
|
|
937
|
+
fatal('Minification error on ' + inputFile + '\n' + errorMessage(err));
|
|
938
|
+
});
|
|
939
|
+
const stats = calculateSizeStats(sizes.originalSize, sizes.minifiedSize);
|
|
940
|
+
if (isDryRun || isVerbose) {
|
|
941
|
+
console.error(` ${MARK_SUCCESS}✓${MARK_RESET} ${path.relative(process.cwd(), inputFile)}: ${stats.originalSize.toLocaleString()} → ${stats.minifiedSize.toLocaleString()} bytes (${stats.sign}${Math.abs(stats.saved).toLocaleString()}, ${stats.percentage}%)`);
|
|
942
|
+
}
|
|
943
|
+
allStats[idx] = { originalSize: stats.originalSize, minifiedSize: stats.minifiedSize, saved: stats.saved };
|
|
944
|
+
advanceProgress();
|
|
945
|
+
}));
|
|
946
|
+
} finally {
|
|
947
|
+
await pool.close();
|
|
948
|
+
}
|
|
949
|
+
return allStats.filter(Boolean);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const concurrency = Math.max(1, Math.min(os.cpus().length || 4, 8));
|
|
953
|
+
await runWithConcurrency(list, concurrency, async (inputFile, idx) => {
|
|
954
|
+
const outFile = await prepareOutDir(inputFile);
|
|
955
|
+
const stats = await processFile(inputFile, outFile, isDryRun, isVerbose);
|
|
956
|
+
allStats[idx] = stats;
|
|
957
|
+
advanceProgress();
|
|
958
|
+
});
|
|
959
|
+
return allStats.filter(Boolean);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const writeMinify = async () => {
|
|
963
|
+
const minifierOptions = createOptions();
|
|
964
|
+
|
|
965
|
+
// Show config info if verbose
|
|
966
|
+
if (programOptions.verbose || programOptions.dry) {
|
|
967
|
+
getActiveOptionsDisplay(minifierOptions);
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
let minified;
|
|
971
|
+
|
|
972
|
+
try {
|
|
973
|
+
const minify = await getMinify();
|
|
974
|
+
minified = await minify(content, minifierOptions);
|
|
975
|
+
} catch (err) {
|
|
976
|
+
fatal('Minification error:\n' + errorMessage(err));
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
const stats = calculateStats(content, minified);
|
|
980
|
+
|
|
981
|
+
if (programOptions.dry) {
|
|
982
|
+
const inputSource = program.args.length > 0 ? program.args.join(', ') : 'STDIN';
|
|
983
|
+
const outputDest = programOptions.output || 'STDOUT';
|
|
984
|
+
|
|
985
|
+
console.error(`[DRY RUN] Would minify: ${inputSource} → ${outputDest}`);
|
|
986
|
+
console.error(` Original: ${stats.originalSize.toLocaleString()} bytes`);
|
|
987
|
+
console.error(` Minified: ${stats.minifiedSize.toLocaleString()} bytes`);
|
|
988
|
+
console.error(` Saved: ${stats.sign}${Math.abs(stats.saved).toLocaleString()} bytes (${stats.percentage}%)`);
|
|
989
|
+
await printCacheStats();
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// Show stats if verbose
|
|
994
|
+
if (programOptions.verbose) {
|
|
995
|
+
const inputSource = program.args.length > 0 ? program.args.join(', ') : 'STDIN';
|
|
996
|
+
console.error(` ${MARK_SUCCESS}✓${MARK_RESET} ${inputSource}: ${stats.originalSize.toLocaleString()} → ${stats.minifiedSize.toLocaleString()} bytes (${stats.sign}${Math.abs(stats.saved).toLocaleString()}, ${stats.percentage}%)`);
|
|
997
|
+
await printCacheStats();
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
if (programOptions.output) {
|
|
1001
|
+
try {
|
|
1002
|
+
await fs.promises.mkdir(path.dirname(programOptions.output), { recursive: true });
|
|
1003
|
+
await fs.promises.writeFile(programOptions.output, minified, { encoding: 'utf8' });
|
|
1004
|
+
} catch (err) {
|
|
1005
|
+
fatal('Cannot write ' + programOptions.output + '\n' + errorMessage(err));
|
|
1006
|
+
}
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
process.stdout.write(minified);
|
|
1011
|
+
};
|
|
1012
|
+
|
|
1013
|
+
const { inputDir, outputDir, fileExt, ignoreDir } = programOptions;
|
|
1014
|
+
|
|
1015
|
+
// Resolve file extensions: CLI argument > config file > defaults
|
|
1016
|
+
const hasCliFileExt = program.getOptionValueSource('fileExt') === 'cli';
|
|
1017
|
+
const resolvedFileExt = hasCliFileExt ? (fileExt || '*') : (config.fileExt || EXTENSIONS_DEFAULT);
|
|
1018
|
+
|
|
1019
|
+
// Resolve ignore patterns: CLI argument takes priority over config file
|
|
1020
|
+
const hasCliIgnoreDir = program.getOptionValueSource('ignoreDir') === 'cli';
|
|
1021
|
+
const resolvedIgnoreDir = hasCliIgnoreDir ? ignoreDir : config.ignoreDir;
|
|
1022
|
+
|
|
1023
|
+
if (inputDir || outputDir) {
|
|
1024
|
+
if (!inputDir) {
|
|
1025
|
+
fatal('The option `output-dir` needs to be used with the option `input-dir`—if you are working with a single file, use `--input`/`--output`');
|
|
1026
|
+
} else if (!outputDir) {
|
|
1027
|
+
fatal('You need to specify where to write the output files with the option `--output-dir`');
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
{
|
|
1031
|
+
const extList = Array.isArray(resolvedFileExt) ? resolvedFileExt : parseFileExtensions(String(resolvedFileExt || ''));
|
|
1032
|
+
const isWildcard = extList.includes('*');
|
|
1033
|
+
const nonHtmlExts = isWildcard ? [] : extList.filter(e => EXTENSIONS_NON_HTML.has(e));
|
|
1034
|
+
if (isWildcard || nonHtmlExts.length > 0) {
|
|
1035
|
+
const label = isWildcard ? 'all file types' : nonHtmlExts.map(e => `.${e}`).join(', ');
|
|
1036
|
+
console.error(`${MARK_WARNING}Warning: Processing ${label}—HTML Minifier Next processes CSS, JavaScript, and SVG only when embedded in HTML. Non-HTML files may produce incomplete or broken output.${MARK_RESET}`);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
await (async () => {
|
|
1041
|
+
// `--dry` automatically enables verbose mode
|
|
1042
|
+
const isVerbose = programOptions.verbose || programOptions.dry;
|
|
1043
|
+
|
|
1044
|
+
// Show config info if verbose
|
|
1045
|
+
if (isVerbose) {
|
|
1046
|
+
const minifierOptions = createOptions();
|
|
1047
|
+
getActiveOptionsDisplay(minifierOptions);
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
// Prevent traversing into the output directory when it is inside the input directory
|
|
1051
|
+
let outputReal;
|
|
1052
|
+
const inputReal = await fs.promises.realpath(inputDir).catch(() => undefined);
|
|
1053
|
+
try {
|
|
1054
|
+
outputReal = await fs.promises.realpath(outputDir);
|
|
1055
|
+
} catch {
|
|
1056
|
+
outputReal = path.resolve(outputDir);
|
|
1057
|
+
}
|
|
1058
|
+
let skipRootAbs;
|
|
1059
|
+
if (inputReal && outputReal && outputReal !== inputReal && outputReal.startsWith(inputReal + path.sep)) {
|
|
1060
|
+
// Skip traversing into the output directory when it is nested inside the input directory
|
|
1061
|
+
skipRootAbs = outputReal;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
if (programOptions.dry) {
|
|
1065
|
+
console.error(`[DRY RUN] Would process directory: ${inputDir} → ${outputDir}`);
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// Set up progress indicator (only in TTY and when not verbose/dry)
|
|
1069
|
+
const showProgress = process.stderr.isTTY && !isVerbose;
|
|
1070
|
+
/** @type {Progress | null} */
|
|
1071
|
+
let progress = null;
|
|
1072
|
+
|
|
1073
|
+
// Parse ignore patterns
|
|
1074
|
+
const ignorePatterns = parseIgnorePatterns(resolvedIgnoreDir);
|
|
1075
|
+
|
|
1076
|
+
// Validate that the input directory exists and is readable
|
|
1077
|
+
try {
|
|
1078
|
+
const stat = await fs.promises.stat(inputDir);
|
|
1079
|
+
if (!stat.isDirectory()) {
|
|
1080
|
+
fatal(`${inputDir} is not a directory—to minify a single file, use \`--input\`/\`--output\`: html-minifier-next [options] -i ${inputDir} -o <output-file>`);
|
|
1081
|
+
}
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
fatal('Cannot read directory ' + inputDir + '\n' + errorMessage(err));
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// Resolve base directory for consistent path comparisons
|
|
1087
|
+
const inputDirResolved = inputReal || inputDir;
|
|
1088
|
+
|
|
1089
|
+
if (showProgress) {
|
|
1090
|
+
// Start with indeterminate progress, count in background
|
|
1091
|
+
progress = {current: 0, total: null};
|
|
1092
|
+
|
|
1093
|
+
// Note: `countFiles` runs asynchronously and mutates `progress.total` when complete.
|
|
1094
|
+
// This shared-state mutation is safe because JavaScript is single-threaded—
|
|
1095
|
+
// `updateProgress` may read `progress.total` as `null` initially,
|
|
1096
|
+
// then see the updated value once `countFiles` resolves,
|
|
1097
|
+
// transitioning the indicator from indeterminate to determinate progress without race conditions.
|
|
1098
|
+
const extensions = typeof resolvedFileExt === 'string' ? parseFileExtensions(resolvedFileExt) : resolvedFileExt;
|
|
1099
|
+
countFiles(inputDir, extensions, skipRootAbs, ignorePatterns, inputDirResolved).then(total => {
|
|
1100
|
+
if (progress) {
|
|
1101
|
+
progress.total = total;
|
|
1102
|
+
}
|
|
1103
|
+
}).catch(() => {
|
|
1104
|
+
// Ignore count errors, just keep showing indeterminate progress
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
const stats = await processDirectory(inputDir, outputDir, resolvedFileExt, programOptions.dry, isVerbose, skipRootAbs, progress, ignorePatterns, inputDirResolved);
|
|
1109
|
+
|
|
1110
|
+
// Show completion message and clear progress indicator
|
|
1111
|
+
if (progress) {
|
|
1112
|
+
clearProgress();
|
|
1113
|
+
console.error(`${MARK_SUCCESS}Processed ${progress.current.toLocaleString()} file${progress.current === 1 ? '' : 's'}.${MARK_RESET}`);
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
if (isVerbose && stats && stats.length > 0) {
|
|
1117
|
+
const totalOriginal = stats.reduce((sum, s) => sum + s.originalSize, 0);
|
|
1118
|
+
const totalMinified = stats.reduce((sum, s) => sum + s.minifiedSize, 0);
|
|
1119
|
+
const totalSaved = totalOriginal - totalMinified;
|
|
1120
|
+
const sign = totalSaved >= 0 ? '-' : '+';
|
|
1121
|
+
const totalPercentage = totalOriginal ? ((Math.abs(totalSaved) / totalOriginal) * 100).toFixed(1) : '0.0';
|
|
1122
|
+
|
|
1123
|
+
console.error('---');
|
|
1124
|
+
console.error(`Total: ${totalOriginal.toLocaleString()} → ${totalMinified.toLocaleString()} bytes (${sign}${Math.abs(totalSaved).toLocaleString()}, ${totalPercentage}%)`);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
if (isVerbose) {
|
|
1128
|
+
await printCacheStats();
|
|
1129
|
+
}
|
|
1130
|
+
})();
|
|
1131
|
+
} else if (filesProvided) { // Minifying one or more files specified on the CMD line
|
|
1132
|
+
// Process each file independently, then concatenate outputs
|
|
1133
|
+
const minifierOptions = createOptions();
|
|
1134
|
+
// Show config info if verbose/dry
|
|
1135
|
+
if (programOptions.verbose || programOptions.dry) {
|
|
1136
|
+
getActiveOptionsDisplay(minifierOptions);
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
for (const file of capturedFiles) {
|
|
1140
|
+
const ext = path.extname(file).replace(/^\./, '').toLowerCase();
|
|
1141
|
+
if (EXTENSIONS_NON_HTML.has(ext)) {
|
|
1142
|
+
console.error(`${MARK_WARNING}Warning: ${path.basename(file)} does not appear to be an HTML file—HTML Minifier Next processes CSS, JavaScript, and SVG only when embedded in HTML. The output may be incomplete or broken.${MARK_RESET}`);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
const concurrency = Math.max(1, Math.min(os.cpus().length || 4, 8));
|
|
1147
|
+
const inputs = capturedFiles.slice();
|
|
1148
|
+
|
|
1149
|
+
// Read originals and minify in parallel with bounded concurrency
|
|
1150
|
+
const originals = new Array(inputs.length);
|
|
1151
|
+
const outputs = new Array(inputs.length);
|
|
1152
|
+
|
|
1153
|
+
await runWithConcurrency(inputs, concurrency, async (file, idx) => {
|
|
1154
|
+
const data = await fs.promises.readFile(file, 'utf8').catch(err => fatal('Cannot read ' + file + '\n' + errorMessage(err)));
|
|
1155
|
+
const minify = await getMinify();
|
|
1156
|
+
let out;
|
|
1157
|
+
try {
|
|
1158
|
+
out = await minify(data, minifierOptions);
|
|
1159
|
+
} catch (err) {
|
|
1160
|
+
fatal('Minification error on ' + file + '\n' + errorMessage(err));
|
|
1161
|
+
}
|
|
1162
|
+
originals[idx] = data;
|
|
1163
|
+
outputs[idx] = out;
|
|
1164
|
+
});
|
|
1165
|
+
|
|
1166
|
+
const originalCombined = originals.join('');
|
|
1167
|
+
const minifiedCombined = outputs.join('');
|
|
1168
|
+
|
|
1169
|
+
const stats = calculateStats(originalCombined, minifiedCombined);
|
|
1170
|
+
|
|
1171
|
+
if (programOptions.dry) {
|
|
1172
|
+
const inputSource = capturedFiles.join(', ');
|
|
1173
|
+
const outputDest = programOptions.output || 'STDOUT';
|
|
1174
|
+
console.error(`[DRY RUN] Would minify: ${inputSource} → ${outputDest}`);
|
|
1175
|
+
console.error(` Original: ${stats.originalSize.toLocaleString()} bytes`);
|
|
1176
|
+
console.error(` Minified: ${stats.minifiedSize.toLocaleString()} bytes`);
|
|
1177
|
+
console.error(` Saved: ${stats.sign}${Math.abs(stats.saved).toLocaleString()} bytes (${stats.percentage}%)`);
|
|
1178
|
+
await printCacheStats();
|
|
1179
|
+
process.exit(0);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
if (programOptions.verbose) {
|
|
1183
|
+
const inputSource = capturedFiles.join(', ');
|
|
1184
|
+
console.error(` ${MARK_SUCCESS}✓${MARK_RESET} ${inputSource}: ${stats.originalSize.toLocaleString()} → ${stats.minifiedSize.toLocaleString()} bytes (${stats.sign}${Math.abs(stats.saved).toLocaleString()}, ${stats.percentage}%)`);
|
|
1185
|
+
await printCacheStats();
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
if (programOptions.output) {
|
|
1189
|
+
try {
|
|
1190
|
+
await fs.promises.mkdir(path.dirname(programOptions.output), { recursive: true });
|
|
1191
|
+
await fs.promises.writeFile(programOptions.output, minifiedCombined, 'utf8');
|
|
1192
|
+
} catch (err) {
|
|
1193
|
+
fatal('Cannot write ' + programOptions.output + '\n' + errorMessage(err));
|
|
1194
|
+
}
|
|
1195
|
+
} else {
|
|
1196
|
+
process.stdout.write(minifiedCombined);
|
|
1197
|
+
}
|
|
1198
|
+
process.exit(0);
|
|
1199
|
+
} else { // Minifying input coming from STDIN
|
|
1200
|
+
content = '';
|
|
1201
|
+
process.stdin.setEncoding('utf8');
|
|
1202
|
+
process.stdin.on('data', function (/** @type {string} */ data) {
|
|
1203
|
+
content += data;
|
|
1204
|
+
}).on('end', async function() {
|
|
1205
|
+
await writeMinify();
|
|
1206
|
+
process.exit(0);
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
})();
|