@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
|
@@ -0,0 +1,2294 @@
|
|
|
1
|
+
import { HTMLParser, endTag } from './htmlparser.js';
|
|
2
|
+
import TokenChain from './tokenchain.js';
|
|
3
|
+
import { presets, getPreset, getPresetNames } from './presets.js';
|
|
4
|
+
|
|
5
|
+
import { LRU, findTagEnd, identity, isThenable, lowercase, uniqueId } from './lib/utils.js';
|
|
6
|
+
import { collectUsedSymbols } from './lib/unused-css.js';
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
RE_LEGACY_ENTITIES,
|
|
10
|
+
RE_ESCAPE_LT,
|
|
11
|
+
RE_ESCAPE_LT_RAW_TEXT,
|
|
12
|
+
RE_HTML_ENCODING,
|
|
13
|
+
RE_WS_START,
|
|
14
|
+
RE_WS_END,
|
|
15
|
+
RE_WS_ONLY,
|
|
16
|
+
RE_WS_NBSP_END,
|
|
17
|
+
RE_STYLE_ELEMENT,
|
|
18
|
+
inlineElementsToKeepWhitespaceAround,
|
|
19
|
+
inlineElementsToKeepWhitespaceWithin,
|
|
20
|
+
specialContentElements,
|
|
21
|
+
rawTextElements,
|
|
22
|
+
htmlElements,
|
|
23
|
+
optionalStartTags,
|
|
24
|
+
optionalEndTags,
|
|
25
|
+
topLevelElements,
|
|
26
|
+
compactElements,
|
|
27
|
+
looseElements,
|
|
28
|
+
trailingElements,
|
|
29
|
+
pInlineElements
|
|
30
|
+
} from './lib/constants.js';
|
|
31
|
+
|
|
32
|
+
import {
|
|
33
|
+
trimWhitespace,
|
|
34
|
+
collapseWhitespaceAll,
|
|
35
|
+
collapseWhitespace,
|
|
36
|
+
collapseWhitespaceSmart,
|
|
37
|
+
canCollapseWhitespace as defaultCanCollapseWhitespace,
|
|
38
|
+
canTrimWhitespace as defaultCanTrimWhitespace
|
|
39
|
+
} from './lib/whitespace.js';
|
|
40
|
+
|
|
41
|
+
import {
|
|
42
|
+
isIgnoredComment,
|
|
43
|
+
isExecutableScript,
|
|
44
|
+
isStyleElement,
|
|
45
|
+
normalizeAttr,
|
|
46
|
+
buildAttr,
|
|
47
|
+
deduplicateAttributes
|
|
48
|
+
} from './lib/attributes.js';
|
|
49
|
+
|
|
50
|
+
import {
|
|
51
|
+
canRemoveParentTag,
|
|
52
|
+
isStartTagMandatory,
|
|
53
|
+
canRemovePrecedingTag,
|
|
54
|
+
canRemoveElement,
|
|
55
|
+
parseRemoveEmptyElementsExcept,
|
|
56
|
+
shouldPreserveEmptyElement
|
|
57
|
+
} from './lib/elements.js';
|
|
58
|
+
|
|
59
|
+
import {
|
|
60
|
+
hasJsonScriptType,
|
|
61
|
+
extractScriptBodies,
|
|
62
|
+
processScript
|
|
63
|
+
} from './lib/content.js';
|
|
64
|
+
|
|
65
|
+
import { processOptions } from './lib/options.js';
|
|
66
|
+
import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
67
|
+
|
|
68
|
+
/** @import { ProcessedOptions } from './lib/options.js' */
|
|
69
|
+
|
|
70
|
+
// Type definitions
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @typedef {Object} HTMLAttribute
|
|
74
|
+
* Representation of an attribute from the HTML parser.
|
|
75
|
+
* Internal counterpart: `HTMLAttribute` in lib/attributes.js—keep in sync.
|
|
76
|
+
*
|
|
77
|
+
* @prop {string} name
|
|
78
|
+
* @prop {string} [value]
|
|
79
|
+
* @prop {string} [quote]
|
|
80
|
+
* @prop {string} [customAssign]
|
|
81
|
+
* @prop {string} [customOpen]
|
|
82
|
+
* @prop {string} [customClose]
|
|
83
|
+
*/
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @typedef {Object} MinifierOptions
|
|
87
|
+
* Options that control how HTML is minified. All of these are optional
|
|
88
|
+
* and usually default to a disabled/safe value unless noted.
|
|
89
|
+
*
|
|
90
|
+
* @prop {(tag: string, attrs: HTMLAttribute[], canCollapseWhitespace: (tag: string) => boolean) => boolean} [canCollapseWhitespace]
|
|
91
|
+
* Predicate that determines whether whitespace inside a given element
|
|
92
|
+
* can be collapsed.
|
|
93
|
+
*
|
|
94
|
+
* Default: Built-in `canCollapseWhitespace` function
|
|
95
|
+
*
|
|
96
|
+
* @prop {(tag: string | null, attrs: HTMLAttribute[] | undefined, canTrimWhitespace: (tag: string) => boolean) => boolean} [canTrimWhitespace]
|
|
97
|
+
* Predicate that determines whether leading/trailing whitespace around
|
|
98
|
+
* the element may be trimmed.
|
|
99
|
+
*
|
|
100
|
+
* Default: Built-in `canTrimWhitespace` function
|
|
101
|
+
*
|
|
102
|
+
* @prop {number} [cacheCSS]
|
|
103
|
+
* The maximum number of entries for the CSS minification cache. Higher values
|
|
104
|
+
* improve performance for inputs with repeated CSS (e.g., batch processing).
|
|
105
|
+
* - Cache is created on first `minify()` call and persists for the process lifetime
|
|
106
|
+
* - Cache size is locked after first call—subsequent calls reuse the same cache
|
|
107
|
+
* - `0` switches the cache off; negative and non-finite values fall back to the default size
|
|
108
|
+
*
|
|
109
|
+
* Default: `500`
|
|
110
|
+
*
|
|
111
|
+
* @prop {number} [cacheJS]
|
|
112
|
+
* The maximum number of entries for the JavaScript minification cache. Higher
|
|
113
|
+
* values improve performance for inputs with repeated JavaScript.
|
|
114
|
+
* - Cache is created on first `minify()` call and persists for the process lifetime
|
|
115
|
+
* - Cache size is locked after first call—subsequent calls reuse the same cache
|
|
116
|
+
* - `0` switches the cache off; negative and non-finite values fall back to the default size
|
|
117
|
+
*
|
|
118
|
+
* Default: `500`
|
|
119
|
+
*
|
|
120
|
+
* @prop {number} [cacheSVG]
|
|
121
|
+
* The maximum number of entries for the SVG minification cache. Higher
|
|
122
|
+
* values improve performance for inputs with repeated SVG content.
|
|
123
|
+
* - Cache is created on first `minify()` call and persists for the process lifetime
|
|
124
|
+
* - Cache size is locked after first call—subsequent calls reuse the same cache
|
|
125
|
+
* - `0` switches the cache off; negative and non-finite values fall back to the default size
|
|
126
|
+
*
|
|
127
|
+
* Default: `500`
|
|
128
|
+
*
|
|
129
|
+
* @prop {boolean} [caseSensitive]
|
|
130
|
+
* When true, tag and attribute names are treated as case-sensitive.
|
|
131
|
+
* Useful for custom HTML tags.
|
|
132
|
+
* If false (default) names are lower-cased via the `name` function.
|
|
133
|
+
*
|
|
134
|
+
* Default: `false`
|
|
135
|
+
*
|
|
136
|
+
* @prop {boolean} [collapseAttributeWhitespace]
|
|
137
|
+
* Collapse multiple whitespace characters within attribute values into a
|
|
138
|
+
* single space. Also trims leading and trailing whitespace from attribute
|
|
139
|
+
* values. Applied as an early normalization step before special attribute
|
|
140
|
+
* handlers (CSS minification, class sorting, etc.) run.
|
|
141
|
+
*
|
|
142
|
+
* Default: `false`
|
|
143
|
+
*
|
|
144
|
+
* @prop {boolean} [collapseBooleanAttributes]
|
|
145
|
+
* Collapse boolean attributes to their name only (for example
|
|
146
|
+
* `disabled="disabled"` → `disabled`).
|
|
147
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#collapse_boolean_attributes
|
|
148
|
+
*
|
|
149
|
+
* Default: `false`
|
|
150
|
+
*
|
|
151
|
+
* @prop {boolean} [collapseInlineTagWhitespace]
|
|
152
|
+
* When false (default) whitespace around `inline` tags is preserved in
|
|
153
|
+
* more cases. When true, whitespace around inline tags may be collapsed.
|
|
154
|
+
* Must also enable `collapseWhitespace` to have effect.
|
|
155
|
+
*
|
|
156
|
+
* Default: `false`
|
|
157
|
+
*
|
|
158
|
+
* @prop {boolean} [collapseWhitespace]
|
|
159
|
+
* Collapse multiple whitespace characters into one where allowed. Also
|
|
160
|
+
* controls trimming behaviour in several code paths.
|
|
161
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#collapse_whitespace
|
|
162
|
+
*
|
|
163
|
+
* Default: `false`
|
|
164
|
+
*
|
|
165
|
+
* @prop {boolean} [conservativeCollapse]
|
|
166
|
+
* If true, be conservative when collapsing whitespace (preserve more
|
|
167
|
+
* whitespace in edge cases). Affects collapse algorithms.
|
|
168
|
+
* Must also enable `collapseWhitespace` to have effect.
|
|
169
|
+
*
|
|
170
|
+
* Default: `false`
|
|
171
|
+
*
|
|
172
|
+
* @prop {boolean} [continueOnMinifyError]
|
|
173
|
+
* When set to `false`, minification errors may throw.
|
|
174
|
+
* By default, the minifier will attempt to recover from minification
|
|
175
|
+
* errors, or ignore them and preserve the original content.
|
|
176
|
+
*
|
|
177
|
+
* Default: `true`
|
|
178
|
+
*
|
|
179
|
+
* @prop {boolean} [continueOnParseError]
|
|
180
|
+
* When true, the parser will attempt to continue on recoverable parse
|
|
181
|
+
* errors. Otherwise, parsing errors may throw.
|
|
182
|
+
*
|
|
183
|
+
* Default: `false`
|
|
184
|
+
*
|
|
185
|
+
* @prop {RegExp[]} [customAttrAssign]
|
|
186
|
+
* Array of regexes used to recognise custom attribute assignment
|
|
187
|
+
* operators (e.g., `'<div flex?="{{mode != cover}}"></div>'`).
|
|
188
|
+
* These are concatenated with the built-in assignment patterns.
|
|
189
|
+
*
|
|
190
|
+
* Default: `[]`
|
|
191
|
+
*
|
|
192
|
+
* @prop {RegExp} [customAttrCollapse]
|
|
193
|
+
* Regex matching attribute names whose values should be collapsed.
|
|
194
|
+
* Basically used to remove newlines and excess spaces inside attribute values,
|
|
195
|
+
* e.g., `/ng-class/`.
|
|
196
|
+
*
|
|
197
|
+
* @prop {[RegExp, RegExp][]} [customAttrSurround]
|
|
198
|
+
* Array of `[openRegExp, closeRegExp]` pairs used by the parser to
|
|
199
|
+
* detect custom attribute surround patterns (for non-standard syntaxes,
|
|
200
|
+
* e.g., `<input {{#if value}}checked="checked"{{/if}}>`).
|
|
201
|
+
*
|
|
202
|
+
* @prop {RegExp[]} [customEventAttributes]
|
|
203
|
+
* Array of regexes used to detect event handler attributes for `minifyJS`
|
|
204
|
+
* (e.g., `ng-click`). The default matches standard `on…` event attributes.
|
|
205
|
+
*
|
|
206
|
+
* Default: `[/^on[a-z]{3,}$/]`
|
|
207
|
+
*
|
|
208
|
+
* @prop {boolean} [strictCustomFragments]
|
|
209
|
+
* Rejects `ignoreCustomFragments` patterns that risk catastrophic backtracking,
|
|
210
|
+
* rather than warning about them: those that compound quantifiers or alternation
|
|
211
|
+
* (`(a+)+`, `(a|b)*`), those that repeat the same unbounded atom twice in a row
|
|
212
|
+
* (`.*.*`), and those too long or too deeply nested to analyze at all.
|
|
213
|
+
*
|
|
214
|
+
* Default: `false`
|
|
215
|
+
*
|
|
216
|
+
* @prop {boolean} [decodeEntities]
|
|
217
|
+
* When true, decodes HTML entities in text and attributes before
|
|
218
|
+
* processing, and re-encodes ambiguous ampersands when outputting.
|
|
219
|
+
*
|
|
220
|
+
* Default: `false`
|
|
221
|
+
*
|
|
222
|
+
*
|
|
223
|
+
* @prop {RegExp[]} [ignoreCustomComments]
|
|
224
|
+
* Comments matching any pattern in this array of regexes will be
|
|
225
|
+
* preserved when `removeComments` is enabled. The default preserves
|
|
226
|
+
* “bang” comments and comments starting with `#`.
|
|
227
|
+
*
|
|
228
|
+
* Default: `[/^!/, /^\s*#/]`
|
|
229
|
+
*
|
|
230
|
+
* @prop {RegExp[]} [ignoreCustomFragments]
|
|
231
|
+
* Array of regexes used to identify fragments that should be
|
|
232
|
+
* preserved (for example server templates). These fragments are temporarily
|
|
233
|
+
* replaced during minification to avoid corrupting template code.
|
|
234
|
+
* The default preserves ASP/PHP-style tags.
|
|
235
|
+
*
|
|
236
|
+
* Default: `[/<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/]`
|
|
237
|
+
*
|
|
238
|
+
* @prop {boolean} [includeAutoGeneratedTags]
|
|
239
|
+
* If false, tags marked as auto-generated by the parser will be omitted
|
|
240
|
+
* from output. Useful to skip injected tags.
|
|
241
|
+
*
|
|
242
|
+
* Default: `false`
|
|
243
|
+
*
|
|
244
|
+
* @prop {ArrayLike<string>} [inlineCustomElements]
|
|
245
|
+
* Collection of custom element tag names that should be treated as inline
|
|
246
|
+
* elements for white-space handling, alongside the built-in inline elements.
|
|
247
|
+
*
|
|
248
|
+
* Default: `[]`
|
|
249
|
+
*
|
|
250
|
+
* @prop {boolean} [keepClosingSlash]
|
|
251
|
+
* Keep the trailing slash on void elements and other start tags that carry one, and read it
|
|
252
|
+
* as closing the element. The default drops the slash and ignores it, as HTML does; in SVG
|
|
253
|
+
* and MathML a slash closes the element either way.
|
|
254
|
+
*
|
|
255
|
+
* Default: `false`
|
|
256
|
+
*
|
|
257
|
+
* @prop {(message: unknown) => void} [log]
|
|
258
|
+
* Logging function used by the minifier for warnings/errors/info.
|
|
259
|
+
* You can directly provide `console.log`, but `message` may also be an `Error`
|
|
260
|
+
* object or other non-string value.
|
|
261
|
+
*
|
|
262
|
+
* Default: `() => {}` (no-op function)
|
|
263
|
+
*
|
|
264
|
+
* @prop {number} [maxInputLength]
|
|
265
|
+
* The maximum allowed input length. Used as a guard against ReDoS via
|
|
266
|
+
* pathological inputs. If the input exceeds this length an error is
|
|
267
|
+
* thrown.
|
|
268
|
+
*
|
|
269
|
+
* Default: No limit
|
|
270
|
+
*
|
|
271
|
+
* @prop {number} [maxLineLength]
|
|
272
|
+
* Maximum line length for the output. When set the minifier will wrap
|
|
273
|
+
* output to the given number of characters where possible.
|
|
274
|
+
*
|
|
275
|
+
* Default: No limit
|
|
276
|
+
*
|
|
277
|
+
* @prop {boolean} [mergeScripts]
|
|
278
|
+
* When true, consecutive inline `<script>` elements are merged into one.
|
|
279
|
+
* Only merges compatible scripts (same `type`, matching `async`/`defer`/
|
|
280
|
+
* `nomodule`/`nonce` attributes). Does not merge external scripts (with `src`).
|
|
281
|
+
*
|
|
282
|
+
* Default: `false`
|
|
283
|
+
*
|
|
284
|
+
* @prop {boolean | Partial<import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>> | ((text: string, type?: string) => Promise<string> | string)} [minifyCSS]
|
|
285
|
+
* When true, enables CSS minification for inline `<style>` tags or
|
|
286
|
+
* `style` attributes. If an object is provided, it is passed to
|
|
287
|
+
* [Lightning CSS](https://www.npmjs.com/package/lightningcss)
|
|
288
|
+
* as transform options. If a function is provided, it will be used to perform
|
|
289
|
+
* custom CSS minification. If disabled, CSS is not minified.
|
|
290
|
+
*
|
|
291
|
+
* Default: `false`
|
|
292
|
+
*
|
|
293
|
+
* @prop {boolean | import("terser").MinifyOptions | {engine?: 'terser' | 'swc', [key: string]: any} | ((text: string, inline?: boolean) => Promise<string> | string)} [minifyJS]
|
|
294
|
+
* When true, enables JS minification for `<script>` contents and
|
|
295
|
+
* event handler attributes. If an object is provided, it can include:
|
|
296
|
+
* - `engine`: The minifier to use (`terser` or `swc`). Default: `terser`.
|
|
297
|
+
* Note: Inline event handlers (e.g., `onclick="…"`) always use Terser
|
|
298
|
+
* regardless of engine setting, as SWC doesn’t support bare return statements.
|
|
299
|
+
* - Engine-specific options (e.g., Terser options if `engine: 'terser'`,
|
|
300
|
+
* SWC options if `engine: 'swc'`).
|
|
301
|
+
* If a function is provided, it will be used to perform
|
|
302
|
+
* custom JS minification. If disabled, JS is not minified.
|
|
303
|
+
*
|
|
304
|
+
* Default: `false`
|
|
305
|
+
*
|
|
306
|
+
* @prop {boolean | string | {site?: string} | ((text: string) => Promise<string> | string)} [minifyURLs]
|
|
307
|
+
* When true, enables URL rewriting/minification. If an object is provided,
|
|
308
|
+
* the `site` property sets the base URL for computing relative paths.
|
|
309
|
+
* If a string is provided, it is treated as an `{ site: string }` options
|
|
310
|
+
* object. If a function is provided, it will be used to perform custom URL
|
|
311
|
+
* minification. If disabled, URLs are not minified.
|
|
312
|
+
*
|
|
313
|
+
* Default: `false`
|
|
314
|
+
*
|
|
315
|
+
* @prop {boolean | Object} [minifySVG]
|
|
316
|
+
* When true, enables SVG minification using [SVGO](https://github.com/svg/svgo).
|
|
317
|
+
* Complete SVG subtrees are extracted and optimized as a block.
|
|
318
|
+
* If an object is provided, it is passed to SVGO as configuration options.
|
|
319
|
+
* If disabled, SVG content is minified using standard HTML rules only.
|
|
320
|
+
*
|
|
321
|
+
* Default: `false`
|
|
322
|
+
*
|
|
323
|
+
* @prop {boolean} [noNewlinesBeforeTagClose]
|
|
324
|
+
* When wrapping lines, prevent inserting a newline directly before a
|
|
325
|
+
* closing tag (useful to keep tags like `</a>` on the same line).
|
|
326
|
+
*
|
|
327
|
+
* Default: `false`
|
|
328
|
+
*
|
|
329
|
+
* @prop {boolean} [partialMarkup]
|
|
330
|
+
* When true, treat input as a partial HTML fragment rather than a complete
|
|
331
|
+
* document. This preserves stray end tags (closing tags without corresponding
|
|
332
|
+
* opening tags) and prevents auto-closing of unclosed tags at the end of input.
|
|
333
|
+
* Useful for minifying template fragments, SSI includes, or other partial HTML
|
|
334
|
+
* that will be combined with other fragments.
|
|
335
|
+
*
|
|
336
|
+
* Default: `false`
|
|
337
|
+
*
|
|
338
|
+
* @prop {boolean} [preserveLineBreaks]
|
|
339
|
+
* Preserve a single line break at the start/end of text nodes when
|
|
340
|
+
* collapsing/trimming whitespace.
|
|
341
|
+
* Must also enable `collapseWhitespace` to have effect.
|
|
342
|
+
*
|
|
343
|
+
* Default: `false`
|
|
344
|
+
*
|
|
345
|
+
* @prop {string} [preset]
|
|
346
|
+
* Name of a preset configuration to use as a base (`conservative` or
|
|
347
|
+
* `comprehensive`). Explicitly provided options take precedence over
|
|
348
|
+
* preset values. Unknown preset names are ignored (with a warning).
|
|
349
|
+
*
|
|
350
|
+
* Default: No preset
|
|
351
|
+
*
|
|
352
|
+
* @prop {boolean} [preventAttributesEscaping]
|
|
353
|
+
* When true, attribute values will not be HTML-escaped (dangerous for
|
|
354
|
+
* untrusted input). By default, attributes are escaped.
|
|
355
|
+
*
|
|
356
|
+
* Default: `false`
|
|
357
|
+
*
|
|
358
|
+
* @prop {string[]} [processScripts]
|
|
359
|
+
* Array of `type` attribute values for `<script>` elements whose contents
|
|
360
|
+
* should be processed as HTML
|
|
361
|
+
* (e.g., `text/ng-template`, `text/x-handlebars-template`, etc.).
|
|
362
|
+
* When present, the contents of matching script tags are recursively minified,
|
|
363
|
+
* like normal HTML content.
|
|
364
|
+
*
|
|
365
|
+
* Default: `[]`
|
|
366
|
+
*
|
|
367
|
+
* @prop {"\"" | "'"} [quoteCharacter]
|
|
368
|
+
* Preferred quote character for attribute values. If unspecified the
|
|
369
|
+
* minifier picks the safest quote based on the attribute value.
|
|
370
|
+
*
|
|
371
|
+
* Default: Auto-detected
|
|
372
|
+
*
|
|
373
|
+
* @prop {boolean} [removeAttributeQuotes]
|
|
374
|
+
* Remove quotes around attribute values where it is safe to do so.
|
|
375
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_attribute_quotes
|
|
376
|
+
*
|
|
377
|
+
* Default: `false`
|
|
378
|
+
*
|
|
379
|
+
* @prop {boolean} [removeComments]
|
|
380
|
+
* Remove HTML comments. Comments that match `ignoreCustomComments` will
|
|
381
|
+
* still be preserved.
|
|
382
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_comments
|
|
383
|
+
*
|
|
384
|
+
* Default: `false`
|
|
385
|
+
*
|
|
386
|
+
* @prop {boolean} [removeDefaultTypeAttributes]
|
|
387
|
+
* Remove default `type` attributes from `<style>`/`<link>` (e.g., `type="text/css"`)
|
|
388
|
+
* and `<script>` (e.g., `type="text/javascript"`) elements.
|
|
389
|
+
*
|
|
390
|
+
* Default: `false`
|
|
391
|
+
*
|
|
392
|
+
* @prop {boolean | ((attrName: string, tag: string) => boolean)} [removeEmptyAttributes]
|
|
393
|
+
* If true, removes attributes whose values are empty (some attributes
|
|
394
|
+
* are excluded by name). Can also be a function to customise which empty
|
|
395
|
+
* attributes are removed.
|
|
396
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_or_blank_attributes
|
|
397
|
+
*
|
|
398
|
+
* Default: `false`
|
|
399
|
+
*
|
|
400
|
+
* @prop {boolean} [removeEmptyElements]
|
|
401
|
+
* Remove elements that are empty and safe to remove (for example
|
|
402
|
+
* `<script />` without `src`).
|
|
403
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_elements
|
|
404
|
+
*
|
|
405
|
+
* Default: `false`
|
|
406
|
+
*
|
|
407
|
+
* @prop {string[]} [removeEmptyElementsExcept]
|
|
408
|
+
* Specifies empty elements to preserve when `removeEmptyElements` is enabled.
|
|
409
|
+
* Has no effect unless `removeEmptyElements: true`.
|
|
410
|
+
*
|
|
411
|
+
* Accepts tag names or HTML-like element specifications:
|
|
412
|
+
*
|
|
413
|
+
* * Tag name only: `["td", "span"]`—preserves all empty elements of these types
|
|
414
|
+
* * With valued attributes: `["<span aria-hidden='true'>"]`—preserves only when attribute values match
|
|
415
|
+
* * With boolean attributes: `["<input disabled>"]`—preserves only when boolean attribute is present
|
|
416
|
+
* * Mixed: `["<button type='button' disabled>"]`—all specified attributes must match
|
|
417
|
+
*
|
|
418
|
+
* Attribute matching:
|
|
419
|
+
*
|
|
420
|
+
* * All specified attributes must be present and match (valued attributes must have exact values)
|
|
421
|
+
* * Additional attributes on the element are allowed
|
|
422
|
+
* * Attribute name matching respects the `caseSensitive` option
|
|
423
|
+
* * Supports double quotes, single quotes, and unquoted attribute values in specifications
|
|
424
|
+
*
|
|
425
|
+
* Limitations:
|
|
426
|
+
*
|
|
427
|
+
* * Self-closing syntax (e.g., `["<span/>"]`) is not supported; use `["span"]` instead
|
|
428
|
+
* * Definitions containing `>` within quoted attribute values (e.g., `["<span title='a>b'>"]`) are not supported
|
|
429
|
+
*
|
|
430
|
+
* Default: `[]`
|
|
431
|
+
*
|
|
432
|
+
* @prop {boolean} [removeOptionalTags]
|
|
433
|
+
* Drop optional start/end tags where the HTML specification permits it
|
|
434
|
+
* (for example `</li>`, optional `<html>` etc.).
|
|
435
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_optional_tags
|
|
436
|
+
*
|
|
437
|
+
* Default: `false`
|
|
438
|
+
*
|
|
439
|
+
* @prop {boolean} [removeRedundantAttributes]
|
|
440
|
+
* Remove attributes that are redundant because they match the element’s
|
|
441
|
+
* default values (for example `<button type="submit">`).
|
|
442
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_redundant_attributes
|
|
443
|
+
*
|
|
444
|
+
* Default: `false`
|
|
445
|
+
*
|
|
446
|
+
* @prop {boolean} [removeTagWhitespace]
|
|
447
|
+
* **Note that this will result in invalid HTML!**
|
|
448
|
+
*
|
|
449
|
+
* When true, extra whitespace between tag name and attributes (or before
|
|
450
|
+
* the closing bracket) will be removed where possible. Affects output spacing
|
|
451
|
+
* such as the space used in the short doctype representation.
|
|
452
|
+
*
|
|
453
|
+
* Default: `false`
|
|
454
|
+
*
|
|
455
|
+
* @prop {boolean | {safelist?: Array<string | RegExp>, scripts?: boolean}} [removeUnusedCSS]
|
|
456
|
+
* **Note that this can change how a document renders!**
|
|
457
|
+
*
|
|
458
|
+
* Remove rules from `style` elements whose class or ID selectors the document
|
|
459
|
+
* never references. Requires `minifyCSS` (removal runs through Lightning CSS)
|
|
460
|
+
* and has no effect on `style` or `media` attributes.
|
|
461
|
+
*
|
|
462
|
+
* Class names and IDs are collected from the markup, from `data-*` attributes,
|
|
463
|
+
* and—unless `scripts` is set to `false`—from inline `script` elements. Names
|
|
464
|
+
* that only ever appear in external scripts cannot be detected; list those
|
|
465
|
+
* under `safelist` (strings or regular expressions) to keep them.
|
|
466
|
+
*
|
|
467
|
+
* Default: `false`
|
|
468
|
+
*
|
|
469
|
+
* @prop {boolean | ((tag: string, attrs: HTMLAttribute[]) => void)} [sortAttributes]
|
|
470
|
+
* When true, enables sorting of attributes. If a function is provided it
|
|
471
|
+
* will be used as a custom attribute sorter, which should mutate `attrs`
|
|
472
|
+
* in-place to the desired order. If disabled, the minifier will attempt to
|
|
473
|
+
* preserve the order from the input.
|
|
474
|
+
*
|
|
475
|
+
* Default: `false`
|
|
476
|
+
*
|
|
477
|
+
* @prop {boolean | ((value: string) => string)} [sortClassNames]
|
|
478
|
+
* When true, enables sorting of class names inside `class` attributes.
|
|
479
|
+
* If a function is provided, it will be used to transform/sort the class
|
|
480
|
+
* name string. If disabled, the minifier will attempt to preserve the
|
|
481
|
+
* class-name order from the input.
|
|
482
|
+
*
|
|
483
|
+
* Default: `false`
|
|
484
|
+
*
|
|
485
|
+
* @prop {boolean} [trimCustomFragments]
|
|
486
|
+
* When true, whitespace around ignored custom fragments may be trimmed
|
|
487
|
+
* more aggressively. This affects how preserved fragments interact with
|
|
488
|
+
* surrounding whitespace collapse.
|
|
489
|
+
*
|
|
490
|
+
* Default: `false`
|
|
491
|
+
*
|
|
492
|
+
* @prop {boolean} [useShortDoctype]
|
|
493
|
+
* Replace the HTML doctype with the short `<!doctype html>` form.
|
|
494
|
+
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#use_short_doctype
|
|
495
|
+
*
|
|
496
|
+
* Default: `false`
|
|
497
|
+
*/
|
|
498
|
+
|
|
499
|
+
// Lazy-load heavy dependencies only when needed
|
|
500
|
+
|
|
501
|
+
/** @type {Promise<Function> | undefined} */
|
|
502
|
+
let lightningCSSPromise;
|
|
503
|
+
async function getLightningCSS() {
|
|
504
|
+
if (!lightningCSSPromise) {
|
|
505
|
+
lightningCSSPromise = import('lightningcss').then(m => m.transform);
|
|
506
|
+
}
|
|
507
|
+
return lightningCSSPromise;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** @type {Promise<Function> | undefined} */
|
|
511
|
+
let terserPromise;
|
|
512
|
+
async function getTerser() {
|
|
513
|
+
if (!terserPromise) {
|
|
514
|
+
terserPromise = import('terser').then(m => m.minify);
|
|
515
|
+
}
|
|
516
|
+
return terserPromise;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** @type {Promise<any> | undefined} */
|
|
520
|
+
let swcPromise;
|
|
521
|
+
async function getSwc() {
|
|
522
|
+
if (!swcPromise) {
|
|
523
|
+
swcPromise = import('@swc/core')
|
|
524
|
+
.then(m => m.default || m)
|
|
525
|
+
.catch(() => {
|
|
526
|
+
throw new Error(
|
|
527
|
+
'The swc minifier requires @swc/core to be installed.\n' +
|
|
528
|
+
'Install it with: npm install @swc/core'
|
|
529
|
+
);
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
return swcPromise;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** @type {Promise<Function> | undefined} */
|
|
536
|
+
let svgoPromise;
|
|
537
|
+
async function getSvgo() {
|
|
538
|
+
if (!svgoPromise) {
|
|
539
|
+
svgoPromise = import('svgo').then(m => m.optimize);
|
|
540
|
+
}
|
|
541
|
+
return svgoPromise;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** @type {Promise<Function> | undefined} */
|
|
545
|
+
let decodeHTMLPromise;
|
|
546
|
+
async function getDecodeHTML() {
|
|
547
|
+
if (!decodeHTMLPromise) {
|
|
548
|
+
decodeHTMLPromise = import('entities').then(m => m.decodeHTML);
|
|
549
|
+
}
|
|
550
|
+
return decodeHTMLPromise;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Minification caches (initialized on first use with configurable sizes)
|
|
554
|
+
/** @type {LRU | null} */
|
|
555
|
+
let cssMinifyCache = null;
|
|
556
|
+
/** @type {LRU | null} */
|
|
557
|
+
let jsMinifyCache = null;
|
|
558
|
+
/** @type {LRU | null} */
|
|
559
|
+
let svgMinifyCache = null;
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* @typedef {Object} CacheStats
|
|
563
|
+
* Hit/miss statistics and current occupancy for a single minification cache.
|
|
564
|
+
*
|
|
565
|
+
* @prop {number} gets Number of lookups attempted against the cache.
|
|
566
|
+
* @prop {number} hits Number of lookups that found a cached entry.
|
|
567
|
+
* @prop {number} size Number of entries currently held in the cache.
|
|
568
|
+
* @prop {number} limit Maximum number of entries the cache can hold.
|
|
569
|
+
*/
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* @param {LRU | null} cache
|
|
573
|
+
* @returns {CacheStats}
|
|
574
|
+
*/
|
|
575
|
+
const cacheStatsOrEmpty = (cache) => cache ? cache.stats() : { gets: 0, hits: 0, size: 0, limit: 0 };
|
|
576
|
+
|
|
577
|
+
// Pre-compiled patterns for script merging (avoid repeated allocation in hot path)
|
|
578
|
+
const RE_SCRIPT_ATTRS = /([^\s=]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
|
579
|
+
const RE_SCRIPT_OPEN = /<script(?=[\s>])/gi; // Finds tag start; use `findTagEnd()` for the actual closing `>`
|
|
580
|
+
const RE_SCRIPT_CLOSE = /<\/script\s*>/gi;
|
|
581
|
+
const SCRIPT_BOOL_ATTRS = new Set(['async', 'defer', 'nomodule']);
|
|
582
|
+
const DEFAULT_JS_TYPES = new Set(['', 'text/javascript', 'application/javascript']);
|
|
583
|
+
|
|
584
|
+
// Pre-compiled patterns for buffer scanning
|
|
585
|
+
const RE_START_TAG = /^<[^/!]/;
|
|
586
|
+
const RE_END_TAG = /^<\//;
|
|
587
|
+
const RE_WHITESPACE_ONLY = /^\s+$/;
|
|
588
|
+
const RE_TRAILING_WHITESPACE = /\s$/;
|
|
589
|
+
|
|
590
|
+
// Pre-compiled patterns for `htmlmin:ignore` block content analysis
|
|
591
|
+
const RE_HTML_COMMENT_START = /^\s*<!--/;
|
|
592
|
+
const RE_CLOSING_TAG_START = /^\s*<\/([a-zA-Z][\w:-]*)/;
|
|
593
|
+
const RE_LAST_HTML_TAG = /[\s\S]*<(\/?[a-zA-Z][\w:-]*)/;
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
// Probe for SVG/MathML elements—when the input has none (the common case),
|
|
597
|
+
// the per-tag foreign-content machinery can be skipped entirely
|
|
598
|
+
const RE_FOREIGN_ELEMENT_PROBE = /<(?:svg|math)[\s/>]/i;
|
|
599
|
+
|
|
600
|
+
// Script merging
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Merge consecutive inline script tags into one (`mergeConsecutiveScripts`).
|
|
604
|
+
* Only merges scripts that are compatible:
|
|
605
|
+
* - Both inline (no `src` attribute)
|
|
606
|
+
* - Same `type` (or both default JavaScript)
|
|
607
|
+
* - No conflicting attributes (`async`, `defer`, `nomodule`, different `nonce`)
|
|
608
|
+
*
|
|
609
|
+
* Uses a scanner rather than a regex to locate script boundaries, so literal
|
|
610
|
+
* `</script>` strings inside script content are handled correctly per the HTML
|
|
611
|
+
* spec (raw text ends at the first `</script>`).
|
|
612
|
+
*
|
|
613
|
+
* Single forward pass: Each script absorbs all directly following compatible
|
|
614
|
+
* scripts, and the output is assembled from segments—this avoids rebuilding
|
|
615
|
+
* the full string and restarting the scan after every merge (O(n²) on inputs
|
|
616
|
+
* with many merges). Merges can’t cascade backwards: compatibility depends
|
|
617
|
+
* only on the attributes of the first script in a chain, which merging
|
|
618
|
+
* preserves, so one pass finds every merge the iterated rescan found.
|
|
619
|
+
*
|
|
620
|
+
* @param {string} html - The HTML string to process
|
|
621
|
+
* @returns {string} HTML with consecutive scripts merged
|
|
622
|
+
*/
|
|
623
|
+
function mergeConsecutiveScripts(html) {
|
|
624
|
+
// Parse an attribute string into a name→value map
|
|
625
|
+
const parseAttrs = (/** @type {string} */ attrStr) => {
|
|
626
|
+
/** @type {Record<string, string>} */
|
|
627
|
+
const attrs = {};
|
|
628
|
+
RE_SCRIPT_ATTRS.lastIndex = 0;
|
|
629
|
+
let m;
|
|
630
|
+
while ((m = RE_SCRIPT_ATTRS.exec(attrStr)) !== null) {
|
|
631
|
+
const name = (m[1] ?? '').toLowerCase();
|
|
632
|
+
const value = m[2] ?? m[3] ?? m[4] ?? '';
|
|
633
|
+
attrs[name] = value;
|
|
634
|
+
}
|
|
635
|
+
return attrs;
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
/** @type {string[]} */
|
|
639
|
+
const segments = [];
|
|
640
|
+
let consumedPos = 0; // Start of the input region not yet copied to `segments`
|
|
641
|
+
|
|
642
|
+
RE_SCRIPT_OPEN.lastIndex = 0;
|
|
643
|
+
let m1;
|
|
644
|
+
|
|
645
|
+
while ((m1 = RE_SCRIPT_OPEN.exec(html)) !== null) {
|
|
646
|
+
// Use findTagEnd() to get the real closing '>', skipping quoted attribute values
|
|
647
|
+
const tagEnd1 = findTagEnd(html, m1.index + 7);
|
|
648
|
+
if (tagEnd1 === -1) break;
|
|
649
|
+
|
|
650
|
+
const attrs1Str = html.slice(m1.index + 7, tagEnd1);
|
|
651
|
+
|
|
652
|
+
// Find end of this script’s content (first `</script>`—per HTML spec, raw text ends here)
|
|
653
|
+
RE_SCRIPT_CLOSE.lastIndex = tagEnd1 + 1;
|
|
654
|
+
const close1 = RE_SCRIPT_CLOSE.exec(html);
|
|
655
|
+
if (!close1) break;
|
|
656
|
+
|
|
657
|
+
let mergedContent = html.slice(tagEnd1 + 1, close1.index);
|
|
658
|
+
let afterClose = close1.index + close1[0].length;
|
|
659
|
+
|
|
660
|
+
const a1 = parseAttrs(attrs1Str);
|
|
661
|
+
// `src` (external) and non-default types (modules, JSON, etc.) must not be merged:
|
|
662
|
+
// module scripts have per-script lexical scope, and non-JS content (e.g., JSON)
|
|
663
|
+
// is not concatenable; even identical non-JS types are incompatible
|
|
664
|
+
const mergeable = !('src' in a1) && DEFAULT_JS_TYPES.has((a1.type || '').toLowerCase());
|
|
665
|
+
let mergedAny = false;
|
|
666
|
+
|
|
667
|
+
// Absorb all directly following compatible scripts
|
|
668
|
+
while (mergeable) {
|
|
669
|
+
// Skip optional whitespace and check for a consecutive <script> tag
|
|
670
|
+
let i = afterClose;
|
|
671
|
+
while (i < html.length && (html[i] === ' ' || html[i] === '\t' || html[i] === '\n' || html[i] === '\r' || html[i] === '\f')) i++;
|
|
672
|
+
if (html.slice(i, i + 7).toLowerCase() !== '<script' || (html.charAt(i + 7) !== '>' && !/\s/.test(html.charAt(i + 7)))) break;
|
|
673
|
+
|
|
674
|
+
const tagEnd2 = findTagEnd(html, i + 7);
|
|
675
|
+
if (tagEnd2 === -1) break;
|
|
676
|
+
|
|
677
|
+
const attrs2Str = html.slice(i + 7, tagEnd2);
|
|
678
|
+
|
|
679
|
+
// Find end of the following script’s content
|
|
680
|
+
RE_SCRIPT_CLOSE.lastIndex = tagEnd2 + 1;
|
|
681
|
+
const close2 = RE_SCRIPT_CLOSE.exec(html);
|
|
682
|
+
if (!close2) break;
|
|
683
|
+
|
|
684
|
+
const a2 = parseAttrs(attrs2Str);
|
|
685
|
+
|
|
686
|
+
// Check compatibility: No `src`, default JS type, no conflicting boolean
|
|
687
|
+
// attributes, and `nonce` must be same or both absent
|
|
688
|
+
if ('src' in a2 || !DEFAULT_JS_TYPES.has((a2.type || '').toLowerCase())) break;
|
|
689
|
+
let boolConflict = false;
|
|
690
|
+
for (const attr of SCRIPT_BOOL_ATTRS) {
|
|
691
|
+
if ((attr in a1) !== (attr in a2)) { boolConflict = true; break; }
|
|
692
|
+
}
|
|
693
|
+
if (boolConflict || a1.nonce !== a2.nonce) break;
|
|
694
|
+
|
|
695
|
+
// Scripts are compatible—combine content: Use semicolon normally,
|
|
696
|
+
// newline only for trailing `//` comments
|
|
697
|
+
const content2 = html.slice(tagEnd2 + 1, close2.index);
|
|
698
|
+
const c1 = mergedContent.trim();
|
|
699
|
+
const c2 = content2.trim();
|
|
700
|
+
if (c1 && c2) {
|
|
701
|
+
// Check if last line of c1 contains `//` (single-line comment)
|
|
702
|
+
// If so, use newline to terminate it; otherwise use semicolon (if not already present)
|
|
703
|
+
const lastLine = c1.slice(c1.lastIndexOf('\n') + 1);
|
|
704
|
+
const separator = lastLine.includes('//') ? '\n' : (c1.endsWith(';') ? '' : ';');
|
|
705
|
+
mergedContent = c1 + separator + c2;
|
|
706
|
+
} else {
|
|
707
|
+
mergedContent = c1 || c2;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
afterClose = close2.index + close2[0].length;
|
|
711
|
+
mergedAny = true;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
if (mergedAny) {
|
|
715
|
+
// Use first script’s attributes (they are compatible)
|
|
716
|
+
segments.push(html.slice(consumedPos, m1.index), `<script${attrs1Str}>${mergedContent}</script>`);
|
|
717
|
+
consumedPos = afterClose;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// Continue scanning after this script (skips `<script` occurrences inside content)
|
|
721
|
+
RE_SCRIPT_OPEN.lastIndex = afterClose;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
if (!segments.length) return html;
|
|
725
|
+
segments.push(html.slice(consumedPos));
|
|
726
|
+
return segments.join('');
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* @param {string} value
|
|
731
|
+
* @param {ProcessedOptions} options
|
|
732
|
+
* @param {string} uidIgnore
|
|
733
|
+
* @param {string} uidAttr
|
|
734
|
+
* @param {string[]} ignoredMarkupChunks
|
|
735
|
+
*/
|
|
736
|
+
async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupChunks) {
|
|
737
|
+
const attrChains = options.sortAttributes && typeof options.sortAttributes !== 'function' && Object.create(null);
|
|
738
|
+
const classChain = options.sortClassNames && typeof options.sortClassNames !== 'function' && new TokenChain();
|
|
739
|
+
const resolveName = options.name;
|
|
740
|
+
|
|
741
|
+
function attrNames(/** @type {HTMLAttribute[]} */ attrs) {
|
|
742
|
+
return attrs.map(function (attr) {
|
|
743
|
+
return resolveName(attr.name);
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function shouldSkipUID(/** @type {string} */ token, /** @type {string} */ uid) {
|
|
748
|
+
return !uid || token.indexOf(uid) === -1;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function shouldKeepToken(/** @type {string} */ token) {
|
|
752
|
+
// Filter out any HTML comment tokens (UID placeholders)
|
|
753
|
+
// These are temporary markers created by `htmlmin:ignore` and `ignoreCustomFragments`
|
|
754
|
+
if (token.startsWith('<!--') && token.endsWith('-->')) {
|
|
755
|
+
return false;
|
|
756
|
+
}
|
|
757
|
+
return shouldSkipUID(token, uidIgnore) && shouldSkipUID(token, uidAttr);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// Pre-compile regex patterns for reuse (performance optimization)
|
|
761
|
+
// These must be declared before `scan()` since scan uses them
|
|
762
|
+
const whitespaceSplitPatternScan = /[ \t\n\f\r]+/;
|
|
763
|
+
const whitespaceSplitPatternSort = /[ \n\f\r]+/;
|
|
764
|
+
|
|
765
|
+
async function scan(/** @type {string} */ input) {
|
|
766
|
+
/** @type {string} */
|
|
767
|
+
let currentTag;
|
|
768
|
+
/** @type {string | undefined} */
|
|
769
|
+
let currentType;
|
|
770
|
+
const parser = new HTMLParser(input, {
|
|
771
|
+
start: function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ unary) {
|
|
772
|
+
if (attrChains) {
|
|
773
|
+
if (!attrChains[tag]) {
|
|
774
|
+
attrChains[tag] = new TokenChain();
|
|
775
|
+
}
|
|
776
|
+
const attrNamesList = attrNames(attrs).filter(shouldKeepToken);
|
|
777
|
+
attrChains[tag].add(attrNamesList);
|
|
778
|
+
}
|
|
779
|
+
for (const attr of attrs) {
|
|
780
|
+
if (classChain && attr.value && resolveName(attr.name) === 'class') {
|
|
781
|
+
const classes = trimWhitespace(attr.value).split(whitespaceSplitPatternScan).filter(shouldKeepToken);
|
|
782
|
+
classChain.add(classes);
|
|
783
|
+
} else if (options.processScripts && attr.name.toLowerCase() === 'type') {
|
|
784
|
+
currentTag = tag;
|
|
785
|
+
currentType = attr.value;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
// As on the main path: What a unary tag holds ends with the tag, so no text can belong to it
|
|
789
|
+
if (unary) {
|
|
790
|
+
currentTag = '';
|
|
791
|
+
currentType = undefined;
|
|
792
|
+
}
|
|
793
|
+
},
|
|
794
|
+
end: function () {
|
|
795
|
+
currentTag = '';
|
|
796
|
+
},
|
|
797
|
+
chars: async function (/** @type {string} */ text) {
|
|
798
|
+
// Only recursively scan HTML content, not JSON-LD or other non-HTML script types
|
|
799
|
+
// `scan()` is for analyzing HTML attribute order, not for parsing JSON
|
|
800
|
+
if (options.processScripts && specialContentElements.has(currentTag) &&
|
|
801
|
+
options.processScripts.indexOf(currentType ?? '') > -1 &&
|
|
802
|
+
currentType === 'text/html') {
|
|
803
|
+
await scan(text);
|
|
804
|
+
}
|
|
805
|
+
},
|
|
806
|
+
// No need for `nextTag` information in this scan
|
|
807
|
+
wantsNextTag: false,
|
|
808
|
+
// Continue on parse errors during analysis pass
|
|
809
|
+
continueOnParseError: options.continueOnParseError,
|
|
810
|
+
selfClosingSlash: options.keepClosingSlash
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
try {
|
|
814
|
+
await parser.parse();
|
|
815
|
+
} catch (err) {
|
|
816
|
+
// If parsing fails during analysis pass, skip it—there’s partial frequency data from what can be parsed
|
|
817
|
+
if (!options.continueOnParseError) {
|
|
818
|
+
throw err;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// For the first pass, create a copy of options and disable aggressive minification.
|
|
824
|
+
// Keep attribute transformations (like `removeDefaultTypeAttributes`) for accurate analysis.
|
|
825
|
+
// This is safe because `createSortFns` is called before custom fragment UID markers (`uidAttr`) are added.
|
|
826
|
+
// Note: `htmlmin:ignore` UID markers (`uidIgnore`) already exist and are expanded for analysis.
|
|
827
|
+
const firstPassOptions = Object.assign({}, options, {
|
|
828
|
+
// Disable sorting for the analysis pass
|
|
829
|
+
sortAttributes: false,
|
|
830
|
+
sortClassNames: false,
|
|
831
|
+
// Disable aggressive minification that doesn’t affect attribute analysis
|
|
832
|
+
collapseWhitespace: false,
|
|
833
|
+
removeAttributeQuotes: false,
|
|
834
|
+
removeTagWhitespace: false,
|
|
835
|
+
decodeEntities: false,
|
|
836
|
+
processScripts: false,
|
|
837
|
+
// Keep `ignoreCustomFragments` to handle template syntax correctly
|
|
838
|
+
// Continue on parse errors during analysis (e.g., template syntax)
|
|
839
|
+
continueOnParseError: true,
|
|
840
|
+
log: identity
|
|
841
|
+
});
|
|
842
|
+
|
|
843
|
+
// Temporarily enable `continueOnParseError` for the `scan()` function call below.
|
|
844
|
+
// Note: `firstPassOptions` already has `continueOnParseError: true` for the `minifyHTML` call.
|
|
845
|
+
const originalContinueOnParseError = options.continueOnParseError;
|
|
846
|
+
options.continueOnParseError = true;
|
|
847
|
+
|
|
848
|
+
// Pre-compile the UID replacement pattern, and read the fragments the way the
|
|
849
|
+
// main path does, so each keeps its own flags
|
|
850
|
+
const uidReplacePattern = uidIgnore && ignoredMarkupChunks
|
|
851
|
+
? new RegExp('<!--' + uidIgnore + '(\\d+)-->', 'g')
|
|
852
|
+
: null;
|
|
853
|
+
const customFragments = (options.ignoreCustomFragments || []).map(toFragment);
|
|
854
|
+
|
|
855
|
+
try {
|
|
856
|
+
// Expand UID tokens back to the original content for frequency analysis
|
|
857
|
+
let expandedValue = value;
|
|
858
|
+
if (uidReplacePattern) {
|
|
859
|
+
expandedValue = value.replace(uidReplacePattern, function (/** @type {string} */ _match, /** @type {string} */ index) {
|
|
860
|
+
return ignoredMarkupChunks[+index] || '';
|
|
861
|
+
});
|
|
862
|
+
// Reset `lastIndex` for pattern reuse
|
|
863
|
+
uidReplacePattern.lastIndex = 0;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// First pass minification applies attribute transformations like `removeDefaultTypeAttributes` for accurate frequency analysis
|
|
867
|
+
const firstPassOutput = await minifyHTML(expandedValue, firstPassOptions);
|
|
868
|
+
|
|
869
|
+
// For frequency analysis, remove custom fragments temporarily
|
|
870
|
+
// because HTML comments in opening tags prevent proper attribute parsing;
|
|
871
|
+
// removed with a space to preserve attribute boundaries
|
|
872
|
+
let scanValue = firstPassOutput;
|
|
873
|
+
if (customFragments.length) {
|
|
874
|
+
scanValue = replaceCustomFragments(firstPassOutput, customFragments, () => ' ');
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
await scan(scanValue);
|
|
878
|
+
} finally {
|
|
879
|
+
// Restore original option
|
|
880
|
+
if (originalContinueOnParseError !== undefined) {
|
|
881
|
+
options.continueOnParseError = originalContinueOnParseError;
|
|
882
|
+
} else {
|
|
883
|
+
delete options.continueOnParseError;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (attrChains) {
|
|
887
|
+
const attrSorters = Object.create(null);
|
|
888
|
+
for (const tag in attrChains) {
|
|
889
|
+
attrSorters[tag] = attrChains[tag].createSorter();
|
|
890
|
+
}
|
|
891
|
+
// Memoize sorted attribute orders—attribute sets often repeat in templates
|
|
892
|
+
const attrOrderCache = new LRU(500);
|
|
893
|
+
|
|
894
|
+
options.sortAttributes = function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs) {
|
|
895
|
+
const sorter = attrSorters[tag];
|
|
896
|
+
if (sorter) {
|
|
897
|
+
const names = attrNames(attrs);
|
|
898
|
+
|
|
899
|
+
// Create order-independent cache key from tag and sorted attribute names
|
|
900
|
+
const cacheKey = tag + ':' + names.slice().sort().join(',');
|
|
901
|
+
let sortedNames = /** @type {string[] | undefined} */ (attrOrderCache.get(cacheKey));
|
|
902
|
+
|
|
903
|
+
if (sortedNames === undefined) {
|
|
904
|
+
// Only sort if not in cache—need to clone names since sort mutates in place
|
|
905
|
+
sortedNames = sorter.sort(names.slice());
|
|
906
|
+
attrOrderCache.set(cacheKey, sortedNames);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// Apply the sorted order to `attrs`
|
|
910
|
+
const attrMap = Object.create(null);
|
|
911
|
+
names.forEach(function (/** @type {string} */ name, /** @type {number} */ index) {
|
|
912
|
+
(attrMap[name] || (attrMap[name] = [])).push(attrs[index]);
|
|
913
|
+
});
|
|
914
|
+
/** @type {string[]} */ (sortedNames).forEach(function (/** @type {string} */ name, /** @type {number} */ index) {
|
|
915
|
+
attrs[index] = attrMap[name].shift();
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
if (classChain) {
|
|
921
|
+
const sorter = classChain.createSorter();
|
|
922
|
+
// Memoize `sortClassNames` results—class lists often repeat in templates
|
|
923
|
+
const classNameCache = new LRU(500);
|
|
924
|
+
|
|
925
|
+
options.sortClassNames = function (/** @type {string} */ classNames) {
|
|
926
|
+
// Fast path: Single class (no spaces) needs no sorting
|
|
927
|
+
if (classNames.indexOf(' ') === -1) {
|
|
928
|
+
return classNames;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// Check cache first
|
|
932
|
+
const cached = /** @type {string | undefined} */ (classNameCache.get(classNames));
|
|
933
|
+
if (cached !== undefined) {
|
|
934
|
+
return cached;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// Expand UID tokens back to original content before sorting
|
|
938
|
+
// Fast path: Skip if no HTML comments (UID markers) present
|
|
939
|
+
let expandedValue = classNames;
|
|
940
|
+
if (uidReplacePattern && classNames.indexOf('<!--') !== -1) {
|
|
941
|
+
expandedValue = classNames.replace(uidReplacePattern, function (/** @type {string} */ _match, /** @type {string} */ index) {
|
|
942
|
+
return ignoredMarkupChunks[+index] || '';
|
|
943
|
+
});
|
|
944
|
+
// Reset `lastIndex` for pattern reuse
|
|
945
|
+
uidReplacePattern.lastIndex = 0;
|
|
946
|
+
}
|
|
947
|
+
const classes = expandedValue.split(whitespaceSplitPatternSort).filter(function(/** @type {string} */ cls) {
|
|
948
|
+
return cls !== '';
|
|
949
|
+
});
|
|
950
|
+
const sorted = sorter.sort(classes);
|
|
951
|
+
const result = sorted.join(' ');
|
|
952
|
+
|
|
953
|
+
// Cache the result
|
|
954
|
+
classNameCache.set(classNames, result);
|
|
955
|
+
return result;
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// Match `/^<\/([\w:-]+)>$/` by hand—the regex engine’s per-call setup costs more
|
|
961
|
+
// than the scan on these short buffer entries
|
|
962
|
+
/**
|
|
963
|
+
* @param {string} str
|
|
964
|
+
* @returns {string | null} The tag name, or `null` where the string is not a plain end tag
|
|
965
|
+
*/
|
|
966
|
+
function matchPlainEndTag(str) {
|
|
967
|
+
const end = str.length;
|
|
968
|
+
if (end < 4 || str.charCodeAt(0) !== 60 /* < */ || str.charCodeAt(1) !== 47 /* / */ || str.charCodeAt(end - 1) !== 62 /* > */) {
|
|
969
|
+
return null;
|
|
970
|
+
}
|
|
971
|
+
for (let i = 2; i < end - 1; i++) {
|
|
972
|
+
const code = str.charCodeAt(i);
|
|
973
|
+
// `[\w:-]`: Letters, digits, `_`, `:`, `-`
|
|
974
|
+
if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 58 || code === 45)) {
|
|
975
|
+
return null;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return str.slice(2, end - 1);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/**
|
|
982
|
+
* @param {string} value - HTML content to minify
|
|
983
|
+
* @param {ProcessedOptions} options - Normalized minification options
|
|
984
|
+
* @param {boolean} [partialMarkup] - Whether treating input as partial markup
|
|
985
|
+
* @returns {Promise<string>} Minified HTML
|
|
986
|
+
*/
|
|
987
|
+
async function minifyHTML(value, options, partialMarkup) {
|
|
988
|
+
// Check input length limitation to prevent ReDoS attacks
|
|
989
|
+
if (options.maxInputLength && value.length > options.maxInputLength) {
|
|
990
|
+
throw new Error(`Input length (${value.length}) exceeds maximum allowed length (${options.maxInputLength})`);
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
if (options.collapseWhitespace) {
|
|
994
|
+
value = collapseWhitespace(value, options, true, true);
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const resolveName = options.name;
|
|
998
|
+
/** @type {HTMLAttribute[]} */
|
|
999
|
+
const emptyAttrs = [];
|
|
1000
|
+
|
|
1001
|
+
/** @type {string[]} */
|
|
1002
|
+
const buffer = [];
|
|
1003
|
+
/** @type {string} */
|
|
1004
|
+
let charsPrevTag = '';
|
|
1005
|
+
let currentChars = '';
|
|
1006
|
+
/** @type {boolean} */
|
|
1007
|
+
let hasChars = false;
|
|
1008
|
+
let currentTag = '';
|
|
1009
|
+
/** @type {Array<{name: string, value?: string, quote?: string, customAssign?: string, customOpen?: string, customClose?: string}>} */
|
|
1010
|
+
let currentAttrs = [];
|
|
1011
|
+
/** @type {string[]} */
|
|
1012
|
+
const stackNoTrimWhitespace = [];
|
|
1013
|
+
/** @type {string[]} */
|
|
1014
|
+
const stackNoCollapseWhitespace = [];
|
|
1015
|
+
let preTextareaDepth = 0; // Count of `pre`/`textarea` entries in `stackNoTrimWhitespace`
|
|
1016
|
+
let optionalStartTag = '';
|
|
1017
|
+
let optionalEndTag = '';
|
|
1018
|
+
let optionalEndTagEmitted = false;
|
|
1019
|
+
/** @type {string[]} */
|
|
1020
|
+
const ignoredMarkupChunks = [];
|
|
1021
|
+
/** @type {Array<RegExpExecArray | null>} */
|
|
1022
|
+
const ignoredCustomMarkupChunks = [];
|
|
1023
|
+
/** @type {string | undefined} */
|
|
1024
|
+
let uidIgnore;
|
|
1025
|
+
/** @type {RegExp | undefined} */
|
|
1026
|
+
let uidIgnorePlaceholderPattern;
|
|
1027
|
+
/** @type {string | undefined} */
|
|
1028
|
+
let uidAttr;
|
|
1029
|
+
/** @type {RegExp | undefined} */
|
|
1030
|
+
let uidPattern;
|
|
1031
|
+
/** @type {RegExp | undefined} */
|
|
1032
|
+
let uidAttrLeadingPattern;
|
|
1033
|
+
// Create inline tags/text sets with custom elements
|
|
1034
|
+
const customElementsInput = options.inlineCustomElements ?? [];
|
|
1035
|
+
const customElementsArr = Array.isArray(customElementsInput) ? customElementsInput : Array.from(customElementsInput);
|
|
1036
|
+
const normalizedCustomElements = customElementsArr.map(name => resolveName(name));
|
|
1037
|
+
// Fast path: Reuse base sets if no custom elements
|
|
1038
|
+
const inlineTextSet = normalizedCustomElements.length
|
|
1039
|
+
? new Set([...inlineElementsToKeepWhitespaceWithin, ...normalizedCustomElements])
|
|
1040
|
+
: inlineElementsToKeepWhitespaceWithin;
|
|
1041
|
+
const inlineElements = normalizedCustomElements.length
|
|
1042
|
+
? new Set([...inlineElementsToKeepWhitespaceAround, ...normalizedCustomElements])
|
|
1043
|
+
: inlineElementsToKeepWhitespaceAround;
|
|
1044
|
+
|
|
1045
|
+
// Parse `removeEmptyElementsExcept` option
|
|
1046
|
+
/** @type {Array<{tag: string, attrs: {[x: string]: string | undefined} | null}>} */
|
|
1047
|
+
let removeEmptyElementsExcept;
|
|
1048
|
+
if (options.removeEmptyElementsExcept && !Array.isArray(options.removeEmptyElementsExcept)) {
|
|
1049
|
+
if (options.log) {
|
|
1050
|
+
options.log('Warning: `removeEmptyElementsExcept` option must be an array, received: ' + typeof options.removeEmptyElementsExcept);
|
|
1051
|
+
}
|
|
1052
|
+
removeEmptyElementsExcept = [];
|
|
1053
|
+
} else {
|
|
1054
|
+
removeEmptyElementsExcept = parseRemoveEmptyElementsExcept(options.removeEmptyElementsExcept || [], options) || [];
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// Temporarily replace ignored chunks with comments, so that there’s no need to worry what’s there;
|
|
1058
|
+
// there might be completely-horribly-broken-alien-non-html-emoji-cthulhu-filled content
|
|
1059
|
+
if (value.indexOf('<!-- htmlmin:ignore -->') !== -1) {
|
|
1060
|
+
// Use `indexOf`-based O(n) loop instead of a global regex with [\s\S]*? to avoid O(n²)
|
|
1061
|
+
// backtracking on adversarial HTML with many `<!--` prefixes but no closing marker
|
|
1062
|
+
const ignoreMarker = '<!-- htmlmin:ignore -->';
|
|
1063
|
+
const ignoreMarkerLen = ignoreMarker.length;
|
|
1064
|
+
let ignoreResult = '';
|
|
1065
|
+
let ignorePos = 0;
|
|
1066
|
+
while (ignorePos < value.length) {
|
|
1067
|
+
const ignoreStart = value.indexOf(ignoreMarker, ignorePos);
|
|
1068
|
+
if (ignoreStart === -1) { ignoreResult += value.slice(ignorePos); break; }
|
|
1069
|
+
ignoreResult += value.slice(ignorePos, ignoreStart);
|
|
1070
|
+
const ignoreEnd = value.indexOf(ignoreMarker, ignoreStart + ignoreMarkerLen);
|
|
1071
|
+
if (ignoreEnd === -1) { ignoreResult += value.slice(ignoreStart); break; }
|
|
1072
|
+
const group1 = value.slice(ignoreStart + ignoreMarkerLen, ignoreEnd);
|
|
1073
|
+
if (!uidIgnore) {
|
|
1074
|
+
uidIgnore = uniqueId(value);
|
|
1075
|
+
const pattern = new RegExp('^' + uidIgnore + '([0-9]+)$');
|
|
1076
|
+
uidIgnorePlaceholderPattern = new RegExp('^<!--' + uidIgnore + '(\\d+)-->$');
|
|
1077
|
+
if (options.ignoreCustomComments) {
|
|
1078
|
+
options.ignoreCustomComments = options.ignoreCustomComments.slice();
|
|
1079
|
+
} else {
|
|
1080
|
+
options.ignoreCustomComments = [];
|
|
1081
|
+
}
|
|
1082
|
+
options.ignoreCustomComments.push(pattern);
|
|
1083
|
+
}
|
|
1084
|
+
const token = '<!--' + uidIgnore + ignoredMarkupChunks.length + '-->';
|
|
1085
|
+
ignoredMarkupChunks.push(group1);
|
|
1086
|
+
ignoreResult += token;
|
|
1087
|
+
ignorePos = ignoreEnd + ignoreMarkerLen;
|
|
1088
|
+
}
|
|
1089
|
+
value = ignoreResult;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// Create sort functions after `htmlmin:ignore` processing but before custom fragment UID markers
|
|
1093
|
+
// This allows proper frequency analysis with access to ignored content via UID tokens
|
|
1094
|
+
if ((options.sortAttributes && typeof options.sortAttributes !== 'function') ||
|
|
1095
|
+
(options.sortClassNames && typeof options.sortClassNames !== 'function')) {
|
|
1096
|
+
await createSortFns(value, options, uidIgnore ?? '', uidAttr ?? '', ignoredMarkupChunks);
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
const customFragments = (options.ignoreCustomFragments || []).map(toFragment);
|
|
1100
|
+
if (customFragments.length) {
|
|
1101
|
+
// Temporarily replace custom ignored fragments with unique attributes
|
|
1102
|
+
const replaceFragment = function (/** @type {string} */ match) {
|
|
1103
|
+
if (!uidAttr) {
|
|
1104
|
+
uidAttr = uniqueId(value);
|
|
1105
|
+
uidPattern = new RegExp('(\\s*)' + uidAttr + '([0-9]+)' + uidAttr + '(\\s*)', 'g');
|
|
1106
|
+
uidAttrLeadingPattern = new RegExp('^\\s*' + uidAttr + '(\\d+)' + uidAttr);
|
|
1107
|
+
|
|
1108
|
+
if (options.minifyCSS !== identity) {
|
|
1109
|
+
options.minifyCSS = (function (/** @type {ProcessedOptions['minifyCSS']} */ fn) {
|
|
1110
|
+
return function (/** @type {string} */ text, /** @type {string | undefined} */ type, /** @type {ProcessedOptions['cssContext']} */ context) {
|
|
1111
|
+
text = text.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ _match, /** @type {string} */ _prefix, /** @type {string} */ index) {
|
|
1112
|
+
const chunks = ignoredCustomMarkupChunks[+index];
|
|
1113
|
+
return (chunks?.[1] ?? '') + uidAttr + index + uidAttr + (chunks?.[2] ?? '');
|
|
1114
|
+
});
|
|
1115
|
+
|
|
1116
|
+
return fn(text, type, context);
|
|
1117
|
+
};
|
|
1118
|
+
})(options.minifyCSS);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
if (options.minifyJS !== identity) {
|
|
1122
|
+
options.minifyJS = (function (/** @type {ProcessedOptions['minifyJS']} */ fn) {
|
|
1123
|
+
return function (/** @type {string} */ text, /** @type {boolean | undefined} */ inline, /** @type {boolean | undefined} */ isModule) {
|
|
1124
|
+
return fn(text.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ _match, /** @type {string} */ _prefix, /** @type {string} */ index) {
|
|
1125
|
+
const chunks = ignoredCustomMarkupChunks[+index];
|
|
1126
|
+
return (chunks?.[1] ?? '') + uidAttr + index + uidAttr + (chunks?.[2] ?? '');
|
|
1127
|
+
}), inline, isModule);
|
|
1128
|
+
};
|
|
1129
|
+
})(options.minifyJS);
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
const token = uidAttr + ignoredCustomMarkupChunks.length + uidAttr;
|
|
1134
|
+
ignoredCustomMarkupChunks.push(/^(\s*)[\s\S]*?(\s*)$/.exec(match));
|
|
1135
|
+
return '\t' + token + '\t';
|
|
1136
|
+
};
|
|
1137
|
+
|
|
1138
|
+
value = replaceCustomFragments(value, customFragments, replaceFragment);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
function canCollapseWhitespace(/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs) {
|
|
1142
|
+
return options.canCollapseWhitespace(tag, attrs, defaultCanCollapseWhitespace);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
function canTrimWhitespace(/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs) {
|
|
1146
|
+
return options.canTrimWhitespace(tag, attrs, defaultCanTrimWhitespace);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
function removeStartTag() {
|
|
1150
|
+
let index = buffer.length - 1;
|
|
1151
|
+
while (index > 0 && !RE_START_TAG.test(buffer[index] ?? '')) {
|
|
1152
|
+
index--;
|
|
1153
|
+
}
|
|
1154
|
+
buffer.length = Math.max(0, index);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// Whether the element being parsed holds text rather than markup. The namespace decides
|
|
1158
|
+
// this, not the name alone: `script` and `style` hold text wherever they stand, the rest
|
|
1159
|
+
// only as HTML elements—an SVG or MathML `title` holds markup like any foreign element
|
|
1160
|
+
function holdsRawText() {
|
|
1161
|
+
return specialContentElements.has(currentTag) ||
|
|
1162
|
+
(rawTextElements.has(currentTag) && !options.insideForeignContent);
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// Whether whitespace-only text between tags survives minification
|
|
1166
|
+
function keepsWhitespace() {
|
|
1167
|
+
return !options.collapseWhitespace || Boolean(options.conservativeCollapse) || Boolean(options.preserveLineBreaks);
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// The two whitespace runs an omitted tag separated become one run, which collapses to the
|
|
1171
|
+
// single character it is due: a line break under `preserveLineBreaks`, a no-break space
|
|
1172
|
+
// where the run holds one, a space under `conservativeCollapse`
|
|
1173
|
+
function mergeWhitespaceRuns(/** @type {number} */ index) {
|
|
1174
|
+
let before = index - 1;
|
|
1175
|
+
while (before >= 0 && buffer[before] === '') {
|
|
1176
|
+
before--;
|
|
1177
|
+
}
|
|
1178
|
+
let after = index;
|
|
1179
|
+
while (after < buffer.length && buffer[after] === '') {
|
|
1180
|
+
after++;
|
|
1181
|
+
}
|
|
1182
|
+
if (before < 0 || after >= buffer.length) {
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
const prev = buffer[before] ?? '';
|
|
1186
|
+
const next = buffer[after] ?? '';
|
|
1187
|
+
if (!RE_WS_NBSP_END.test(prev) || !RE_WS_START.test(next)) {
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
// A line break the run already carries outranks the whitespace ahead of it; trimming
|
|
1191
|
+
// the other side takes ASCII whitespace only, so a no-break space stays as is
|
|
1192
|
+
if (options.preserveLineBreaks && /[\n\r]/.test((next.match(RE_WS_START) ?? [''])[0])) {
|
|
1193
|
+
buffer[before] = prev.replace(RE_WS_END, '');
|
|
1194
|
+
} else {
|
|
1195
|
+
buffer[after] = next.replace(RE_WS_START, '');
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
function removeEndTag() {
|
|
1200
|
+
let index = buffer.length - 1;
|
|
1201
|
+
while (index > 0 && !RE_END_TAG.test(buffer[index] ?? '')) {
|
|
1202
|
+
index--;
|
|
1203
|
+
}
|
|
1204
|
+
// Text that follows the end tag is kept as is, so drop the tag alone. Whitespace kept
|
|
1205
|
+
// verbatim—in `pre`, in `textarea`, or wherever `canTrimWhitespace` says so—counts as
|
|
1206
|
+
// kept text too, no matter how whitespace is collapsed elsewhere.
|
|
1207
|
+
const noTrim = stackNoTrimWhitespace.length > 0;
|
|
1208
|
+
if (index < buffer.length - 1 && (keepsWhitespace() || noTrim) && RE_END_TAG.test(buffer[index] ?? '')) {
|
|
1209
|
+
buffer.splice(index, 1);
|
|
1210
|
+
// Only collapsed whitespace can merge
|
|
1211
|
+
if (options.collapseWhitespace && !noTrim) {
|
|
1212
|
+
mergeWhitespaceRuns(index);
|
|
1213
|
+
}
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
buffer.length = Math.max(0, index);
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
// Look for trailing whitespaces, bypass any inline tags
|
|
1220
|
+
function trimTrailingWhitespace(/** @type {number} */ index, /** @type {string} */ nextTag) {
|
|
1221
|
+
for (let prevTag = ''; index >= 0 && canTrimWhitespace(prevTag, emptyAttrs); index--) {
|
|
1222
|
+
const str = buffer[index] ?? '';
|
|
1223
|
+
const endTagName = matchPlainEndTag(str);
|
|
1224
|
+
if (endTagName !== null) {
|
|
1225
|
+
prevTag = endTagName;
|
|
1226
|
+
} else if (str.charCodeAt(str.length - 1) === 62 /* > */ ||
|
|
1227
|
+
(buffer[index] = collapseWhitespaceSmart(str, '', nextTag, emptyAttrs, emptyAttrs, options, inlineElements, inlineTextSet))) {
|
|
1228
|
+
break;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// Look for trailing whitespaces from previously processed text
|
|
1234
|
+
// which may not be trimmed due to a following comment or an empty
|
|
1235
|
+
// element which has now been removed
|
|
1236
|
+
function squashTrailingWhitespace(/** @type {string} */ nextTag) {
|
|
1237
|
+
let charsIndex = buffer.length - 1;
|
|
1238
|
+
// Step back over every trailing comment and empty entry, not just one—a single step
|
|
1239
|
+
// stops the search at the comment itself, leaving whitespace behind that a second
|
|
1240
|
+
// minification run then removes
|
|
1241
|
+
while (charsIndex > 0) {
|
|
1242
|
+
const item = buffer[charsIndex] ?? '';
|
|
1243
|
+
if (!/^(?:<!|$)/.test(item) || (uidIgnore && item.indexOf(uidIgnore) !== -1)) {
|
|
1244
|
+
break;
|
|
1245
|
+
}
|
|
1246
|
+
charsIndex--;
|
|
1247
|
+
}
|
|
1248
|
+
trimTrailingWhitespace(charsIndex, nextTag);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// Per-text-node context for `charsCollapse`/`charsFinalize`, set by the `chars`
|
|
1252
|
+
// handler before either phase runs; shared variables (rather than parameters)
|
|
1253
|
+
// let both phases live at this scope—`charsCollapse` reassigns `textPrevTag`
|
|
1254
|
+
// and `charsFinalize` must see that change. Defining the phases inside the
|
|
1255
|
+
// `chars` handler instead would allocate two closures per text node.
|
|
1256
|
+
/** @type {string} */
|
|
1257
|
+
let textPrevTag = '';
|
|
1258
|
+
/** @type {string} */
|
|
1259
|
+
let textNextTag = '';
|
|
1260
|
+
/** @type {HTMLAttribute[]} */
|
|
1261
|
+
let textPrevAttrs = emptyAttrs;
|
|
1262
|
+
/** @type {HTMLAttribute[]} */
|
|
1263
|
+
let textNextAttrs = emptyAttrs;
|
|
1264
|
+
|
|
1265
|
+
// Whitespace collapsing phase (sync)
|
|
1266
|
+
function charsCollapse(/** @type {string} */ text) {
|
|
1267
|
+
// Trim outermost newline-based whitespace inside `pre`/`textarea` elements
|
|
1268
|
+
// This removes trailing newlines often added by template engines before closing tags
|
|
1269
|
+
// Only trims single trailing newlines (multiple newlines are likely intentional formatting)
|
|
1270
|
+
if (options.collapseWhitespace && stackNoTrimWhitespace.length) {
|
|
1271
|
+
const topTag = stackNoTrimWhitespace[stackNoTrimWhitespace.length - 1];
|
|
1272
|
+
if (preTextareaDepth > 0) {
|
|
1273
|
+
// Trim trailing whitespace only if it ends with a single newline (not multiple)
|
|
1274
|
+
// Multiple newlines are likely intentional formatting, single newline is often a template artifact
|
|
1275
|
+
// Treat CRLF (`\r\n`), CR (`\r`), and LF (`\n`) as single line-ending units
|
|
1276
|
+
if (textNextTag && textNextTag === '/' + topTag && /[^\r\n](?:\r\n|\r|\n)[ \t]*$/.test(text)) {
|
|
1277
|
+
text = text.replace(/(?:\r\n|\r|\n)[ \t]*$/, '');
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
if (options.collapseWhitespace) {
|
|
1282
|
+
if (!stackNoTrimWhitespace.length) {
|
|
1283
|
+
// When the prev item is a UID placeholder, compute its effective tag name for whitespace decisions;
|
|
1284
|
+
// this is only used in `collapseWhitespaceSmart`—`textPrevTag` itself is not modified,
|
|
1285
|
+
// to avoid side effects on the `inlineTextSet` branch below
|
|
1286
|
+
let effectivePrevTag = textPrevTag;
|
|
1287
|
+
if (textPrevTag === 'comment') {
|
|
1288
|
+
const prevComment = buffer[buffer.length - 1] ?? '';
|
|
1289
|
+
if (!uidIgnore || prevComment.indexOf(uidIgnore) === -1) {
|
|
1290
|
+
if (!prevComment) {
|
|
1291
|
+
textPrevTag = charsPrevTag;
|
|
1292
|
+
effectivePrevTag = textPrevTag;
|
|
1293
|
+
}
|
|
1294
|
+
if (buffer.length > 1 && (!prevComment || (!options.conservativeCollapse && / $/.test(currentChars)))) {
|
|
1295
|
+
const charsIndex = buffer.length - 2;
|
|
1296
|
+
buffer[charsIndex] = (buffer[charsIndex] ?? '').replace(/\s+$/, function (trailingSpaces) {
|
|
1297
|
+
text = trailingSpaces + text;
|
|
1298
|
+
return '';
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
} else if (uidIgnorePlaceholderPattern && textNextTag !== 'comment') {
|
|
1302
|
+
// UID placeholder followed by a real element—derive the effective `prevTag` from the
|
|
1303
|
+
// placeholder’s last HTML tag so `collapseWhitespaceSmart` can make the right call;
|
|
1304
|
+
// when `textNextTag` is `comment` (another UID placeholder), `commentFinalize` handles it
|
|
1305
|
+
const match = prevComment.match(uidIgnorePlaceholderPattern);
|
|
1306
|
+
if (match) {
|
|
1307
|
+
const idx = +(match[1] ?? '');
|
|
1308
|
+
if (idx < ignoredMarkupChunks.length) {
|
|
1309
|
+
const content = ignoredMarkupChunks[idx];
|
|
1310
|
+
const lastTagMatch = content && RE_LAST_HTML_TAG.exec(content);
|
|
1311
|
+
if (lastTagMatch) {
|
|
1312
|
+
const group = lastTagMatch[1] ?? '';
|
|
1313
|
+
const isClose = group.charAt(0) === '/';
|
|
1314
|
+
const tagName = resolveName(isClose ? group.slice(1) : group);
|
|
1315
|
+
effectivePrevTag = isClose ? '/' + tagName : tagName;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
if (textPrevTag) {
|
|
1322
|
+
if (textPrevTag === '/nobr' || textPrevTag === 'wbr') {
|
|
1323
|
+
if (/^\s/.test(text)) {
|
|
1324
|
+
let tagIndex = buffer.length - 1;
|
|
1325
|
+
while (tagIndex > 0 && (buffer[tagIndex] ?? '').lastIndexOf('<' + textPrevTag) !== 0) {
|
|
1326
|
+
tagIndex--;
|
|
1327
|
+
}
|
|
1328
|
+
trimTrailingWhitespace(tagIndex - 1, 'br');
|
|
1329
|
+
}
|
|
1330
|
+
} else if (inlineTextSet.has(textPrevTag.charAt(0) === '/' ? textPrevTag.slice(1) : textPrevTag)) {
|
|
1331
|
+
text = collapseWhitespace(text, options, /(?:^|\s)$/.test(currentChars), false);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
if (textPrevTag || textNextTag) {
|
|
1335
|
+
text = collapseWhitespaceSmart(text, effectivePrevTag, textNextTag, textPrevAttrs, textNextAttrs, options, inlineElements, inlineTextSet);
|
|
1336
|
+
} else {
|
|
1337
|
+
text = collapseWhitespace(text, options, true, true);
|
|
1338
|
+
}
|
|
1339
|
+
if (!text && RE_TRAILING_WHITESPACE.test(currentChars) && textPrevTag && textPrevTag.charAt(0) === '/') {
|
|
1340
|
+
trimTrailingWhitespace(buffer.length - 1, textNextTag);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
if (!stackNoCollapseWhitespace.length && textNextTag !== 'html' && !(textPrevTag && textNextTag)) {
|
|
1344
|
+
text = collapseWhitespace(text, options, false, false, true);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
return text;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
// Finalization phase (sync): Optional tag handling, entity re-encoding, buffer push
|
|
1351
|
+
function charsFinalize(/** @type {string} */ text) {
|
|
1352
|
+
if (options.removeOptionalTags && text) {
|
|
1353
|
+
// UID-attr tokens are padded with `\t`, which would falsely look like leading whitespace;
|
|
1354
|
+
// resolve single-token text to its actual content for the space/comment checks below
|
|
1355
|
+
let effectiveText = text;
|
|
1356
|
+
if (uidAttrLeadingPattern && uidAttr && text.includes(uidAttr)) {
|
|
1357
|
+
const uidMatch = uidAttrLeadingPattern.exec(text);
|
|
1358
|
+
if (uidMatch) {
|
|
1359
|
+
const idx = +(uidMatch[1] ?? 0);
|
|
1360
|
+
const chunks = idx < ignoredCustomMarkupChunks.length ? ignoredCustomMarkupChunks[idx] : null;
|
|
1361
|
+
if (chunks != null) {
|
|
1362
|
+
effectiveText = chunks[0] ?? '';
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
// `<html>` may be omitted if first thing inside is not a comment
|
|
1367
|
+
// `<body>` may be omitted if first thing inside is not space, comment, `<meta>`, `<link>`, `<script>`, `<style>`, or `<template>`
|
|
1368
|
+
if (optionalStartTag === 'html' || (optionalStartTag === 'body' && !/^\s/.test(effectiveText))) {
|
|
1369
|
+
removeStartTag();
|
|
1370
|
+
}
|
|
1371
|
+
optionalStartTag = '';
|
|
1372
|
+
// `</html>` or `</body>` may be omitted if not followed by comment
|
|
1373
|
+
// `</head>`, `</colgroup>`, or `</caption>` may be omitted if not followed by space or comment
|
|
1374
|
+
if (optionalEndTagEmitted && (compactElements.has(optionalEndTag) || (looseElements.has(optionalEndTag) && !/^\s/.test(effectiveText)))) {
|
|
1375
|
+
removeEndTag();
|
|
1376
|
+
// The tag is gone from the buffer, so nothing is left to omit later
|
|
1377
|
+
optionalEndTag = '';
|
|
1378
|
+
optionalEndTagEmitted = false;
|
|
1379
|
+
}
|
|
1380
|
+
// Whitespace-only text doesn’t prevent omission of the pending end tag: It’s either
|
|
1381
|
+
// collapsed away, or kept in place while the tag alone is dropped—except for
|
|
1382
|
+
// `</head>`, `</colgroup>`, and `</caption>`, which may not be followed by space.
|
|
1383
|
+
// Only ASCII whitespace counts, as no-break space and friends are content
|
|
1384
|
+
// https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
|
|
1385
|
+
if (!RE_WS_ONLY.test(text) || (keepsWhitespace() && looseElements.has(optionalEndTag))) {
|
|
1386
|
+
optionalEndTag = '';
|
|
1387
|
+
optionalEndTagEmitted = false;
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
charsPrevTag = /^\s*$/.test(text) ? textPrevTag : 'comment';
|
|
1391
|
+
if (options.decodeEntities && text && !holdsRawText()) {
|
|
1392
|
+
// Escape any `&` symbols that start either:
|
|
1393
|
+
// 1. a legacy-named character reference (i.e., one that doesn’t end with `;`)
|
|
1394
|
+
// 2. or any other character reference (i.e., one that does end with `;`)
|
|
1395
|
+
// Note that `&` can be escaped as `&`, without the semicolon.
|
|
1396
|
+
// https://mathiasbynens.be/notes/ambiguous-ampersands
|
|
1397
|
+
if (text.indexOf('&') !== -1) {
|
|
1398
|
+
text = text.replace(RE_LEGACY_ENTITIES, '&$1');
|
|
1399
|
+
}
|
|
1400
|
+
if (text.indexOf('<') !== -1) {
|
|
1401
|
+
// Escapable raw text ends at its own end tag alone, so only that one needs escaping;
|
|
1402
|
+
// in foreign content the same element holds markup, where every `<` does
|
|
1403
|
+
const escapeLt = (options.insideForeignContent ? undefined : RE_ESCAPE_LT_RAW_TEXT[currentTag]) ?? RE_ESCAPE_LT;
|
|
1404
|
+
text = text.replace(escapeLt, '<');
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
if (uidPattern && options.collapseWhitespace && stackNoTrimWhitespace.length) {
|
|
1408
|
+
text = text.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ match, /** @type {string} */ _prefix, /** @type {string} */ index) {
|
|
1409
|
+
return ignoredCustomMarkupChunks[+index]?.[0] ?? match;
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
currentChars += text;
|
|
1413
|
+
if (text) {
|
|
1414
|
+
hasChars = true;
|
|
1415
|
+
}
|
|
1416
|
+
buffer.push(text);
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// Comment finalization (sync): Optional tag handling, `htmlmin:ignore` whitespace collapsing, buffer push
|
|
1420
|
+
function commentFinalize(/** @type {string} */ comment) {
|
|
1421
|
+
if (options.removeOptionalTags && comment) {
|
|
1422
|
+
if (uidIgnorePlaceholderPattern) {
|
|
1423
|
+
const match = uidIgnorePlaceholderPattern.exec(comment);
|
|
1424
|
+
if (match) {
|
|
1425
|
+
// UID placeholders represent real HTML content, not true HTML comments;
|
|
1426
|
+
// if there’s a pending optional end tag and the ignored content isn’t itself
|
|
1427
|
+
// a comment (which per the HTML spec prevents omission), resolve it now,
|
|
1428
|
+
// before the UID is pushed to the buffer
|
|
1429
|
+
const idx = +(match[1] ?? 0);
|
|
1430
|
+
const content = idx < ignoredMarkupChunks.length ? ignoredMarkupChunks[idx] : null;
|
|
1431
|
+
if (optionalEndTag && optionalEndTagEmitted && content != null && !/^\s*<!--/.test(content)) {
|
|
1432
|
+
const firstTagMatch = content.match(/^\s*<([a-zA-Z][^\s/>]*)/);
|
|
1433
|
+
const firstTagGroup = firstTagMatch?.[1] ?? '';
|
|
1434
|
+
const firstTag = firstTagGroup ? resolveName(firstTagGroup) : '';
|
|
1435
|
+
if (canRemovePrecedingTag(optionalEndTag, firstTag)) {
|
|
1436
|
+
removeEndTag();
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
// Comments (real or placeholder) always suppress optional start tag omissions
|
|
1442
|
+
optionalStartTag = '';
|
|
1443
|
+
optionalEndTag = '';
|
|
1444
|
+
optionalEndTagEmitted = false;
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
// Optimize whitespace collapsing between consecutive `htmlmin:ignore` placeholder comments
|
|
1448
|
+
if (options.collapseWhitespace && comment && uidIgnorePlaceholderPattern) {
|
|
1449
|
+
if (uidIgnorePlaceholderPattern.test(comment)) {
|
|
1450
|
+
// Check if previous buffer items are: [ignore-placeholder, whitespace-only text]
|
|
1451
|
+
if (buffer.length >= 2) {
|
|
1452
|
+
const prevText = buffer[buffer.length - 1];
|
|
1453
|
+
const prevComment = buffer[buffer.length - 2];
|
|
1454
|
+
|
|
1455
|
+
// Check if previous item is whitespace-only and item before that is ignore-placeholder
|
|
1456
|
+
if (prevText && RE_WHITESPACE_ONLY.test(prevText) && prevComment && uidIgnorePlaceholderPattern.test(prevComment)) {
|
|
1457
|
+
// Extract the index from both placeholders to check their content
|
|
1458
|
+
const currentMatch = comment.match(uidIgnorePlaceholderPattern);
|
|
1459
|
+
const prevMatch = prevComment.match(uidIgnorePlaceholderPattern);
|
|
1460
|
+
|
|
1461
|
+
if (currentMatch && prevMatch) {
|
|
1462
|
+
const currentIndex = +(currentMatch[1] ?? 0);
|
|
1463
|
+
const prevIndex = +(prevMatch[1] ?? 0);
|
|
1464
|
+
|
|
1465
|
+
// Defensive bounds check to ensure indices are valid
|
|
1466
|
+
if (currentIndex < ignoredMarkupChunks.length && prevIndex < ignoredMarkupChunks.length) {
|
|
1467
|
+
const currentContent = ignoredMarkupChunks[currentIndex];
|
|
1468
|
+
const prevContent = ignoredMarkupChunks[prevIndex];
|
|
1469
|
+
|
|
1470
|
+
// Only collapse whitespace if both blocks contain HTML (start with `<`)
|
|
1471
|
+
// Don’t collapse if either contains plain text, as that would change meaning
|
|
1472
|
+
if (currentContent && prevContent && /^\s*</.test(currentContent) && /^\s*</.test(prevContent)) {
|
|
1473
|
+
// Extract tag names from the HTML content
|
|
1474
|
+
const currentTagMatch = currentContent.match(/^\s*<([a-zA-Z][\w:-]*)/);
|
|
1475
|
+
const prevTagMatch = prevContent.match(/^\s*<([a-zA-Z][\w:-]*)/);
|
|
1476
|
+
// HTML comments are invisible (no block/inline nature), treat as non-inline
|
|
1477
|
+
const prevIsHtmlComment = !prevTagMatch && RE_HTML_COMMENT_START.test(prevContent);
|
|
1478
|
+
const currentIsHtmlComment = !currentTagMatch && RE_HTML_COMMENT_START.test(currentContent);
|
|
1479
|
+
// Closing tags (e.g., `</div>`)—inline-ness determines whether to collapse
|
|
1480
|
+
const prevClosingTagMatch = !prevTagMatch && RE_CLOSING_TAG_START.exec(prevContent);
|
|
1481
|
+
const currentClosingTagMatch = !currentTagMatch && RE_CLOSING_TAG_START.exec(currentContent);
|
|
1482
|
+
|
|
1483
|
+
// Collapse if both sides are element/closing tags or HTML comments, and neither is inline
|
|
1484
|
+
if ((currentTagMatch || currentIsHtmlComment || currentClosingTagMatch) &&
|
|
1485
|
+
(prevTagMatch || prevIsHtmlComment || prevClosingTagMatch)) {
|
|
1486
|
+
const currentTagName = currentTagMatch ? resolveName(currentTagMatch[1] ?? '')
|
|
1487
|
+
: currentClosingTagMatch ? resolveName(currentClosingTagMatch[1] ?? '') : null;
|
|
1488
|
+
const prevTagName = prevTagMatch ? resolveName(prevTagMatch[1] ?? '')
|
|
1489
|
+
: prevClosingTagMatch ? resolveName(prevClosingTagMatch[1] ?? '') : null;
|
|
1490
|
+
|
|
1491
|
+
// Don’t collapse between inline elements (HTML comments count as non-inline)
|
|
1492
|
+
if (!inlineElements.has(currentTagName ?? '') && !inlineElements.has(prevTagName ?? '')) {
|
|
1493
|
+
// Collapse whitespace respecting context rules
|
|
1494
|
+
let collapsedText = prevText;
|
|
1495
|
+
|
|
1496
|
+
// Apply `collapseWhitespace` with appropriate context
|
|
1497
|
+
if (!stackNoTrimWhitespace.length && !stackNoCollapseWhitespace.length) {
|
|
1498
|
+
// Not in pre or other no-collapse context
|
|
1499
|
+
if (prevText.includes('\xA0')) {
|
|
1500
|
+
// No-break spaces are content, so every one of them survives in place;
|
|
1501
|
+
// the ASCII whitespace around them collapses as it would anywhere else
|
|
1502
|
+
collapsedText = collapseWhitespace(prevText, options, true, true, true);
|
|
1503
|
+
} else if (options.preserveLineBreaks && /[\n\r]/.test(prevText)) {
|
|
1504
|
+
// Preserve line break as single newline
|
|
1505
|
+
collapsedText = '\n';
|
|
1506
|
+
} else if (options.conservativeCollapse) {
|
|
1507
|
+
// Conservative mode: Keep single space
|
|
1508
|
+
collapsedText = ' ';
|
|
1509
|
+
} else {
|
|
1510
|
+
// Aggressive mode: Remove all whitespace
|
|
1511
|
+
collapsedText = '';
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
// Replace the whitespace in buffer
|
|
1516
|
+
buffer[buffer.length - 1] = collapsedText;
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
buffer.push(comment);
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
// Inline scripts are minified one at a time as the parse reaches them, which serializes
|
|
1531
|
+
// work the minifier could overlap. Dispatching them all up front turns that into a single
|
|
1532
|
+
// wave the parse then reads results from. Bodies are matched by exact content, so one the
|
|
1533
|
+
// parse asks for in another form simply misses and takes the original path.
|
|
1534
|
+
/** @type {Map<string, Promise<string>> | null} */
|
|
1535
|
+
let jsPrewarmed = null;
|
|
1536
|
+
if (options.parallelJS && options.minifyJS !== identity && !options.processScripts?.length) {
|
|
1537
|
+
const bodies = extractScriptBodies(value);
|
|
1538
|
+
if (bodies.length > 1) {
|
|
1539
|
+
jsPrewarmed = new Map();
|
|
1540
|
+
// `collapseWhitespace` reaches script bodies through the whole-document pass above,
|
|
1541
|
+
// so the parse sees them trimmed; other whitespace modes leave them as they are
|
|
1542
|
+
const trims = Boolean(options.collapseWhitespace) &&
|
|
1543
|
+
!options.conservativeCollapse && !options.preserveLineBreaks;
|
|
1544
|
+
for (const { code, isModule } of bodies) {
|
|
1545
|
+
const body = trims ? code.trim() : code;
|
|
1546
|
+
const key = (isModule ? 'm|' : '|') + body;
|
|
1547
|
+
if (jsPrewarmed.has(key)) {
|
|
1548
|
+
continue;
|
|
1549
|
+
}
|
|
1550
|
+
const pending = Promise.resolve(options.minifyJS(body, false, isModule));
|
|
1551
|
+
// The awaiting consumer reports the failure; a body the parse never asks for
|
|
1552
|
+
// would not have been minified at all, so its failure is not ours to raise
|
|
1553
|
+
pending.catch(() => {});
|
|
1554
|
+
jsPrewarmed.set(key, pending);
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
// SVG subtree capture: When SVGO is active, record buffer positions for post-processing
|
|
1560
|
+
/** @type {Array<{start: number, end: number}>} */
|
|
1561
|
+
const svgBlocks = []; // Array of { start, end } buffer indices
|
|
1562
|
+
let svgBufferStartIndex = -1;
|
|
1563
|
+
let svgDepth = 0;
|
|
1564
|
+
|
|
1565
|
+
// One-time probe: If the input contains no SVG/MathML elements and the call
|
|
1566
|
+
// isn’t already inside foreign content (recursive calls inherit options),
|
|
1567
|
+
// the per-tag foreign-content handling in `start`/`end` can be skipped
|
|
1568
|
+
const hasForeignContext = Boolean(options.insideForeignContent) || RE_FOREIGN_ELEMENT_PROBE.test(value);
|
|
1569
|
+
|
|
1570
|
+
const parser = new HTMLParser(value, {
|
|
1571
|
+
partialMarkup: partialMarkup ?? options.partialMarkup,
|
|
1572
|
+
continueOnParseError: options.continueOnParseError,
|
|
1573
|
+
customAttrAssign: options.customAttrAssign,
|
|
1574
|
+
customAttrSurround: options.customAttrSurround,
|
|
1575
|
+
// Compute `nextTag` only when whitespace collapse features require it
|
|
1576
|
+
wantsNextTag: !!(options.collapseWhitespace || options.collapseInlineTagWhitespace || options.conservativeCollapse),
|
|
1577
|
+
// `keepClosingSlash` calls the slash meaningful, which decides how the input is read as well
|
|
1578
|
+
selfClosingSlash: options.keepClosingSlash,
|
|
1579
|
+
|
|
1580
|
+
start: async function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ unary, /** @type {string} */ unarySlash, /** @type {boolean} */ autoGenerated) {
|
|
1581
|
+
// `lowerTag` stays '' when no foreign content is around—the SVG/MathML
|
|
1582
|
+
// checks below can then never match, and no per-tag lowercasing is needed
|
|
1583
|
+
let lowerTag = '';
|
|
1584
|
+
let useNameParentForTag = false;
|
|
1585
|
+
// The context the start tag sits in, which the branches below leave behind
|
|
1586
|
+
const optionsParent = options;
|
|
1587
|
+
let pushedContext = false;
|
|
1588
|
+
if (hasForeignContext) {
|
|
1589
|
+
lowerTag = tag.toLowerCase();
|
|
1590
|
+
if (lowerTag === 'svg' || lowerTag === 'math') {
|
|
1591
|
+
// Preserve the surrounding HTML context’s name function (e.g., `identity`
|
|
1592
|
+
// under `caseSensitive`) and slash handling so `foreignObject`/`annotation-xml`
|
|
1593
|
+
// can restore them
|
|
1594
|
+
const nameHTML = options.name;
|
|
1595
|
+
const keepClosingSlashHTML = Boolean(options.keepClosingSlash);
|
|
1596
|
+
options = Object.create(options);
|
|
1597
|
+
options.caseSensitive = true;
|
|
1598
|
+
options.keepClosingSlash = true;
|
|
1599
|
+
options.name = identity;
|
|
1600
|
+
options.nameHTML = nameHTML;
|
|
1601
|
+
options.keepClosingSlashHTML = keepClosingSlashHTML;
|
|
1602
|
+
// SVGO reads an SVG block whole, nested MathML included, so what the block is stays true inside it
|
|
1603
|
+
options.insideSVG = lowerTag === 'svg' || Boolean(options.insideSVG);
|
|
1604
|
+
options.insideForeignContent = true;
|
|
1605
|
+
// Disable HTML-specific options that produce invalid XML:
|
|
1606
|
+
// SVG with `minifySVG` enabled is passed to SVGO, which requires valid XML input;
|
|
1607
|
+
// MathML is never processed by SVGO, so these restrictions never apply to it
|
|
1608
|
+
if (lowerTag === 'svg' && options.minifySVG) {
|
|
1609
|
+
options.removeAttributeQuotes = false;
|
|
1610
|
+
// @@ Encode a bare `&` for SVGO as well—it costs the block its optimization
|
|
1611
|
+
// (though not its validity; early fix could encode `&` where it’s unambiguous)
|
|
1612
|
+
options.decodeEntities = false;
|
|
1613
|
+
// Omitting a start and end tag both would keep the block well-formed, which this misses
|
|
1614
|
+
options.removeOptionalTags = false;
|
|
1615
|
+
options.collapseBooleanAttributes = false;
|
|
1616
|
+
options.includeAutoGeneratedTags = true;
|
|
1617
|
+
}
|
|
1618
|
+
options.removeTagWhitespace = false;
|
|
1619
|
+
pushedContext = true;
|
|
1620
|
+
}
|
|
1621
|
+
// `foreignObject` in SVG and `annotation-xml` in MathML contain HTML content
|
|
1622
|
+
// (the element itself is in SVG/MathML namespace, only its children are HTML);
|
|
1623
|
+
// a repeated attribute is dropped after the first, so the first `encoding` decides
|
|
1624
|
+
if (options.insideForeignContent && (lowerTag === 'foreignobject' ||
|
|
1625
|
+
(lowerTag === 'annotation-xml' && RE_HTML_ENCODING.test(
|
|
1626
|
+
attrs.find((/** @type {HTMLAttribute} */ a) => a.name.toLowerCase() === 'encoding')?.value ?? '')))) {
|
|
1627
|
+
const nameParent = options.name;
|
|
1628
|
+
options = Object.create(options);
|
|
1629
|
+
options.caseSensitive = false;
|
|
1630
|
+
// What the parser read the slash as, so that the two agree here as they do in HTML
|
|
1631
|
+
options.keepClosingSlash = options.keepClosingSlashHTML ?? false;
|
|
1632
|
+
options.nameParent = nameParent; // Preserve for the element tag itself
|
|
1633
|
+
options.name = options.nameHTML ?? lowercase;
|
|
1634
|
+
options.insideForeignContent = false;
|
|
1635
|
+
// Note: `removeAttributeQuotes`, `removeTagWhitespace`, and `decodeEntities`
|
|
1636
|
+
// stay disabled (inherited from SVG context) because the entire SVG block
|
|
1637
|
+
// must be valid XML for SVGO processing
|
|
1638
|
+
useNameParentForTag = true;
|
|
1639
|
+
pushedContext = true;
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
// `nameParent` is always set when `useNameParentForTag` is true; the extra check only narrows the type
|
|
1643
|
+
tag = (useNameParentForTag && options.nameParent ? options.nameParent : options.name)(tag);
|
|
1644
|
+
currentTag = tag;
|
|
1645
|
+
charsPrevTag = tag;
|
|
1646
|
+
if (!inlineTextSet.has(tag)) {
|
|
1647
|
+
currentChars = '';
|
|
1648
|
+
}
|
|
1649
|
+
hasChars = false;
|
|
1650
|
+
currentAttrs = attrs;
|
|
1651
|
+
|
|
1652
|
+
let optional = options.removeOptionalTags;
|
|
1653
|
+
if (optional) {
|
|
1654
|
+
const htmlTag = htmlElements.has(tag);
|
|
1655
|
+
// `<html>` may be omitted if first thing inside is not a comment
|
|
1656
|
+
// `<head>` may be omitted if first thing inside is an element
|
|
1657
|
+
// `<body>` may be omitted if first thing inside is not space, comment, `<meta>`, `<link>`, `<script>`, `<style>`, or `<template>`
|
|
1658
|
+
// `<colgroup>` may be omitted if first thing inside is `<col>`
|
|
1659
|
+
// `<tbody>` may be omitted if first thing inside is `<tr>`
|
|
1660
|
+
if (htmlTag && canRemoveParentTag(optionalStartTag, tag)) {
|
|
1661
|
+
removeStartTag();
|
|
1662
|
+
}
|
|
1663
|
+
optionalStartTag = '';
|
|
1664
|
+
// End-tag-followed-by-start-tag omission rules
|
|
1665
|
+
if (htmlTag && canRemovePrecedingTag(optionalEndTag, tag)) {
|
|
1666
|
+
if (optionalEndTagEmitted) {
|
|
1667
|
+
removeEndTag();
|
|
1668
|
+
}
|
|
1669
|
+
// `<colgroup>` cannot be omitted if preceding `</colgroup>` is omitted
|
|
1670
|
+
// `<tbody>` cannot be omitted if preceding `</tbody>`, `</thead>`, or `</tfoot>` is omitted
|
|
1671
|
+
optional = !isStartTagMandatory(optionalEndTag, tag);
|
|
1672
|
+
}
|
|
1673
|
+
optionalEndTag = '';
|
|
1674
|
+
optionalEndTagEmitted = false;
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
// Set whitespace flags for nested tags (e.g., `<code>` within a `<pre>`)
|
|
1678
|
+
if (options.collapseWhitespace) {
|
|
1679
|
+
if (!stackNoTrimWhitespace.length) {
|
|
1680
|
+
squashTrailingWhitespace(tag);
|
|
1681
|
+
}
|
|
1682
|
+
if (!unary) {
|
|
1683
|
+
if (!canTrimWhitespace(tag, attrs) || stackNoTrimWhitespace.length) {
|
|
1684
|
+
stackNoTrimWhitespace.push(tag);
|
|
1685
|
+
if (tag === 'pre' || tag === 'textarea') preTextareaDepth++;
|
|
1686
|
+
}
|
|
1687
|
+
if (!canCollapseWhitespace(tag, attrs) || stackNoCollapseWhitespace.length) {
|
|
1688
|
+
stackNoCollapseWhitespace.push(tag);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
// Track SVG subtree for SVGO block processing
|
|
1694
|
+
if (lowerTag === 'svg' && options.minifySVG && !unary) {
|
|
1695
|
+
if (svgDepth === 0) {
|
|
1696
|
+
svgBufferStartIndex = buffer.length; // Record position before <svg> is pushed
|
|
1697
|
+
}
|
|
1698
|
+
svgDepth++;
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
const openTag = '<' + tag;
|
|
1702
|
+
// SVGO reads the whole SVG block as XML, where an element closes itself or not, so
|
|
1703
|
+
// every unary element in there is written with a slash
|
|
1704
|
+
const needsXMLSlash = unary && Boolean(options.insideSVG) && Boolean(options.minifySVG);
|
|
1705
|
+
const hasUnarySlash = needsXMLSlash || (unarySlash && (useNameParentForTag ? optionsParent : options).keepClosingSlash);
|
|
1706
|
+
|
|
1707
|
+
buffer.push(openTag);
|
|
1708
|
+
|
|
1709
|
+
// Remove duplicate attributes (per HTML spec, first occurrence wins)
|
|
1710
|
+
// Duplicate attributes result in invalid HTML
|
|
1711
|
+
// https://html.spec.whatwg.org/multipage/parsing.html#attribute-name-state
|
|
1712
|
+
deduplicateAttributes(attrs, Boolean(options.caseSensitive));
|
|
1713
|
+
|
|
1714
|
+
if (options.sortAttributes) {
|
|
1715
|
+
// By the time tags are processed, `createSortFns` has replaced any truthy non-function value
|
|
1716
|
+
/** @type {(tag: string, attrs: HTMLAttribute[]) => void} */ (options.sortAttributes)(tag, attrs);
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
const attrResults = new Array(attrs.length);
|
|
1720
|
+
let anyThenable = false;
|
|
1721
|
+
for (let i = 0; i < attrs.length; i++) {
|
|
1722
|
+
const result = normalizeAttr(/** @type {HTMLAttribute} */ (attrs[i]), attrs, tag, options, minifyHTML);
|
|
1723
|
+
if (!anyThenable && isThenable(result)) {
|
|
1724
|
+
anyThenable = true;
|
|
1725
|
+
}
|
|
1726
|
+
attrResults[i] = result;
|
|
1727
|
+
}
|
|
1728
|
+
// The `isThenable` probe guarantees the sync branch holds no promises
|
|
1729
|
+
const normalizedAttrs = /** @type {Array<{name: string, value: string | undefined, attr: HTMLAttribute} | undefined>} */ (anyThenable ? await Promise.all(attrResults) : attrResults);
|
|
1730
|
+
// Find the last kept attribute, then emit in order—avoids the
|
|
1731
|
+
// intermediate parts array and reverse of the previous approach
|
|
1732
|
+
let lastKeptIndex = -1;
|
|
1733
|
+
for (let i = normalizedAttrs.length - 1; i >= 0; i--) {
|
|
1734
|
+
if (normalizedAttrs[i]) {
|
|
1735
|
+
lastKeptIndex = i;
|
|
1736
|
+
break;
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
if (lastKeptIndex !== -1) {
|
|
1740
|
+
buffer.push(' ');
|
|
1741
|
+
for (let i = 0; i <= lastKeptIndex; i++) {
|
|
1742
|
+
const normalizedAttr = normalizedAttrs[i];
|
|
1743
|
+
if (normalizedAttr) {
|
|
1744
|
+
buffer.push(buildAttr(normalizedAttr, hasUnarySlash, options, i === lastKeptIndex, uidAttr));
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
} else if (optional && optionalStartTags.has(tag)) {
|
|
1748
|
+
// Start tag must never be omitted if it has any attributes
|
|
1749
|
+
optionalStartTag = tag;
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
buffer.push(buffer.pop() + (hasUnarySlash ? '/' : '') + '>');
|
|
1753
|
+
|
|
1754
|
+
if (autoGenerated && !options.includeAutoGeneratedTags) {
|
|
1755
|
+
removeStartTag();
|
|
1756
|
+
optionalStartTag = '';
|
|
1757
|
+
currentTag = '';
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
// `end` restores what a start tag pushed, and a unary tag never reaches it
|
|
1761
|
+
if (unary && pushedContext) {
|
|
1762
|
+
options = optionsParent;
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
// What a unary tag holds ends with the tag, so no text can belong to it
|
|
1766
|
+
if (unary) {
|
|
1767
|
+
currentTag = '';
|
|
1768
|
+
}
|
|
1769
|
+
},
|
|
1770
|
+
end: function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ autoGenerated) {
|
|
1771
|
+
// As in `start`: `lowerTag` stays '' when no foreign content is around
|
|
1772
|
+
let lowerTag = '';
|
|
1773
|
+
if (hasForeignContext) {
|
|
1774
|
+
lowerTag = tag.toLowerCase();
|
|
1775
|
+
// Restore parent context when exiting SVG/MathML or HTML-in-foreign-content elements
|
|
1776
|
+
if (lowerTag === 'svg' || lowerTag === 'math') {
|
|
1777
|
+
options = Object.getPrototypeOf(options);
|
|
1778
|
+
} else if ((lowerTag === 'foreignobject' || lowerTag === 'annotation-xml') &&
|
|
1779
|
+
!options.insideForeignContent && Object.getPrototypeOf(options).insideForeignContent) {
|
|
1780
|
+
options = Object.getPrototypeOf(options);
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
tag = options.name(tag);
|
|
1784
|
+
|
|
1785
|
+
// Check if current tag is in a whitespace stack
|
|
1786
|
+
if (options.collapseWhitespace) {
|
|
1787
|
+
if (stackNoTrimWhitespace.length) {
|
|
1788
|
+
if (tag === stackNoTrimWhitespace[stackNoTrimWhitespace.length - 1]) {
|
|
1789
|
+
if (tag === 'pre' || tag === 'textarea') preTextareaDepth--;
|
|
1790
|
+
stackNoTrimWhitespace.pop();
|
|
1791
|
+
}
|
|
1792
|
+
} else {
|
|
1793
|
+
squashTrailingWhitespace('/' + tag);
|
|
1794
|
+
}
|
|
1795
|
+
if (stackNoCollapseWhitespace.length &&
|
|
1796
|
+
tag === stackNoCollapseWhitespace[stackNoCollapseWhitespace.length - 1]) {
|
|
1797
|
+
stackNoCollapseWhitespace.pop();
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
let isElementEmpty = false;
|
|
1802
|
+
if (tag === currentTag) {
|
|
1803
|
+
currentTag = '';
|
|
1804
|
+
isElementEmpty = !hasChars;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
if (options.removeOptionalTags) {
|
|
1808
|
+
// `<html>`, `<head>` or `<body>` may be omitted if the element is empty
|
|
1809
|
+
if (isElementEmpty && topLevelElements.has(optionalStartTag)) {
|
|
1810
|
+
removeStartTag();
|
|
1811
|
+
}
|
|
1812
|
+
optionalStartTag = '';
|
|
1813
|
+
// `</html>` or `</body>` may be omitted if not followed by comment,
|
|
1814
|
+
// `</head>` may be omitted if not followed by space or comment,
|
|
1815
|
+
// `</p>` may be omitted if no more content in parent,
|
|
1816
|
+
// unless parent is in `pInlineElements` or is a custom element
|
|
1817
|
+
// (https://html.spec.whatwg.org/multipage/syntax.html#optional-tags);
|
|
1818
|
+
// except for `</dt>` or `</thead>`, end tags may be omitted if no more content in parent element
|
|
1819
|
+
if (tag && optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag) && (optionalEndTag !== 'p' || (!pInlineElements.has(tag) && !tag.includes('-')))) {
|
|
1820
|
+
removeEndTag();
|
|
1821
|
+
}
|
|
1822
|
+
optionalEndTag = optionalEndTags.has(tag) ? tag : '';
|
|
1823
|
+
optionalEndTagEmitted = true;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
if (options.removeEmptyElements && isElementEmpty && !options.insideForeignContent && canRemoveElement(tag, attrs)) {
|
|
1827
|
+
let preserve = false;
|
|
1828
|
+
if (removeEmptyElementsExcept.length) {
|
|
1829
|
+
// Normalize attribute names for comparison with specs
|
|
1830
|
+
const normalizedAttrs = attrs.map((/** @type {HTMLAttribute} */ attr) => ({ ...attr, name: resolveName(attr.name) }));
|
|
1831
|
+
preserve = shouldPreserveEmptyElement(tag, normalizedAttrs, removeEmptyElementsExcept);
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
if (!preserve) {
|
|
1835
|
+
// Remove last element from buffer
|
|
1836
|
+
removeStartTag();
|
|
1837
|
+
optionalStartTag = '';
|
|
1838
|
+
optionalEndTag = '';
|
|
1839
|
+
optionalEndTagEmitted = false;
|
|
1840
|
+
} else {
|
|
1841
|
+
// Preserve the element—add closing tag
|
|
1842
|
+
if (autoGenerated && !options.includeAutoGeneratedTags) {
|
|
1843
|
+
optionalEndTagEmitted = false;
|
|
1844
|
+
} else {
|
|
1845
|
+
buffer.push('</' + tag + '>');
|
|
1846
|
+
}
|
|
1847
|
+
charsPrevTag = '/' + tag;
|
|
1848
|
+
if (!inlineElements.has(tag)) {
|
|
1849
|
+
currentChars = '';
|
|
1850
|
+
} else if (isElementEmpty) {
|
|
1851
|
+
currentChars += '|';
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
} else {
|
|
1855
|
+
if (autoGenerated && !options.includeAutoGeneratedTags) {
|
|
1856
|
+
optionalEndTagEmitted = false;
|
|
1857
|
+
} else {
|
|
1858
|
+
buffer.push('</' + tag + '>');
|
|
1859
|
+
}
|
|
1860
|
+
charsPrevTag = '/' + tag;
|
|
1861
|
+
if (!inlineElements.has(tag)) {
|
|
1862
|
+
currentChars = '';
|
|
1863
|
+
} else if (isElementEmpty) {
|
|
1864
|
+
currentChars += '|';
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
// SVG subtree capture: Record end position for post-processing with SVGO
|
|
1869
|
+
if (lowerTag === 'svg' && options.minifySVG && svgDepth > 0) {
|
|
1870
|
+
svgDepth--;
|
|
1871
|
+
if (svgDepth === 0 && svgBufferStartIndex >= 0) {
|
|
1872
|
+
svgBlocks.push({ start: svgBufferStartIndex, end: buffer.length });
|
|
1873
|
+
svgBufferStartIndex = -1;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
},
|
|
1877
|
+
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs) {
|
|
1878
|
+
// Publish this node’s context for the `charsCollapse`/`charsFinalize` phases
|
|
1879
|
+
textPrevTag = prevTag === '' ? 'comment' : prevTag;
|
|
1880
|
+
textNextTag = nextTag === '' ? 'comment' : nextTag;
|
|
1881
|
+
textPrevAttrs = prevAttrs || [];
|
|
1882
|
+
textNextAttrs = nextAttrs || [];
|
|
1883
|
+
|
|
1884
|
+
// Detect whether any async work is actually needed for this text node
|
|
1885
|
+
const needsDecode = options.decodeEntities && text && !holdsRawText() && text.indexOf('&') !== -1;
|
|
1886
|
+
const needsProcessScript = specialContentElements.has(currentTag) && (options.processScripts || hasJsonScriptType(currentAttrs));
|
|
1887
|
+
const needsMinifyJS = options.minifyJS !== identity && isExecutableScript(currentTag, currentAttrs);
|
|
1888
|
+
const isModuleScript = needsMinifyJS && currentAttrs.some(
|
|
1889
|
+
a => a.name.toLowerCase() === 'type' && (a.value ?? '').trim().toLowerCase() === 'module'
|
|
1890
|
+
);
|
|
1891
|
+
const needsMinifyCSS = options.minifyCSS !== identity && isStyleElement(currentTag, currentAttrs);
|
|
1892
|
+
|
|
1893
|
+
// Fast path: All work is sync—skip async machinery entirely
|
|
1894
|
+
if (!needsDecode && !needsProcessScript && !needsMinifyJS && !needsMinifyCSS) {
|
|
1895
|
+
charsFinalize(charsCollapse(text));
|
|
1896
|
+
return;
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
// Slow path: At least one async step required
|
|
1900
|
+
return (async () => {
|
|
1901
|
+
if (needsDecode) {
|
|
1902
|
+
text = (await getDecodeHTML())(text);
|
|
1903
|
+
}
|
|
1904
|
+
text = charsCollapse(text);
|
|
1905
|
+
if (needsProcessScript) {
|
|
1906
|
+
text = await processScript(text, options, currentAttrs, minifyHTML);
|
|
1907
|
+
}
|
|
1908
|
+
if (needsMinifyJS) {
|
|
1909
|
+
const prewarmed = jsPrewarmed?.get((isModuleScript ? 'm|' : '|') + text);
|
|
1910
|
+
text = prewarmed ? await prewarmed : await options.minifyJS(text, false, isModuleScript);
|
|
1911
|
+
}
|
|
1912
|
+
if (needsMinifyCSS) {
|
|
1913
|
+
text = await options.minifyCSS(text, undefined, options.cssContext);
|
|
1914
|
+
}
|
|
1915
|
+
charsFinalize(text);
|
|
1916
|
+
})();
|
|
1917
|
+
},
|
|
1918
|
+
comment: function (/** @type {string} */ text, /** @type {boolean} */ nonStandard) {
|
|
1919
|
+
const prefix = nonStandard ? '<!' : '<!--';
|
|
1920
|
+
const suffix = nonStandard ? '>' : '-->';
|
|
1921
|
+
|
|
1922
|
+
if (options.removeComments) {
|
|
1923
|
+
if (isIgnoredComment(text, options)) {
|
|
1924
|
+
text = prefix + text + suffix;
|
|
1925
|
+
} else {
|
|
1926
|
+
text = '';
|
|
1927
|
+
}
|
|
1928
|
+
} else {
|
|
1929
|
+
text = prefix + text + suffix;
|
|
1930
|
+
}
|
|
1931
|
+
commentFinalize(text);
|
|
1932
|
+
},
|
|
1933
|
+
doctype: function (/** @type {string} */ doctype) {
|
|
1934
|
+
buffer.push(options.useShortDoctype
|
|
1935
|
+
? '<!doctype' +
|
|
1936
|
+
(options.removeTagWhitespace ? '' : ' ') + 'html>'
|
|
1937
|
+
: collapseWhitespaceAll(doctype));
|
|
1938
|
+
}
|
|
1939
|
+
});
|
|
1940
|
+
|
|
1941
|
+
await parser.parse();
|
|
1942
|
+
|
|
1943
|
+
// Post-processing: Optimize SVG blocks with SVGO
|
|
1944
|
+
// Run all SVGO calls in parallel, then splice results in reverse to preserve indices
|
|
1945
|
+
const minifySVG = options.minifySVG;
|
|
1946
|
+
if (minifySVG && svgBlocks.length) {
|
|
1947
|
+
const optimized = await Promise.all(
|
|
1948
|
+
svgBlocks.map(({ start, end }) =>
|
|
1949
|
+
minifySVG(buffer.slice(start, end).join(''))
|
|
1950
|
+
)
|
|
1951
|
+
);
|
|
1952
|
+
for (let i = svgBlocks.length - 1; i >= 0; i--) {
|
|
1953
|
+
const block = svgBlocks[i];
|
|
1954
|
+
if (block) buffer.splice(block.start, block.end - block.start, optimized[i] ?? '');
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
if (options.removeOptionalTags) {
|
|
1959
|
+
// `<html>` may be omitted if first thing inside is not a comment
|
|
1960
|
+
// `<head>` or `<body>` may be omitted if empty
|
|
1961
|
+
if (topLevelElements.has(optionalStartTag)) {
|
|
1962
|
+
removeStartTag();
|
|
1963
|
+
}
|
|
1964
|
+
// except for `</dt>` or `</thead>`, end tags may be omitted if no more content in parent element
|
|
1965
|
+
if (optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag)) {
|
|
1966
|
+
removeEndTag();
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
if (options.collapseWhitespace) {
|
|
1970
|
+
squashTrailingWhitespace('br');
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
return joinResultSegments(buffer, options, uidPattern
|
|
1974
|
+
? function (/** @type {string} */ str) {
|
|
1975
|
+
return str.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ match, /** @type {string} */ prefix, /** @type {string} */ index, /** @type {string} */ suffix) {
|
|
1976
|
+
let chunk = ignoredCustomMarkupChunks[+index]?.[0] ?? match;
|
|
1977
|
+
if (options.collapseWhitespace) {
|
|
1978
|
+
if (prefix !== '\t') {
|
|
1979
|
+
chunk = prefix + chunk;
|
|
1980
|
+
}
|
|
1981
|
+
if (suffix !== '\t') {
|
|
1982
|
+
chunk += suffix;
|
|
1983
|
+
}
|
|
1984
|
+
return collapseWhitespace(chunk, {
|
|
1985
|
+
preserveLineBreaks: options.preserveLineBreaks,
|
|
1986
|
+
conservativeCollapse: !options.trimCustomFragments
|
|
1987
|
+
}, /^[ \n\r\t\f]/.test(chunk), /[ \n\r\t\f]$/.test(chunk));
|
|
1988
|
+
}
|
|
1989
|
+
return chunk;
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
: identity, uidIgnore
|
|
1993
|
+
? function (/** @type {string} */ str) {
|
|
1994
|
+
return str.replace(new RegExp('<!--' + uidIgnore + '([0-9]+)-->', 'g'), function (/** @type {string} */ _match, /** @type {string} */ index) {
|
|
1995
|
+
return ignoredMarkupChunks[+index] ?? '';
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
: identity);
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
/**
|
|
2002
|
+
* @param {string[]} results
|
|
2003
|
+
* @param {ProcessedOptions} options
|
|
2004
|
+
* @param {Function} restoreCustom
|
|
2005
|
+
* @param {Function} restoreIgnore
|
|
2006
|
+
*/
|
|
2007
|
+
function joinResultSegments(results, options, restoreCustom, restoreIgnore) {
|
|
2008
|
+
let str;
|
|
2009
|
+
const maxLineLength = options.maxLineLength;
|
|
2010
|
+
const noNewlinesBeforeTagClose = options.noNewlinesBeforeTagClose;
|
|
2011
|
+
|
|
2012
|
+
if (maxLineLength) {
|
|
2013
|
+
let line = ''; const lines = [];
|
|
2014
|
+
// Index-based scan—`Array.shift()` is O(n) per call, which would make this
|
|
2015
|
+
// loop quadratic on documents with many segments
|
|
2016
|
+
let index = 0;
|
|
2017
|
+
while (index < results.length) {
|
|
2018
|
+
const len = line.length;
|
|
2019
|
+
const cur = results[index] ?? '';
|
|
2020
|
+
const end = cur.indexOf('\n');
|
|
2021
|
+
const isClosingTag = Boolean(cur.match(endTag));
|
|
2022
|
+
const shouldKeepSameLine = noNewlinesBeforeTagClose && isClosingTag;
|
|
2023
|
+
|
|
2024
|
+
if (end < 0) {
|
|
2025
|
+
line += restoreIgnore(restoreCustom(cur));
|
|
2026
|
+
index++;
|
|
2027
|
+
} else {
|
|
2028
|
+
line += restoreIgnore(restoreCustom(cur.slice(0, end)));
|
|
2029
|
+
results[index] = cur.slice(end + 1);
|
|
2030
|
+
}
|
|
2031
|
+
if (len > 0 && line.length > maxLineLength && !shouldKeepSameLine) {
|
|
2032
|
+
lines.push(line.slice(0, len));
|
|
2033
|
+
line = line.slice(len);
|
|
2034
|
+
} else if (end >= 0) {
|
|
2035
|
+
lines.push(line);
|
|
2036
|
+
line = '';
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
if (line) {
|
|
2040
|
+
lines.push(line);
|
|
2041
|
+
}
|
|
2042
|
+
str = lines.join('\n');
|
|
2043
|
+
} else {
|
|
2044
|
+
str = restoreIgnore(restoreCustom(results.join('')));
|
|
2045
|
+
}
|
|
2046
|
+
return options.collapseWhitespace ? collapseWhitespace(str, options, true, true) : str;
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
/**
|
|
2050
|
+
* Initialize minification caches with configurable sizes.
|
|
2051
|
+
*
|
|
2052
|
+
* Important behavior notes:
|
|
2053
|
+
* - Caches are created on the first `minify()` call and persist for the lifetime of the process
|
|
2054
|
+
* - Cache sizes are locked after first initialization—subsequent calls use the same caches
|
|
2055
|
+
* even if different `cacheCSS`/`cacheJS`/`cacheSVG` options are provided
|
|
2056
|
+
* - The first call’s options determine the cache sizes for subsequent calls
|
|
2057
|
+
* - Invalid values (NaN, Infinity, negative) fall back to the default size (500)
|
|
2058
|
+
*/
|
|
2059
|
+
/** @param {MinifierOptions} options */
|
|
2060
|
+
function initCaches(options) {
|
|
2061
|
+
// Only create caches once (on first call)—sizes are locked after this
|
|
2062
|
+
if (!cssMinifyCache) {
|
|
2063
|
+
const defaultSize = 500;
|
|
2064
|
+
|
|
2065
|
+
// Helper to parse env var—returns parsed number (including 0) or undefined if absent, invalid, or negative
|
|
2066
|
+
const parseEnvCacheSize = (/** @type {string | undefined} */ envVar) => {
|
|
2067
|
+
if (envVar === undefined) return undefined;
|
|
2068
|
+
const parsed = Number(envVar);
|
|
2069
|
+
if (Number.isNaN(parsed) || !Number.isFinite(parsed) || parsed < 0) {
|
|
2070
|
+
return undefined;
|
|
2071
|
+
}
|
|
2072
|
+
return parsed;
|
|
2073
|
+
};
|
|
2074
|
+
|
|
2075
|
+
// Non-finite and negative sizes fall back to `defaultSize`, as they do for the
|
|
2076
|
+
// environment variables above
|
|
2077
|
+
const sanitizeSize = (/** @type {number} */ size) => Number.isFinite(size) && size >= 0 ? Math.floor(size) : defaultSize;
|
|
2078
|
+
|
|
2079
|
+
// Get cache sizes with precedence: Options > env > default
|
|
2080
|
+
const cssSize = options.cacheCSS !== undefined ? options.cacheCSS
|
|
2081
|
+
: (parseEnvCacheSize(process.env.HMN_CACHE_CSS) ?? defaultSize);
|
|
2082
|
+
const jsSize = options.cacheJS !== undefined ? options.cacheJS
|
|
2083
|
+
: (parseEnvCacheSize(process.env.HMN_CACHE_JS) ?? defaultSize);
|
|
2084
|
+
const svgSize = options.cacheSVG !== undefined ? options.cacheSVG
|
|
2085
|
+
: (parseEnvCacheSize(process.env.HMN_CACHE_SVG) ?? defaultSize);
|
|
2086
|
+
|
|
2087
|
+
const cssFinalSize = sanitizeSize(cssSize);
|
|
2088
|
+
const jsFinalSize = sanitizeSize(jsSize);
|
|
2089
|
+
const svgFinalSize = sanitizeSize(svgSize);
|
|
2090
|
+
|
|
2091
|
+
cssMinifyCache = new LRU(cssFinalSize);
|
|
2092
|
+
jsMinifyCache = new LRU(jsFinalSize);
|
|
2093
|
+
svgMinifyCache = new LRU(svgFinalSize);
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
return { cssMinifyCache, jsMinifyCache, svgMinifyCache };
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
/**
|
|
2100
|
+
* Get hit/miss statistics for the CSS, JavaScript, and SVG minification caches.
|
|
2101
|
+
*
|
|
2102
|
+
* Each cache is created lazily on the first `minify()` call (see `initCaches`); before
|
|
2103
|
+
* that first call, or for a cache never exercised (e.g., `minifyCSS` disabled), its
|
|
2104
|
+
* entry reports all-zero stats.
|
|
2105
|
+
*
|
|
2106
|
+
* @returns {{ css: CacheStats, js: CacheStats, svg: CacheStats }}
|
|
2107
|
+
*/
|
|
2108
|
+
export function getCacheStats() {
|
|
2109
|
+
return {
|
|
2110
|
+
css: cacheStatsOrEmpty(cssMinifyCache),
|
|
2111
|
+
js: cacheStatsOrEmpty(jsMinifyCache),
|
|
2112
|
+
svg: cacheStatsOrEmpty(svgMinifyCache)
|
|
2113
|
+
};
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
// Memoized options processing: Batch runs typically pass one options object to
|
|
2117
|
+
// many `minify()` calls, and full processing (regex parsing, closure creation,
|
|
2118
|
+
// option-signature stringification) is comparatively expensive. The cache is
|
|
2119
|
+
// keyed on the options object and verified against a deep snapshot, so any
|
|
2120
|
+
// mutation of a reused object—top-level or nested (e.g., engine options)—still
|
|
2121
|
+
// triggers reprocessing. Each call works on a shallow copy of the processed
|
|
2122
|
+
// options, since `minifyHTML` reassigns top-level keys (wrapped minifiers,
|
|
2123
|
+
// sorters, UID comment patterns) that must not leak across calls.
|
|
2124
|
+
/** @type {MinifierOptions} */
|
|
2125
|
+
const EMPTY_OPTIONS = {};
|
|
2126
|
+
/** @type {WeakMap<object, {snapshot: unknown, processed: ProcessedOptions}>} */
|
|
2127
|
+
const processedOptionsCache = new WeakMap();
|
|
2128
|
+
|
|
2129
|
+
// A “plain” value is an array or plain object, which the snapshot copies and
|
|
2130
|
+
// compares structurally; anything else (functions, RegExps, class instances)
|
|
2131
|
+
// is kept and compared by identity—a false mismatch merely reprocesses, which
|
|
2132
|
+
// is the pre-memoization behavior
|
|
2133
|
+
/** @param {unknown} value */
|
|
2134
|
+
function isPlainValue(value) {
|
|
2135
|
+
if (Array.isArray(value)) return true;
|
|
2136
|
+
if (value === null || typeof value !== 'object') return false;
|
|
2137
|
+
const proto = Object.getPrototypeOf(value);
|
|
2138
|
+
return proto === Object.prototype || proto === null;
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
// Budget for `snapshotValue`: Bounds the work spent on pathological options
|
|
2142
|
+
// objects; when the budget runs out, the object isn’t memoized and falls
|
|
2143
|
+
// back to per-call processing
|
|
2144
|
+
const SNAPSHOT_MAX_NODES = 1024;
|
|
2145
|
+
const SNAPSHOT_UNSAFE = Symbol('snapshot-unsafe');
|
|
2146
|
+
// Skipped memoization is fail-safe but silent—warn once per process
|
|
2147
|
+
let snapshotBudgetWarned = false;
|
|
2148
|
+
|
|
2149
|
+
/**
|
|
2150
|
+
* @param {unknown} value
|
|
2151
|
+
* @param {{budget: number}} state
|
|
2152
|
+
* @returns {unknown} The copy, or `SNAPSHOT_UNSAFE` once the budget is exhausted
|
|
2153
|
+
*/
|
|
2154
|
+
function snapshotValue(value, state) {
|
|
2155
|
+
if (!isPlainValue(value)) return value;
|
|
2156
|
+
if (--state.budget < 0) return SNAPSHOT_UNSAFE;
|
|
2157
|
+
if (Array.isArray(value)) {
|
|
2158
|
+
const copy = new Array(value.length);
|
|
2159
|
+
for (let i = 0; i < value.length; i++) {
|
|
2160
|
+
const child = snapshotValue(value[i], state);
|
|
2161
|
+
if (child === SNAPSHOT_UNSAFE) return SNAPSHOT_UNSAFE;
|
|
2162
|
+
copy[i] = child;
|
|
2163
|
+
}
|
|
2164
|
+
return copy;
|
|
2165
|
+
}
|
|
2166
|
+
/** @type {Record<string, unknown>} */
|
|
2167
|
+
const copy = {};
|
|
2168
|
+
const source = /** @type {Record<string, unknown>} */ (value);
|
|
2169
|
+
for (const key of Object.keys(source)) {
|
|
2170
|
+
const child = snapshotValue(source[key], state);
|
|
2171
|
+
if (child === SNAPSHOT_UNSAFE) return SNAPSHOT_UNSAFE;
|
|
2172
|
+
copy[key] = child;
|
|
2173
|
+
}
|
|
2174
|
+
return copy;
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
/**
|
|
2178
|
+
* @param {unknown} snapshot
|
|
2179
|
+
* @param {unknown} current
|
|
2180
|
+
* @returns {boolean}
|
|
2181
|
+
*/
|
|
2182
|
+
function valueUnchanged(snapshot, current) {
|
|
2183
|
+
if (snapshot === current) return true;
|
|
2184
|
+
if (!isPlainValue(snapshot) || !isPlainValue(current)) return false;
|
|
2185
|
+
if (Array.isArray(snapshot)) {
|
|
2186
|
+
if (!Array.isArray(current) || snapshot.length !== current.length) return false;
|
|
2187
|
+
for (let i = 0; i < snapshot.length; i++) {
|
|
2188
|
+
if (!valueUnchanged(snapshot[i], current[i])) return false;
|
|
2189
|
+
}
|
|
2190
|
+
return true;
|
|
2191
|
+
}
|
|
2192
|
+
if (Array.isArray(current)) return false;
|
|
2193
|
+
const snapshotObj = /** @type {Record<string, unknown>} */ (snapshot);
|
|
2194
|
+
const currentObj = /** @type {Record<string, unknown>} */ (current);
|
|
2195
|
+
const snapshotKeys = Object.keys(snapshotObj);
|
|
2196
|
+
if (snapshotKeys.length !== Object.keys(currentObj).length) return false;
|
|
2197
|
+
for (const key of snapshotKeys) {
|
|
2198
|
+
if (!Object.hasOwn(currentObj, key) || !valueUnchanged(snapshotObj[key], currentObj[key])) {
|
|
2199
|
+
return false;
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
return true;
|
|
2203
|
+
}
|
|
2204
|
+
|
|
2205
|
+
/**
|
|
2206
|
+
* @param {string} value
|
|
2207
|
+
* @param {MinifierOptions} [options]
|
|
2208
|
+
* @returns {Promise<string>}
|
|
2209
|
+
*/
|
|
2210
|
+
export const minify = async function (value, options) {
|
|
2211
|
+
const start = Date.now();
|
|
2212
|
+
|
|
2213
|
+
const inputOptions = options || EMPTY_OPTIONS;
|
|
2214
|
+
|
|
2215
|
+
// Initialize caches on first use with configurable sizes
|
|
2216
|
+
const caches = initCaches(inputOptions);
|
|
2217
|
+
|
|
2218
|
+
// WeakMap keys must be objects
|
|
2219
|
+
const canMemoize = typeof inputOptions === 'object' && inputOptions !== null;
|
|
2220
|
+
const cached = canMemoize ? processedOptionsCache.get(inputOptions) : undefined;
|
|
2221
|
+
/** @type {ProcessedOptions} */
|
|
2222
|
+
let processedBase;
|
|
2223
|
+
// `valueUnchanged` needs no budget of its own: Recursion is bounded by the
|
|
2224
|
+
// stored snapshot, which is a finite tree of at most `SNAPSHOT_MAX_NODES`
|
|
2225
|
+
if (cached && valueUnchanged(cached.snapshot, inputOptions)) {
|
|
2226
|
+
processedBase = cached.processed;
|
|
2227
|
+
} else {
|
|
2228
|
+
processedBase = processOptions(inputOptions, {
|
|
2229
|
+
getLightningCSS,
|
|
2230
|
+
getTerser,
|
|
2231
|
+
getSwc,
|
|
2232
|
+
getSvgo,
|
|
2233
|
+
cssMinifyCache: caches.cssMinifyCache ?? undefined,
|
|
2234
|
+
jsMinifyCache: caches.jsMinifyCache ?? undefined,
|
|
2235
|
+
svgMinifyCache: caches.svgMinifyCache ?? undefined
|
|
2236
|
+
});
|
|
2237
|
+
if (canMemoize) {
|
|
2238
|
+
const snapshot = snapshotValue(inputOptions, { budget: SNAPSHOT_MAX_NODES });
|
|
2239
|
+
if (snapshot !== SNAPSHOT_UNSAFE) {
|
|
2240
|
+
processedOptionsCache.set(inputOptions, { snapshot, processed: processedBase });
|
|
2241
|
+
} else if (!snapshotBudgetWarned) {
|
|
2242
|
+
snapshotBudgetWarned = true;
|
|
2243
|
+
const warn = typeof inputOptions.log === 'function' ? inputOptions.log : console.warn;
|
|
2244
|
+
warn('HTML Minifier Next: Options object exceeds the memoization complexity limit; options will be processed on every call');
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
// Work on a shallow copy so per-call reassignments don’t reach the cached base
|
|
2249
|
+
const processedOptions = /** @type {ProcessedOptions} */ ({ ...processedBase });
|
|
2250
|
+
|
|
2251
|
+
// Warnings are deduplicated per document, so the state has to live on the per-call
|
|
2252
|
+
// copy; the `minifyCSS` closure hangs off the memoized base, shared across calls
|
|
2253
|
+
processedOptions.cssContext = { warned: new Set() };
|
|
2254
|
+
|
|
2255
|
+
// Unused-CSS removal needs the whole document’s symbols before the first `style`
|
|
2256
|
+
// element is minified, so collect them upfront from the raw input. A document
|
|
2257
|
+
// without a style sheet has nothing to remove from, and scanning it would be work
|
|
2258
|
+
// spent on an empty result.
|
|
2259
|
+
if (processedOptions.removeUnusedCSS && RE_STYLE_ELEMENT.test(value)) {
|
|
2260
|
+
processedOptions.cssContext.usedSymbols = collectUsedSymbols(
|
|
2261
|
+
value,
|
|
2262
|
+
processedOptions.removeUnusedCSS.scripts,
|
|
2263
|
+
value.indexOf('&') !== -1
|
|
2264
|
+
? /** @type {(text: string) => string} */ (await getDecodeHTML())
|
|
2265
|
+
: undefined
|
|
2266
|
+
);
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
let result = await minifyHTML(value, processedOptions);
|
|
2270
|
+
|
|
2271
|
+
// Post-processing: Merge consecutive inline scripts if enabled
|
|
2272
|
+
if (processedOptions.mergeScripts) {
|
|
2273
|
+
result = mergeConsecutiveScripts(result);
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
processedOptions.log('minified in: ' + (Date.now() - start) + 'ms');
|
|
2277
|
+
return result;
|
|
2278
|
+
};
|
|
2279
|
+
|
|
2280
|
+
// Exports
|
|
2281
|
+
|
|
2282
|
+
export {
|
|
2283
|
+
presets,
|
|
2284
|
+
getPreset,
|
|
2285
|
+
getPresetNames
|
|
2286
|
+
};
|
|
2287
|
+
|
|
2288
|
+
export default {
|
|
2289
|
+
minify,
|
|
2290
|
+
presets,
|
|
2291
|
+
getPreset,
|
|
2292
|
+
getPresetNames,
|
|
2293
|
+
getCacheStats
|
|
2294
|
+
};
|