@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.
Files changed (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * HTML element tag omission rules
3
+ */
4
+
5
+ import {
6
+ headerElements,
7
+ descriptionElements,
8
+ pBlockElements,
9
+ rubyEndTagOmission,
10
+ rubyRtcEndTagOmission,
11
+ optionElements,
12
+ tableContentElements,
13
+ tableSectionElements,
14
+ cellElements
15
+ } from './constants.js';
16
+ import { hasAttrName } from './attributes.js';
17
+
18
+ /** @import { HTMLAttribute } from './attributes.js' */
19
+ /** @import { ProcessedOptions } from './options.js' */
20
+
21
+ // Tag omission rules
22
+
23
+ /**
24
+ * @param {string} optionalStartTag
25
+ * @param {string} tag
26
+ */
27
+ function canRemoveParentTag(optionalStartTag, tag) {
28
+ switch (optionalStartTag) {
29
+ case 'html':
30
+ case 'head':
31
+ return true;
32
+ case 'body':
33
+ return !headerElements.has(tag);
34
+ case 'colgroup':
35
+ return tag === 'col';
36
+ case 'tbody':
37
+ return tag === 'tr';
38
+ }
39
+ return false;
40
+ }
41
+
42
+ /**
43
+ * @param {string} optionalEndTag
44
+ * @param {string} tag
45
+ */
46
+ function isStartTagMandatory(optionalEndTag, tag) {
47
+ switch (tag) {
48
+ case 'colgroup':
49
+ return optionalEndTag === 'colgroup';
50
+ case 'tbody':
51
+ return tableSectionElements.has(optionalEndTag);
52
+ }
53
+ return false;
54
+ }
55
+
56
+ /**
57
+ * @param {string} optionalEndTag
58
+ * @param {string} tag
59
+ */
60
+ function canRemovePrecedingTag(optionalEndTag, tag) {
61
+ switch (optionalEndTag) {
62
+ case 'html':
63
+ case 'head':
64
+ case 'body':
65
+ case 'colgroup':
66
+ case 'caption':
67
+ return true;
68
+ case 'li':
69
+ case 'optgroup':
70
+ case 'tr':
71
+ return tag === optionalEndTag;
72
+ case 'dt':
73
+ case 'dd':
74
+ return descriptionElements.has(tag);
75
+ case 'p':
76
+ return pBlockElements.has(tag);
77
+ case 'rb':
78
+ case 'rt':
79
+ case 'rp':
80
+ return rubyEndTagOmission.has(tag);
81
+ case 'rtc':
82
+ return rubyRtcEndTagOmission.has(tag);
83
+ case 'option':
84
+ return optionElements.has(tag);
85
+ case 'thead':
86
+ case 'tbody':
87
+ return tableContentElements.has(tag);
88
+ case 'tfoot':
89
+ return tag === 'tbody';
90
+ case 'td':
91
+ case 'th':
92
+ return cellElements.has(tag);
93
+ }
94
+ return false;
95
+ }
96
+
97
+ // Element removal logic
98
+
99
+ /**
100
+ * @param {string} tag
101
+ * @param {HTMLAttribute[]} attrs
102
+ */
103
+ function canRemoveElement(tag, attrs) {
104
+ // Elements with `id` attribute must never be removed—they serve as:
105
+ // - Navigation targets (skip links, URL fragments)
106
+ // - JavaScript selector targets (`getElementById`, `querySelector`)
107
+ // - CSS targets (`:target` pseudo-class, ID selectors)
108
+ // - Accessibility landmarks (ARIA references)
109
+ // - Portal mount points (React portals, etc.)
110
+ if (hasAttrName('id', attrs)) {
111
+ return false;
112
+ }
113
+
114
+ switch (tag) {
115
+ case 'textarea':
116
+ return false;
117
+ case 'audio':
118
+ case 'script':
119
+ case 'video':
120
+ if (hasAttrName('src', attrs)) {
121
+ return false;
122
+ }
123
+ break;
124
+ case 'iframe':
125
+ if (hasAttrName('src', attrs) || hasAttrName('srcdoc', attrs)) {
126
+ return false;
127
+ }
128
+ break;
129
+ case 'object':
130
+ if (hasAttrName('data', attrs)) {
131
+ return false;
132
+ }
133
+ break;
134
+ case 'applet':
135
+ if (hasAttrName('code', attrs)) {
136
+ return false;
137
+ }
138
+ break;
139
+ }
140
+ return true;
141
+ }
142
+
143
+ /**
144
+ * @param {string} str - Tag name or HTML-like element spec (e.g., `td` or `<span aria-hidden='true'>`)
145
+ * @param {ProcessedOptions} options - Options object for name normalization
146
+ * @returns {{tag: string, attrs: Object.<string, string|undefined>|null}|null} Parsed spec or null if invalid
147
+ */
148
+ function parseElementSpec(str, options) {
149
+ if (typeof str !== 'string') {
150
+ return null;
151
+ }
152
+
153
+ const trimmed = str.trim();
154
+ if (!trimmed) {
155
+ return null;
156
+ }
157
+
158
+ // Simple tag name: `td`
159
+ if (!/[<>]/.test(trimmed)) {
160
+ return { tag: options.name(trimmed), attrs: null };
161
+ }
162
+
163
+ // HTML-like markup: `<span aria-hidden='true'>` or `<td></td>`
164
+ // Extract opening tag using regex
165
+ const match = trimmed.match(/^<([a-zA-Z][\w:-]*)((?:\s+[^>]*)?)>/);
166
+ if (!match) {
167
+ return null;
168
+ }
169
+
170
+ const tag = options.name(match[1] ?? '');
171
+ const attrString = match[2] ?? '';
172
+
173
+ if (!attrString.trim()) {
174
+ return { tag, attrs: null };
175
+ }
176
+
177
+ // Parse attributes from string
178
+ /** @type {{[key: string]: string | undefined}} */
179
+ const attrs = {};
180
+ const attrRegex = /([a-zA-Z][\w:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>/]+)))?/g;
181
+ let attrMatch;
182
+
183
+ while ((attrMatch = attrRegex.exec(attrString))) {
184
+ const attrName = options.name(attrMatch[1] ?? '');
185
+ const attrValue = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4];
186
+ // Boolean attributes have no value (undefined)
187
+ attrs[attrName] = attrValue;
188
+ }
189
+
190
+ return {
191
+ tag,
192
+ attrs: Object.keys(attrs).length > 0 ? attrs : null
193
+ };
194
+ }
195
+
196
+ /**
197
+ * @param {string[]} input - Array of element specifications from `removeEmptyElementsExcept` option
198
+ * @param {ProcessedOptions} options - Options object for parsing
199
+ * @returns {Array<{tag: string, attrs: Object.<string, string|undefined>|null}>} Array of parsed element specs
200
+ */
201
+ function parseRemoveEmptyElementsExcept(input, options) {
202
+ if (!Array.isArray(input)) {
203
+ return [];
204
+ }
205
+
206
+ return /** @type {Array<{tag: string, attrs: {[x: string]: string | undefined} | null}>} */ (input.map(item => {
207
+ if (typeof item === 'string') {
208
+ const spec = parseElementSpec(item, options);
209
+ if (!spec && options.log) {
210
+ options.log('Warning: Unable to parse `removeEmptyElementsExcept` specification: “' + item + '”');
211
+ }
212
+ return spec;
213
+ }
214
+ if (options.log) {
215
+ options.log('Warning: `removeEmptyElementsExcept` specification must be a string, received: ' + typeof item);
216
+ }
217
+ return null;
218
+ }).filter(Boolean));
219
+ }
220
+
221
+ /**
222
+ * @param {string} tag - Element tag name
223
+ * @param {HTMLAttribute[]} attrs - Array of element attributes
224
+ * @param {Array<{tag: string, attrs: Object.<string, string|undefined>|null}>} preserveList - Parsed preserve specs
225
+ * @returns {boolean} True if the empty element should be preserved
226
+ */
227
+ function shouldPreserveEmptyElement(tag, attrs, preserveList) {
228
+ for (const spec of preserveList) {
229
+ // Tag name must match
230
+ if (spec.tag !== tag) {
231
+ continue;
232
+ }
233
+
234
+ // If no attributes specified in spec, tag match is enough
235
+ if (!spec.attrs) {
236
+ return true;
237
+ }
238
+
239
+ // Check if all specified attributes match
240
+ const allAttrsMatch = Object.entries(spec.attrs).every(([name, value]) => {
241
+ const attr = attrs.find(a => a.name === name);
242
+ if (!attr) {
243
+ return false; // Attribute not present
244
+ }
245
+ // Boolean attribute in spec (undefined value) matches if attribute is present
246
+ if (value === undefined) {
247
+ return true;
248
+ }
249
+ // Valued attribute must match exactly
250
+ return attr.value === value;
251
+ });
252
+
253
+ if (allAttrsMatch) {
254
+ return true;
255
+ }
256
+ }
257
+
258
+ return false;
259
+ }
260
+
261
+ // Exports
262
+
263
+ export {
264
+ // Tag omission
265
+ canRemoveParentTag,
266
+ isStartTagMandatory,
267
+ canRemovePrecedingTag,
268
+
269
+ // Element removal
270
+ canRemoveElement,
271
+ parseElementSpec,
272
+ parseRemoveEmptyElementsExcept,
273
+ shouldPreserveEmptyElement
274
+ };
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Worker pool for whole files, as the CLI’s directory runs need them
3
+ *
4
+ * This pools one kind of work—read a file, minify it, write it—rather than arbitrary
5
+ * tasks: The worker body, the message contract, and the result are all about files. The
6
+ * spawning and queueing below would generalize, but nothing else asks for it yet.
7
+ *
8
+ * Minifying a document is CPU-bound work on one thread, so a run over a directory
9
+ * serializes no matter how the files are awaited. Whole files are the unit handed to
10
+ * workers, which is what makes threads pay here: A document takes long enough that the
11
+ * thread it crosses costs a fraction of a percent, and files share no state, so nothing
12
+ * travels but paths, options, and the resulting sizes.
13
+ *
14
+ * Scaling is bounded by what each thread has to re-learn rather than by the cores: Every
15
+ * worker runs its own isolate and warms up its own JIT, so the useful worker count tops
16
+ * out well short of the core count.
17
+ *
18
+ * Node-only: cli.js loads this module lazily and minifies in process wherever worker
19
+ * threads are unavailable or the options can’t cross a structured clone.
20
+ */
21
+
22
+ import fs from 'node:fs';
23
+ import { isMainThread, parentPort, workerData, Worker } from 'node:worker_threads';
24
+
25
+ // This module is its own worker entry point: The pool spawns it by URL and the branch
26
+ // below runs in the spawned copy. Keeping both halves in one file keeps the message
27
+ // contract in one place. The minifier is imported dynamically so that loading the
28
+ // pool on the main thread doesn’t drag it in; only workers ever pay for it.
29
+ if (!isMainThread && parentPort) {
30
+ const port = parentPort;
31
+ const { minify } = await import('../htmlminifier.js');
32
+ const { options, wantsLog } = workerData;
33
+
34
+ // The pool hands a worker one file at a time, so the file a diagnostic belongs to is
35
+ // simply the one in hand
36
+ let fileCurrent = '';
37
+
38
+ // `log` cannot cross a structured clone, so it is rebuilt here and forwarded, and only
39
+ // where the CLI has somewhere to put it. Whether the minifier logged an `Error` travels
40
+ // with the message: The CLI words those differently, and an error that crossed as a
41
+ // plain string would lose that wording.
42
+ const taskOptions = wantsLog
43
+ ? {
44
+ ...options,
45
+ log: (/** @type {unknown} */ message) => port.postMessage({
46
+ log: message instanceof Error ? message.message : String(message),
47
+ logIsError: message instanceof Error,
48
+ logFile: fileCurrent
49
+ })
50
+ }
51
+ : options;
52
+
53
+ port.on('message', async (/** @type {{id: number, inputFile: string, outputFile: string, dryRun: boolean}} */ task) => {
54
+ // Which step failed decides how the CLI words the failure, and reading and writing
55
+ // name different files
56
+ let stage = 'read';
57
+ try {
58
+ fileCurrent = task.inputFile;
59
+ const data = await fs.promises.readFile(task.inputFile, 'utf8');
60
+ stage = 'minify';
61
+ const minified = await minify(data, taskOptions);
62
+ if (!task.dryRun) {
63
+ stage = 'write';
64
+ await fs.promises.writeFile(task.outputFile, minified, 'utf8');
65
+ }
66
+ port.postMessage({
67
+ id: task.id,
68
+ originalSize: Buffer.byteLength(data, 'utf8'),
69
+ minifiedSize: Buffer.byteLength(minified, 'utf8')
70
+ });
71
+ } catch (err) {
72
+ port.postMessage({ id: task.id, stage, error: err instanceof Error ? err.message : String(err) });
73
+ }
74
+ });
75
+ }
76
+
77
+ const urlWorker = new URL(import.meta.url);
78
+
79
+ /**
80
+ * @param {object} args
81
+ * @param {import('../htmlminifier.js').MinifierOptions} args.options
82
+ * @param {number} args.size
83
+ * @param {((message: string, isError: boolean, file: string) => void) | undefined} [args.onLog]
84
+ */
85
+ export function createFilePool({ options, size, onLog }) {
86
+ /** @type {Worker[]} */
87
+ const workers = [];
88
+ /** @type {Worker[]} */
89
+ const idle = [];
90
+ /** @type {Map<number, {resolve: (value: {originalSize: number, minifiedSize: number}) => void, reject: (reason: Error) => void}>} */
91
+ const pending = new Map();
92
+ /** @type {{task: object, resolve: Function, reject: Function}[]} */
93
+ const queue = [];
94
+ let idNext = 0;
95
+ /** @type {Error | null} */
96
+ let failure = null;
97
+ let closing = false;
98
+ const wantsLog = Boolean(onLog);
99
+
100
+ // A worker that dies takes its task with it, and any task still queued would wait for a
101
+ // turn that never comes; both are failed at once so the run ends rather than hangs
102
+ const failAll = (/** @type {Error} */ err) => {
103
+ failure = err;
104
+ for (const { reject } of pending.values()) reject(err);
105
+ pending.clear();
106
+ for (const item of queue.splice(0)) item.reject(err);
107
+ };
108
+
109
+ for (let i = 0; i < size; i++) {
110
+ // Workers inherit the parent’s `execArgv`, which can carry flags that are invalid for
111
+ // a module worker and would kill it on startup
112
+ const worker = new Worker(urlWorker, { workerData: { options, wantsLog }, execArgv: [] });
113
+ worker.unref();
114
+ worker.on('message', (/** @type {{id?: number, log?: string, logIsError?: boolean, logFile?: string, error?: string, stage?: string, originalSize?: number, minifiedSize?: number}} */ message) => {
115
+ if (message.log !== undefined) {
116
+ onLog?.(message.log, Boolean(message.logIsError), message.logFile ?? '');
117
+ return;
118
+ }
119
+ const entry = pending.get(/** @type {number} */ (message.id));
120
+ pending.delete(/** @type {number} */ (message.id));
121
+ idle.push(worker);
122
+ if (!pending.size && !queue.length) worker.unref();
123
+ drain();
124
+ if (!entry) return;
125
+ if (message.error !== undefined) {
126
+ const err = new Error(message.error);
127
+ // Which step failed rides along so the CLI can word the failure as it does for a
128
+ // file it minified itself
129
+ if (message.stage) /** @type {any} */ (err).stage = message.stage;
130
+ entry.reject(err);
131
+ } else {
132
+ entry.resolve({ originalSize: message.originalSize ?? 0, minifiedSize: message.minifiedSize ?? 0 });
133
+ }
134
+ });
135
+ worker.on('error', failAll);
136
+ // A worker can also go without an `error`—killed for memory, or exiting on its own.
137
+ // Its tasks would then wait forever, so an exit before `close()` ends the run, too
138
+ worker.on('exit', (/** @type {number} */ code) => {
139
+ if (closing || failure) return;
140
+ const index = idle.indexOf(worker);
141
+ if (index !== -1) idle.splice(index, 1);
142
+ failAll(new Error(`Worker stopped unexpectedly (exit code ${code})`));
143
+ });
144
+ workers.push(worker);
145
+ idle.push(worker);
146
+ }
147
+
148
+ function drain() {
149
+ while (idle.length && queue.length) {
150
+ const worker = /** @type {Worker} */ (idle.pop());
151
+ const item = /** @type {{task: object, resolve: Function, reject: Function}} */ (queue.shift());
152
+ const id = idNext++;
153
+ pending.set(id, /** @type {any} */ ({ resolve: item.resolve, reject: item.reject }));
154
+ // Only a worker with something outstanding may hold the process open
155
+ worker.ref();
156
+ worker.postMessage({ ...item.task, id });
157
+ }
158
+ }
159
+
160
+ return {
161
+ /**
162
+ * @param {{inputFile: string, outputFile: string, dryRun: boolean}} task
163
+ * @returns {Promise<{originalSize: number, minifiedSize: number}>}
164
+ */
165
+ run(task) {
166
+ if (failure) return Promise.reject(failure);
167
+ return new Promise((resolve, reject) => {
168
+ queue.push({ task, resolve, reject });
169
+ drain();
170
+ });
171
+ },
172
+ async close() {
173
+ closing = true;
174
+ await Promise.all(workers.map(worker => worker.terminate()));
175
+ }
176
+ };
177
+ }