@ohos-ports/html-minifier-next 8.4.2-beta.0 → 8.10.8-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/README.md +147 -33
- package/cli.js +70 -54
- package/dist/types/htmlminifier.d.ts +87 -33
- package/dist/types/htmlminifier.d.ts.map +1 -1
- package/dist/types/htmlparser.d.ts +4 -1
- package/dist/types/htmlparser.d.ts.map +1 -1
- package/dist/types/lib/attributes.d.ts +12 -10
- package/dist/types/lib/attributes.d.ts.map +1 -1
- package/dist/types/lib/constants.d.ts +38 -3
- package/dist/types/lib/constants.d.ts.map +1 -1
- package/dist/types/lib/content.d.ts.map +1 -1
- package/dist/types/lib/elements.d.ts.map +1 -1
- package/dist/types/lib/fragments.d.ts +1 -0
- package/dist/types/lib/fragments.d.ts.map +1 -1
- package/dist/types/lib/option-definitions.d.ts.map +1 -1
- package/dist/types/lib/options.d.ts +14 -46
- package/dist/types/lib/options.d.ts.map +1 -1
- package/dist/types/lib/unused-css.d.ts +34 -4
- package/dist/types/lib/unused-css.d.ts.map +1 -1
- package/dist/types/lib/urls.d.ts.map +1 -1
- package/dist/types/lib/utils.d.ts +31 -1
- package/dist/types/lib/utils.d.ts.map +1 -1
- package/dist/types/lib/whitespace.d.ts +57 -5
- package/dist/types/lib/whitespace.d.ts.map +1 -1
- package/dist/types/presets.d.ts +1 -2
- package/dist/types/presets.d.ts.map +1 -1
- package/dist/types/tokenchain.d.ts.map +1 -1
- package/html-minifier-next.schema.json +15 -7
- package/package.json +17 -18
- package/src/htmlminifier.js +1103 -392
- package/src/htmlparser.js +452 -200
- package/src/lib/attributes.js +201 -112
- package/src/lib/constants.js +130 -19
- package/src/lib/content.js +1 -6
- package/src/lib/elements.js +17 -12
- package/src/lib/file-pool.js +18 -2
- package/src/lib/file-write.js +87 -0
- package/src/lib/fragments.js +74 -8
- package/src/lib/option-definitions.js +17 -10
- package/src/lib/options.js +151 -71
- package/src/lib/unused-css.js +145 -27
- package/src/lib/urls.js +0 -9
- package/src/lib/utils.js +210 -45
- package/src/lib/whitespace.js +173 -63
- package/src/presets.js +1 -2
- package/src/tokenchain.js +1 -4
package/src/htmlminifier.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { HTMLParser
|
|
1
|
+
import { HTMLParser } from './htmlparser.js';
|
|
2
2
|
import TokenChain from './tokenchain.js';
|
|
3
3
|
import { presets, getPreset, getPresetNames } from './presets.js';
|
|
4
4
|
|
|
5
|
-
import { LRU, findTagEnd, identity, isThenable, lowercase, uniqueId } from './lib/utils.js';
|
|
6
|
-
import {
|
|
5
|
+
import { LRU, decodeForeignText, describeDependencyFailure, escapeXML, findTagEnd, identity, isThenable, lowercase, uniqueId } from './lib/utils.js';
|
|
6
|
+
import { collectUsage } from './lib/unused-css.js';
|
|
7
7
|
|
|
8
8
|
import {
|
|
9
9
|
RE_LEGACY_ENTITIES,
|
|
@@ -15,8 +15,11 @@ import {
|
|
|
15
15
|
RE_WS_ONLY,
|
|
16
16
|
RE_WS_NBSP_END,
|
|
17
17
|
RE_STYLE_ELEMENT,
|
|
18
|
+
formattingElements,
|
|
18
19
|
inlineElementsToKeepWhitespaceAround,
|
|
19
20
|
inlineElementsToKeepWhitespaceWithin,
|
|
21
|
+
inlineElementsTransparent,
|
|
22
|
+
inlineElementsTransparentAfter,
|
|
20
23
|
specialContentElements,
|
|
21
24
|
rawTextElements,
|
|
22
25
|
htmlElements,
|
|
@@ -26,16 +29,23 @@ import {
|
|
|
26
29
|
compactElements,
|
|
27
30
|
looseElements,
|
|
28
31
|
trailingElements,
|
|
29
|
-
|
|
32
|
+
pClosingParents,
|
|
33
|
+
namesForeignMixedCase,
|
|
34
|
+
MISSING_DEPENDENCY
|
|
30
35
|
} from './lib/constants.js';
|
|
31
36
|
|
|
32
37
|
import {
|
|
38
|
+
buildInlineSets,
|
|
39
|
+
defaultInlineSets,
|
|
40
|
+
endsWithWhitespace,
|
|
33
41
|
trimWhitespace,
|
|
34
42
|
collapseWhitespaceAll,
|
|
43
|
+
collapseNoBreakSpaces,
|
|
35
44
|
collapseWhitespace,
|
|
36
45
|
collapseWhitespaceSmart,
|
|
37
46
|
canCollapseWhitespace as defaultCanCollapseWhitespace,
|
|
38
|
-
canTrimWhitespace as defaultCanTrimWhitespace
|
|
47
|
+
canTrimWhitespace as defaultCanTrimWhitespace,
|
|
48
|
+
isAllWhitespace
|
|
39
49
|
} from './lib/whitespace.js';
|
|
40
50
|
|
|
41
51
|
import {
|
|
@@ -67,8 +77,6 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
67
77
|
|
|
68
78
|
/** @import { ProcessedOptions } from './lib/options.js' */
|
|
69
79
|
|
|
70
|
-
// Type definitions
|
|
71
|
-
|
|
72
80
|
/**
|
|
73
81
|
* @typedef {Object} HTMLAttribute
|
|
74
82
|
* Representation of an attribute from the HTML parser.
|
|
@@ -88,14 +96,39 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
88
96
|
* and usually default to a disabled/safe value unless noted.
|
|
89
97
|
*
|
|
90
98
|
* @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.
|
|
99
|
+
* Predicate that determines whether runs of whitespace inside a given element
|
|
100
|
+
* can be collapsed (whether its content may be trimmed is up to `canTrimWhitespace`).
|
|
93
101
|
*
|
|
94
102
|
* Default: Built-in `canCollapseWhitespace` function
|
|
95
103
|
*
|
|
104
|
+
* @prop {((text: string, type?: 'inline' | 'media') => boolean) | null} [canMinifyCSS]
|
|
105
|
+
* Synchronous predicate that determines whether the built-in `minifyCSS` may
|
|
106
|
+
* process a given piece of CSS—`type` is `undefined` for `style` elements,
|
|
107
|
+
* `'inline'` for `style` attributes, and `'media'` for `media` attributes.
|
|
108
|
+
* Returning false leaves that CSS as if `minifyCSS` were off, including its URLs
|
|
109
|
+
* and unused rules (within `svg` elements, SVGO still minifies it under `minifySVG`).
|
|
110
|
+
*
|
|
111
|
+
* Default: `null` (all CSS is minified)
|
|
112
|
+
*
|
|
113
|
+
* @prop {((text: string, inline?: boolean) => boolean) | null} [canMinifyJS]
|
|
114
|
+
* Synchronous predicate that determines whether the built-in `minifyJS` may
|
|
115
|
+
* process a given piece of JavaScript—`inline` is true for event handler
|
|
116
|
+
* attributes. Returning false leaves that JavaScript unminified (`mergeScripts`
|
|
117
|
+
* still applies).
|
|
118
|
+
*
|
|
119
|
+
* Default: `null` (all JavaScript is minified)
|
|
120
|
+
*
|
|
121
|
+
* @prop {((text: string) => boolean) | null} [canMinifySVG]
|
|
122
|
+
* Synchronous predicate that determines whether the built-in `minifySVG` may
|
|
123
|
+
* pass a given outermost `svg` element, nested ones included, to SVGO. It
|
|
124
|
+
* receives the element as serialized by the HTML pass (e.g., without comments
|
|
125
|
+
* under `removeComments`); returning false leaves it as that pass wrote it.
|
|
126
|
+
*
|
|
127
|
+
* Default: `null` (all SVG is minified)
|
|
128
|
+
*
|
|
96
129
|
* @prop {(tag: string | null, attrs: HTMLAttribute[] | undefined, canTrimWhitespace: (tag: string) => boolean) => boolean} [canTrimWhitespace]
|
|
97
|
-
* Predicate that determines whether
|
|
98
|
-
*
|
|
130
|
+
* Predicate that determines whether whitespace inside the element may be
|
|
131
|
+
* trimmed; where not, it stays as written, as in `pre`.
|
|
99
132
|
*
|
|
100
133
|
* Default: Built-in `canTrimWhitespace` function
|
|
101
134
|
*
|
|
@@ -127,9 +160,9 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
127
160
|
* Default: `500`
|
|
128
161
|
*
|
|
129
162
|
* @prop {boolean} [caseSensitive]
|
|
130
|
-
* When true, tag and attribute names are
|
|
131
|
-
* Useful for
|
|
132
|
-
*
|
|
163
|
+
* When true, tag and attribute names are written as in the source rather than in lowercase.
|
|
164
|
+
* Useful for framework components like `<MyButton>`. HTML names are still read in any case,
|
|
165
|
+
* so every option applies to them as without it; hooks get names as written.
|
|
133
166
|
*
|
|
134
167
|
* Default: `false`
|
|
135
168
|
*
|
|
@@ -148,9 +181,26 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
148
181
|
*
|
|
149
182
|
* Default: `false`
|
|
150
183
|
*
|
|
184
|
+
* @prop {boolean} [collapseEmptyAttributes]
|
|
185
|
+
* Collapse attributes with empty values to their name only (for example
|
|
186
|
+
* `alt=""` → `alt`), which the HTML parser reads the same way.
|
|
187
|
+
*
|
|
188
|
+
* Default: `false`
|
|
189
|
+
*
|
|
151
190
|
* @prop {boolean} [collapseInlineTagWhitespace]
|
|
152
191
|
* When false (default) whitespace around `inline` tags is preserved in
|
|
153
|
-
* more cases. When true, whitespace
|
|
192
|
+
* more cases. When true, whitespace between inline tags may be collapsed,
|
|
193
|
+
* except around text-level elements (like `a`, `code`, or `em`); whitespace
|
|
194
|
+
* next to text is kept as without the option.
|
|
195
|
+
* Must also enable `collapseWhitespace` to have effect.
|
|
196
|
+
*
|
|
197
|
+
* Default: `false`
|
|
198
|
+
*
|
|
199
|
+
* @prop {boolean} [collapseNoBreakSpaces]
|
|
200
|
+
* Remove whitespace next to a no-break space (`U+00A0`), narrow no-break
|
|
201
|
+
* space (`U+202F`), or figure space (`U+2007`) in text (for example
|
|
202
|
+
* `a b` → `a b`), which changes how the text renders. Runs of
|
|
203
|
+
* no-break spaces are kept.
|
|
154
204
|
* Must also enable `collapseWhitespace` to have effect.
|
|
155
205
|
*
|
|
156
206
|
* Default: `false`
|
|
@@ -231,9 +281,9 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
231
281
|
* Array of regexes used to identify fragments that should be
|
|
232
282
|
* preserved (for example server templates). These fragments are temporarily
|
|
233
283
|
* replaced during minification to avoid corrupting template code.
|
|
234
|
-
* The default preserves ASP/PHP-style tags.
|
|
284
|
+
* The default preserves ASP/PHP-style tags and XML declarations.
|
|
235
285
|
*
|
|
236
|
-
* Default: `[/<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/]`
|
|
286
|
+
* Default: `[/<%[\s\S]*?%>/, /<\?(?:php[\t\n\r ]|=|\$|xml(?:-stylesheet)?(?![\w-])|\s)[\s\S]*?\?>/i]`
|
|
237
287
|
*
|
|
238
288
|
* @prop {boolean} [includeAutoGeneratedTags]
|
|
239
289
|
* If false, tags marked as auto-generated by the parser will be omitted
|
|
@@ -270,7 +320,8 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
270
320
|
*
|
|
271
321
|
* @prop {number} [maxLineLength]
|
|
272
322
|
* Maximum line length for the output. When set the minifier will wrap
|
|
273
|
-
* output to the given number of characters where possible
|
|
323
|
+
* output to the given number of characters where possible, splitting
|
|
324
|
+
* lines only in tags—between attributes or before a tag’s `>`.
|
|
274
325
|
*
|
|
275
326
|
* Default: No limit
|
|
276
327
|
*
|
|
@@ -281,7 +332,7 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
281
332
|
*
|
|
282
333
|
* Default: `false`
|
|
283
334
|
*
|
|
284
|
-
* @prop {boolean | Partial<import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>> | ((text: string, type?: string) => Promise<string> | string)} [minifyCSS]
|
|
335
|
+
* @prop {boolean | Partial<import("@ohos-ports/lightningcss").TransformOptions<import("@ohos-ports/lightningcss").CustomAtRules>> | ((text: string, type?: string) => Promise<string> | string)} [minifyCSS]
|
|
285
336
|
* When true, enables CSS minification for inline `<style>` tags or
|
|
286
337
|
* `style` attributes. If an object is provided, it is passed to
|
|
287
338
|
* [Lightning CSS](https://www.npmjs.com/package/lightningcss)
|
|
@@ -314,15 +365,17 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
314
365
|
*
|
|
315
366
|
* @prop {boolean | Object} [minifySVG]
|
|
316
367
|
* When true, enables SVG minification using [SVGO](https://github.com/svg/svgo).
|
|
317
|
-
* Complete SVG subtrees are extracted and optimized as a block
|
|
318
|
-
*
|
|
368
|
+
* Complete SVG subtrees are extracted and optimized as a block, with the SVGO
|
|
369
|
+
* plugins that assume a standalone SVG file turned off.
|
|
370
|
+
* If an object is provided, it is passed to SVGO as configuration options; unless
|
|
371
|
+
* it sets `plugins`, it keeps that plugin set.
|
|
319
372
|
* If disabled, SVG content is minified using standard HTML rules only.
|
|
320
373
|
*
|
|
321
374
|
* Default: `false`
|
|
322
375
|
*
|
|
323
376
|
* @prop {boolean} [noNewlinesBeforeTagClose]
|
|
324
|
-
* When wrapping lines,
|
|
325
|
-
*
|
|
377
|
+
* When wrapping lines, never split a line in an end tag (e.g., keeps
|
|
378
|
+
* `</a>` from becoming `</a` and `>` on two lines).
|
|
326
379
|
*
|
|
327
380
|
* Default: `false`
|
|
328
381
|
*
|
|
@@ -399,7 +452,7 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
399
452
|
*
|
|
400
453
|
* @prop {boolean} [removeEmptyElements]
|
|
401
454
|
* Remove elements that are empty and safe to remove (for example
|
|
402
|
-
* `<script />` without `src`).
|
|
455
|
+
* `<script />` without `src`), including elements left empty that way.
|
|
403
456
|
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_elements
|
|
404
457
|
*
|
|
405
458
|
* Default: `false`
|
|
@@ -411,21 +464,23 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
411
464
|
* Accepts tag names or HTML-like element specifications:
|
|
412
465
|
*
|
|
413
466
|
* * Tag name only: `["td", "span"]`—preserves all empty elements of these types
|
|
414
|
-
* * With valued attributes: `["<
|
|
415
|
-
* * With boolean attributes: `["<input disabled>"]`—preserves only when
|
|
467
|
+
* * With valued attributes: `["<i class='test'>"]`—preserves only when attribute values match
|
|
468
|
+
* * With boolean attributes: `["<input disabled>"]`—preserves only when the
|
|
469
|
+
* boolean attribute is present
|
|
416
470
|
* * Mixed: `["<button type='button' disabled>"]`—all specified attributes must match
|
|
417
471
|
*
|
|
418
472
|
* Attribute matching:
|
|
419
473
|
*
|
|
420
474
|
* * All specified attributes must be present and match (valued attributes must have exact values)
|
|
421
475
|
* * Additional attributes on the element are allowed
|
|
422
|
-
* *
|
|
476
|
+
* * Element and attribute names match in any case
|
|
423
477
|
* * Supports double quotes, single quotes, and unquoted attribute values in specifications
|
|
424
478
|
*
|
|
425
479
|
* Limitations:
|
|
426
480
|
*
|
|
427
481
|
* * Self-closing syntax (e.g., `["<span/>"]`) is not supported; use `["span"]` instead
|
|
428
|
-
* * Definitions containing `>` within quoted attribute values (e.g.,
|
|
482
|
+
* * Definitions containing `>` within quoted attribute values (e.g.,
|
|
483
|
+
* `["<span title='a>b'>"]`) are not supported
|
|
429
484
|
*
|
|
430
485
|
* Default: `[]`
|
|
431
486
|
*
|
|
@@ -453,16 +508,16 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
453
508
|
* Default: `false`
|
|
454
509
|
*
|
|
455
510
|
* @prop {boolean | {safelist?: Array<string | RegExp>, scripts?: boolean}} [removeUnusedCSS]
|
|
456
|
-
*
|
|
511
|
+
* Remove selectors from `style` elements that name an element, class, or ID the
|
|
512
|
+
* document doesn’t reference, as well as rules that are left without selectors.
|
|
513
|
+
* Requires `minifyCSS` (removal runs through Lightning CSS) and has no effect on
|
|
514
|
+
* `style` or `media` attributes.
|
|
457
515
|
*
|
|
458
|
-
*
|
|
459
|
-
*
|
|
460
|
-
*
|
|
461
|
-
*
|
|
462
|
-
*
|
|
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.
|
|
516
|
+
* Element, class, and ID names are collected from the markup and—unless `scripts`
|
|
517
|
+
* is set to `false`—from inline `script` elements; class names and IDs also from
|
|
518
|
+
* `data-*` attributes. Names that only ever appear in external scripts cannot
|
|
519
|
+
* be detected; list those under `safelist` (strings or regular expressions) to
|
|
520
|
+
* keep them.
|
|
466
521
|
*
|
|
467
522
|
* Default: `false`
|
|
468
523
|
*
|
|
@@ -483,9 +538,10 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
483
538
|
* Default: `false`
|
|
484
539
|
*
|
|
485
540
|
* @prop {boolean} [trimCustomFragments]
|
|
486
|
-
* When true, whitespace around ignored custom fragments
|
|
487
|
-
*
|
|
488
|
-
*
|
|
541
|
+
* When true, whitespace around ignored custom fragments is removed rather
|
|
542
|
+
* than collapsed where the minifier removes whitespace anyway (e.g., between
|
|
543
|
+
* block-level elements). Whitespace in tags, attribute values, CSS, and
|
|
544
|
+
* JavaScript is kept.
|
|
489
545
|
*
|
|
490
546
|
* Default: `false`
|
|
491
547
|
*
|
|
@@ -502,7 +558,7 @@ import { toFragment, replaceCustomFragments } from './lib/fragments.js';
|
|
|
502
558
|
let lightningCSSPromise;
|
|
503
559
|
async function getLightningCSS() {
|
|
504
560
|
if (!lightningCSSPromise) {
|
|
505
|
-
lightningCSSPromise = import('lightningcss').then(m => m.transform);
|
|
561
|
+
lightningCSSPromise = import('@ohos-ports/lightningcss').then(m => m.transform);
|
|
506
562
|
}
|
|
507
563
|
return lightningCSSPromise;
|
|
508
564
|
}
|
|
@@ -516,17 +572,26 @@ async function getTerser() {
|
|
|
516
572
|
return terserPromise;
|
|
517
573
|
}
|
|
518
574
|
|
|
575
|
+
/**
|
|
576
|
+
* @param {string} label - Minifier name as it should read in the message
|
|
577
|
+
* @param {string} specifier - Package that failed to load
|
|
578
|
+
* @param {unknown} cause - Error the import rejected with
|
|
579
|
+
* @returns {Error} Error marked as an unavailable dependency
|
|
580
|
+
*/
|
|
581
|
+
function unavailableDependency(label, specifier, cause) {
|
|
582
|
+
const err = new Error(describeDependencyFailure(label, specifier, cause), { cause });
|
|
583
|
+
/** @type {any} */ (err).code = MISSING_DEPENDENCY;
|
|
584
|
+
return err;
|
|
585
|
+
}
|
|
586
|
+
|
|
519
587
|
/** @type {Promise<any> | undefined} */
|
|
520
588
|
let swcPromise;
|
|
521
589
|
async function getSwc() {
|
|
522
590
|
if (!swcPromise) {
|
|
523
591
|
swcPromise = import('@swc/core')
|
|
524
592
|
.then(m => m.default || m)
|
|
525
|
-
.catch(
|
|
526
|
-
throw
|
|
527
|
-
'The swc minifier requires @swc/core to be installed.\n' +
|
|
528
|
-
'Install it with: npm install @swc/core'
|
|
529
|
-
);
|
|
593
|
+
.catch(err => {
|
|
594
|
+
throw unavailableDependency('swc', '@swc/core', err);
|
|
530
595
|
});
|
|
531
596
|
}
|
|
532
597
|
return swcPromise;
|
|
@@ -543,9 +608,11 @@ async function getSvgo() {
|
|
|
543
608
|
|
|
544
609
|
/** @type {Promise<Function> | undefined} */
|
|
545
610
|
let decodeHTMLPromise;
|
|
611
|
+
/** @type {((text: string) => string) | undefined} The resolved `decodeHTML`, once the lazy import above has settled */
|
|
612
|
+
let decodeHTMLFn;
|
|
546
613
|
async function getDecodeHTML() {
|
|
547
614
|
if (!decodeHTMLPromise) {
|
|
548
|
-
decodeHTMLPromise = import('entities').then(m => m.decodeHTML);
|
|
615
|
+
decodeHTMLPromise = import('entities').then(m => (decodeHTMLFn = m.decodeHTML));
|
|
549
616
|
}
|
|
550
617
|
return decodeHTMLPromise;
|
|
551
618
|
}
|
|
@@ -574,22 +641,32 @@ let svgMinifyCache = null;
|
|
|
574
641
|
*/
|
|
575
642
|
const cacheStatsOrEmpty = (cache) => cache ? cache.stats() : { gets: 0, hits: 0, size: 0, limit: 0 };
|
|
576
643
|
|
|
577
|
-
//
|
|
644
|
+
// Patterns for script merging
|
|
578
645
|
const RE_SCRIPT_ATTRS = /([^\s=]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
|
579
646
|
const RE_SCRIPT_OPEN = /<script(?=[\s>])/gi; // Finds tag start; use `findTagEnd()` for the actual closing `>`
|
|
580
647
|
const RE_SCRIPT_CLOSE = /<\/script\s*>/gi;
|
|
648
|
+
const RE_MATH_TAG = /<(\/?)math(?=[\s/>])/gi;
|
|
581
649
|
const SCRIPT_BOOL_ATTRS = new Set(['async', 'defer', 'nomodule']);
|
|
582
650
|
const DEFAULT_JS_TYPES = new Set(['', 'text/javascript', 'application/javascript']);
|
|
583
651
|
|
|
584
|
-
//
|
|
652
|
+
// Patterns for buffer scanning
|
|
585
653
|
const RE_START_TAG = /^<[^/!]/;
|
|
654
|
+
const RE_START_TAG_NAME = /^<([^\s/>]+)/;
|
|
655
|
+
const RE_LEADING_WHITESPACE = /^[ \t\n\r\f]/;
|
|
656
|
+
const RE_ASCII_WHITESPACE = /[ \t\n\r\f]/;
|
|
586
657
|
const RE_END_TAG = /^<\//;
|
|
587
658
|
const RE_WHITESPACE_ONLY = /^\s+$/;
|
|
659
|
+
const RE_TABS = /\t/g;
|
|
588
660
|
const RE_TRAILING_WHITESPACE = /\s$/;
|
|
661
|
+
const RE_LINE_BREAK_BLANKS_END = /(?:\r\n?|\n)[ \t\f]*$/;
|
|
662
|
+
const RE_BLANKS_LINE_BREAK_START = /^[ \t\f]*(?:\r\n?|\n)/;
|
|
663
|
+
const RE_BLANKS_START = /^[ \t\f]+/;
|
|
664
|
+
const RE_BLANKS_ONLY = /^[ \t\f]+$/;
|
|
589
665
|
|
|
590
|
-
//
|
|
666
|
+
// Patterns for `htmlmin:ignore` block content analysis
|
|
591
667
|
const RE_HTML_COMMENT_START = /^\s*<!--/;
|
|
592
668
|
const RE_CLOSING_TAG_START = /^\s*<\/([a-zA-Z][\w:-]*)/;
|
|
669
|
+
const RE_FIRST_HTML_TAG = /^\s*<([a-zA-Z][\w:-]*)/;
|
|
593
670
|
const RE_LAST_HTML_TAG = /[\s\S]*<(\/?[a-zA-Z][\w:-]*)/;
|
|
594
671
|
|
|
595
672
|
|
|
@@ -597,10 +674,15 @@ const RE_LAST_HTML_TAG = /[\s\S]*<(\/?[a-zA-Z][\w:-]*)/;
|
|
|
597
674
|
// the per-tag foreign-content machinery can be skipped entirely
|
|
598
675
|
const RE_FOREIGN_ELEMENT_PROBE = /<(?:svg|math)[\s/>]/i;
|
|
599
676
|
|
|
600
|
-
//
|
|
677
|
+
// A name in foreign content as the HTML parser reads it
|
|
678
|
+
/** @param {string} name */
|
|
679
|
+
function nameForeign(name) {
|
|
680
|
+
const nameLower = name.toLowerCase();
|
|
681
|
+
return namesForeignMixedCase.get(nameLower) ?? nameLower;
|
|
682
|
+
}
|
|
601
683
|
|
|
602
684
|
/**
|
|
603
|
-
* Merge consecutive inline script tags into one
|
|
685
|
+
* Merge consecutive inline script tags into one.
|
|
604
686
|
* Only merges scripts that are compatible:
|
|
605
687
|
* - Both inline (no `src` attribute)
|
|
606
688
|
* - Same `type` (or both default JavaScript)
|
|
@@ -617,11 +699,11 @@ const RE_FOREIGN_ELEMENT_PROBE = /<(?:svg|math)[\s/>]/i;
|
|
|
617
699
|
* only on the attributes of the first script in a chain, which merging
|
|
618
700
|
* preserves, so one pass finds every merge the iterated rescan found.
|
|
619
701
|
*
|
|
620
|
-
* @param {string} html
|
|
702
|
+
* @param {string} html
|
|
703
|
+
* @param {boolean} [hasMathML] - Whether the HTML holds MathML, whose `script` elements stay apart
|
|
621
704
|
* @returns {string} HTML with consecutive scripts merged
|
|
622
705
|
*/
|
|
623
|
-
function mergeConsecutiveScripts(html) {
|
|
624
|
-
// Parse an attribute string into a name→value map
|
|
706
|
+
function mergeConsecutiveScripts(html, hasMathML = false) {
|
|
625
707
|
const parseAttrs = (/** @type {string} */ attrStr) => {
|
|
626
708
|
/** @type {Record<string, string>} */
|
|
627
709
|
const attrs = {};
|
|
@@ -635,6 +717,21 @@ function mergeConsecutiveScripts(html) {
|
|
|
635
717
|
return attrs;
|
|
636
718
|
};
|
|
637
719
|
|
|
720
|
+
// In MathML, a `script` neither runs nor is hidden, so its text is shown as it is;
|
|
721
|
+
// scripts are visited in order, so the MathML tags before each are counted once
|
|
722
|
+
let mathDepth = 0;
|
|
723
|
+
let mathPos = 0;
|
|
724
|
+
const insideMath = (/** @type {number} */ index) => {
|
|
725
|
+
if (!hasMathML) return false;
|
|
726
|
+
RE_MATH_TAG.lastIndex = mathPos;
|
|
727
|
+
let tag;
|
|
728
|
+
while ((tag = RE_MATH_TAG.exec(html)) !== null && tag.index < index) {
|
|
729
|
+
mathDepth = tag[1] ? Math.max(0, mathDepth - 1) : mathDepth + 1;
|
|
730
|
+
mathPos = RE_MATH_TAG.lastIndex;
|
|
731
|
+
}
|
|
732
|
+
return mathDepth > 0;
|
|
733
|
+
};
|
|
734
|
+
|
|
638
735
|
/** @type {string[]} */
|
|
639
736
|
const segments = [];
|
|
640
737
|
let consumedPos = 0; // Start of the input region not yet copied to `segments`
|
|
@@ -643,7 +740,7 @@ function mergeConsecutiveScripts(html) {
|
|
|
643
740
|
let m1;
|
|
644
741
|
|
|
645
742
|
while ((m1 = RE_SCRIPT_OPEN.exec(html)) !== null) {
|
|
646
|
-
//
|
|
743
|
+
// `findTagEnd` skips quoted attribute values to find the real closing `>`
|
|
647
744
|
const tagEnd1 = findTagEnd(html, m1.index + 7);
|
|
648
745
|
if (tagEnd1 === -1) break;
|
|
649
746
|
|
|
@@ -663,12 +760,14 @@ function mergeConsecutiveScripts(html) {
|
|
|
663
760
|
// is not concatenable; even identical non-JS types are incompatible
|
|
664
761
|
const mergeable = !('src' in a1) && DEFAULT_JS_TYPES.has((a1.type || '').toLowerCase());
|
|
665
762
|
let mergedAny = false;
|
|
763
|
+
// Whitespace between the scripts, which may separate text around them
|
|
764
|
+
let gap = '';
|
|
666
765
|
|
|
667
766
|
// Absorb all directly following compatible scripts
|
|
668
767
|
while (mergeable) {
|
|
669
|
-
// Skip optional whitespace and check for a consecutive <script> tag
|
|
670
768
|
let i = afterClose;
|
|
671
769
|
while (i < html.length && (html[i] === ' ' || html[i] === '\t' || html[i] === '\n' || html[i] === '\r' || html[i] === '\f')) i++;
|
|
770
|
+
const gapNext = html.slice(afterClose, i);
|
|
672
771
|
if (html.slice(i, i + 7).toLowerCase() !== '<script' || (html.charAt(i + 7) !== '>' && !/\s/.test(html.charAt(i + 7)))) break;
|
|
673
772
|
|
|
674
773
|
const tagEnd2 = findTagEnd(html, i + 7);
|
|
@@ -676,7 +775,6 @@ function mergeConsecutiveScripts(html) {
|
|
|
676
775
|
|
|
677
776
|
const attrs2Str = html.slice(i + 7, tagEnd2);
|
|
678
777
|
|
|
679
|
-
// Find end of the following script’s content
|
|
680
778
|
RE_SCRIPT_CLOSE.lastIndex = tagEnd2 + 1;
|
|
681
779
|
const close2 = RE_SCRIPT_CLOSE.exec(html);
|
|
682
780
|
if (!close2) break;
|
|
@@ -690,16 +788,13 @@ function mergeConsecutiveScripts(html) {
|
|
|
690
788
|
for (const attr of SCRIPT_BOOL_ATTRS) {
|
|
691
789
|
if ((attr in a1) !== (attr in a2)) { boolConflict = true; break; }
|
|
692
790
|
}
|
|
693
|
-
if (boolConflict || a1.nonce !== a2.nonce) break;
|
|
791
|
+
if (boolConflict || a1.nonce !== a2.nonce || (!mergedAny && insideMath(m1.index))) break;
|
|
694
792
|
|
|
695
|
-
//
|
|
696
|
-
// newline only for trailing `//` comments
|
|
793
|
+
// Join with a semicolon, or with a newline where the first ends in a `//` comment
|
|
697
794
|
const content2 = html.slice(tagEnd2 + 1, close2.index);
|
|
698
795
|
const c1 = mergedContent.trim();
|
|
699
796
|
const c2 = content2.trim();
|
|
700
797
|
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
798
|
const lastLine = c1.slice(c1.lastIndexOf('\n') + 1);
|
|
704
799
|
const separator = lastLine.includes('//') ? '\n' : (c1.endsWith(';') ? '' : ';');
|
|
705
800
|
mergedContent = c1 + separator + c2;
|
|
@@ -709,11 +804,17 @@ function mergeConsecutiveScripts(html) {
|
|
|
709
804
|
|
|
710
805
|
afterClose = close2.index + close2[0].length;
|
|
711
806
|
mergedAny = true;
|
|
807
|
+
gap ||= gapNext;
|
|
712
808
|
}
|
|
713
809
|
|
|
714
810
|
if (mergedAny) {
|
|
811
|
+
// Whitespace goes after the merged script, unless nothing or
|
|
812
|
+
// whitespace is on either side anyway
|
|
813
|
+
if (gap && (!m1.index || afterClose === html.length || RE_ASCII_WHITESPACE.test(html.charAt(m1.index - 1) + html.charAt(afterClose)))) {
|
|
814
|
+
gap = '';
|
|
815
|
+
}
|
|
715
816
|
// Use first script’s attributes (they are compatible)
|
|
716
|
-
segments.push(html.slice(consumedPos, m1.index), `<script${attrs1Str}>${mergedContent}</script
|
|
817
|
+
segments.push(html.slice(consumedPos, m1.index), `<script${attrs1Str}>${mergedContent}</script>${gap}`);
|
|
717
818
|
consumedPos = afterClose;
|
|
718
819
|
}
|
|
719
820
|
|
|
@@ -749,16 +850,13 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
749
850
|
}
|
|
750
851
|
|
|
751
852
|
function shouldKeepToken(/** @type {string} */ token) {
|
|
752
|
-
//
|
|
753
|
-
// These are temporary markers created by `htmlmin:ignore` and `ignoreCustomFragments`
|
|
853
|
+
// Comments are UID placeholders from `htmlmin:ignore` and `ignoreCustomFragments`
|
|
754
854
|
if (token.startsWith('<!--') && token.endsWith('-->')) {
|
|
755
855
|
return false;
|
|
756
856
|
}
|
|
757
857
|
return shouldSkipUID(token, uidIgnore) && shouldSkipUID(token, uidAttr);
|
|
758
858
|
}
|
|
759
859
|
|
|
760
|
-
// Pre-compile regex patterns for reuse (performance optimization)
|
|
761
|
-
// These must be declared before `scan()` since scan uses them
|
|
762
860
|
const whitespaceSplitPatternScan = /[ \t\n\f\r]+/;
|
|
763
861
|
const whitespaceSplitPatternSort = /[ \n\f\r]+/;
|
|
764
862
|
|
|
@@ -770,11 +868,13 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
770
868
|
const parser = new HTMLParser(input, {
|
|
771
869
|
start: function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ unary) {
|
|
772
870
|
if (attrChains) {
|
|
773
|
-
|
|
774
|
-
|
|
871
|
+
// Lowercase, as the first pass writes names as in the source under `caseSensitive`
|
|
872
|
+
const tagKey = resolveName(tag);
|
|
873
|
+
if (!attrChains[tagKey]) {
|
|
874
|
+
attrChains[tagKey] = new TokenChain();
|
|
775
875
|
}
|
|
776
876
|
const attrNamesList = attrNames(attrs).filter(shouldKeepToken);
|
|
777
|
-
attrChains[
|
|
877
|
+
attrChains[tagKey].add(attrNamesList);
|
|
778
878
|
}
|
|
779
879
|
for (const attr of attrs) {
|
|
780
880
|
if (classChain && attr.value && resolveName(attr.name) === 'class') {
|
|
@@ -785,7 +885,8 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
785
885
|
currentType = attr.value;
|
|
786
886
|
}
|
|
787
887
|
}
|
|
788
|
-
// As on the main path: What a unary tag holds ends with the tag,
|
|
888
|
+
// As on the main path: What a unary tag holds ends with the tag,
|
|
889
|
+
// so no text can belong to it
|
|
789
890
|
if (unary) {
|
|
790
891
|
currentTag = '';
|
|
791
892
|
currentType = undefined;
|
|
@@ -795,17 +896,14 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
795
896
|
currentTag = '';
|
|
796
897
|
},
|
|
797
898
|
chars: async function (/** @type {string} */ text) {
|
|
798
|
-
// Only
|
|
799
|
-
// `scan()` is for analyzing HTML attribute order, not for parsing JSON
|
|
899
|
+
// Only HTML content is scanned recursively, not JSON-LD or other non-HTML script types
|
|
800
900
|
if (options.processScripts && specialContentElements.has(currentTag) &&
|
|
801
901
|
options.processScripts.indexOf(currentType ?? '') > -1 &&
|
|
802
902
|
currentType === 'text/html') {
|
|
803
903
|
await scan(text);
|
|
804
904
|
}
|
|
805
905
|
},
|
|
806
|
-
// No need for `nextTag` information in this scan
|
|
807
906
|
wantsNextTag: false,
|
|
808
|
-
// Continue on parse errors during analysis pass
|
|
809
907
|
continueOnParseError: options.continueOnParseError,
|
|
810
908
|
selfClosingSlash: options.keepClosingSlash
|
|
811
909
|
});
|
|
@@ -813,19 +911,18 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
813
911
|
try {
|
|
814
912
|
await parser.parse();
|
|
815
913
|
} catch (err) {
|
|
816
|
-
// If parsing fails during analysis pass, skip it—there’s partial frequency
|
|
914
|
+
// If parsing fails during analysis pass, skip it—there’s partial frequency
|
|
915
|
+
// data from what can be parsed
|
|
817
916
|
if (!options.continueOnParseError) {
|
|
818
917
|
throw err;
|
|
819
918
|
}
|
|
820
919
|
}
|
|
821
920
|
}
|
|
822
921
|
|
|
823
|
-
//
|
|
824
|
-
//
|
|
825
|
-
//
|
|
826
|
-
// Note: `htmlmin:ignore` UID markers (`uidIgnore`) already exist and are expanded for analysis.
|
|
922
|
+
// First-pass options: Aggressive minification is off, attribute transformations (like
|
|
923
|
+
// `removeDefaultTypeAttributes`) stay. Custom-fragment UID markers (`uidAttr`) don’t
|
|
924
|
+
// exist yet; `htmlmin:ignore` ones (`uidIgnore`) do and are expanded for analysis.
|
|
827
925
|
const firstPassOptions = Object.assign({}, options, {
|
|
828
|
-
// Disable sorting for the analysis pass
|
|
829
926
|
sortAttributes: false,
|
|
830
927
|
sortClassNames: false,
|
|
831
928
|
// Disable aggressive minification that doesn’t affect attribute analysis
|
|
@@ -834,14 +931,12 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
834
931
|
removeTagWhitespace: false,
|
|
835
932
|
decodeEntities: false,
|
|
836
933
|
processScripts: false,
|
|
837
|
-
//
|
|
838
|
-
// Continue on parse errors during analysis (e.g., template syntax)
|
|
934
|
+
// `ignoreCustomFragments` stays, and template syntax may not parse cleanly
|
|
839
935
|
continueOnParseError: true,
|
|
840
936
|
log: identity
|
|
841
937
|
});
|
|
842
938
|
|
|
843
|
-
//
|
|
844
|
-
// Note: `firstPassOptions` already has `continueOnParseError: true` for the `minifyHTML` call.
|
|
939
|
+
// `scan()` reads `options` rather than `firstPassOptions`, so it needs the same leniency
|
|
845
940
|
const originalContinueOnParseError = options.continueOnParseError;
|
|
846
941
|
options.continueOnParseError = true;
|
|
847
942
|
|
|
@@ -859,16 +954,13 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
859
954
|
expandedValue = value.replace(uidReplacePattern, function (/** @type {string} */ _match, /** @type {string} */ index) {
|
|
860
955
|
return ignoredMarkupChunks[+index] || '';
|
|
861
956
|
});
|
|
862
|
-
// Reset `lastIndex` for pattern reuse
|
|
863
957
|
uidReplacePattern.lastIndex = 0;
|
|
864
958
|
}
|
|
865
959
|
|
|
866
|
-
// First pass minification applies attribute transformations like `removeDefaultTypeAttributes` for accurate frequency analysis
|
|
867
960
|
const firstPassOutput = await minifyHTML(expandedValue, firstPassOptions);
|
|
868
961
|
|
|
869
|
-
//
|
|
870
|
-
//
|
|
871
|
-
// removed with a space to preserve attribute boundaries
|
|
962
|
+
// Custom fragments are removed for frequency analysis, as HTML comments in start tags keep
|
|
963
|
+
// attributes from parsing; a space in their place preserves attribute boundaries
|
|
872
964
|
let scanValue = firstPassOutput;
|
|
873
965
|
if (customFragments.length) {
|
|
874
966
|
scanValue = replaceCustomFragments(firstPassOutput, customFragments, () => ' ');
|
|
@@ -876,7 +968,6 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
876
968
|
|
|
877
969
|
await scan(scanValue);
|
|
878
970
|
} finally {
|
|
879
|
-
// Restore original option
|
|
880
971
|
if (originalContinueOnParseError !== undefined) {
|
|
881
972
|
options.continueOnParseError = originalContinueOnParseError;
|
|
882
973
|
} else {
|
|
@@ -892,16 +983,17 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
892
983
|
const attrOrderCache = new LRU(500);
|
|
893
984
|
|
|
894
985
|
options.sortAttributes = function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs) {
|
|
895
|
-
|
|
986
|
+
// Called with the name as written, as any `sortAttributes` function is
|
|
987
|
+
const sorter = attrSorters[resolveName(tag)];
|
|
896
988
|
if (sorter) {
|
|
897
989
|
const names = attrNames(attrs);
|
|
898
990
|
|
|
899
|
-
//
|
|
991
|
+
// Order-independent cache key
|
|
900
992
|
const cacheKey = tag + ':' + names.slice().sort().join(',');
|
|
901
993
|
let sortedNames = /** @type {string[] | undefined} */ (attrOrderCache.get(cacheKey));
|
|
902
994
|
|
|
903
995
|
if (sortedNames === undefined) {
|
|
904
|
-
//
|
|
996
|
+
// `sort` works in place, hence the copy
|
|
905
997
|
sortedNames = sorter.sort(names.slice());
|
|
906
998
|
attrOrderCache.set(cacheKey, sortedNames);
|
|
907
999
|
}
|
|
@@ -928,7 +1020,6 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
928
1020
|
return classNames;
|
|
929
1021
|
}
|
|
930
1022
|
|
|
931
|
-
// Check cache first
|
|
932
1023
|
const cached = /** @type {string | undefined} */ (classNameCache.get(classNames));
|
|
933
1024
|
if (cached !== undefined) {
|
|
934
1025
|
return cached;
|
|
@@ -941,7 +1032,6 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
941
1032
|
expandedValue = classNames.replace(uidReplacePattern, function (/** @type {string} */ _match, /** @type {string} */ index) {
|
|
942
1033
|
return ignoredMarkupChunks[+index] || '';
|
|
943
1034
|
});
|
|
944
|
-
// Reset `lastIndex` for pattern reuse
|
|
945
1035
|
uidReplacePattern.lastIndex = 0;
|
|
946
1036
|
}
|
|
947
1037
|
const classes = expandedValue.split(whitespaceSplitPatternSort).filter(function(/** @type {string} */ cls) {
|
|
@@ -950,7 +1040,6 @@ async function createSortFns(value, options, uidIgnore, uidAttr, ignoredMarkupCh
|
|
|
950
1040
|
const sorted = sorter.sort(classes);
|
|
951
1041
|
const result = sorted.join(' ');
|
|
952
1042
|
|
|
953
|
-
// Cache the result
|
|
954
1043
|
classNameCache.set(classNames, result);
|
|
955
1044
|
return result;
|
|
956
1045
|
};
|
|
@@ -979,13 +1068,13 @@ function matchPlainEndTag(str) {
|
|
|
979
1068
|
}
|
|
980
1069
|
|
|
981
1070
|
/**
|
|
982
|
-
* @param {string} value
|
|
983
|
-
* @param {ProcessedOptions} options
|
|
1071
|
+
* @param {string} value
|
|
1072
|
+
* @param {ProcessedOptions} options
|
|
984
1073
|
* @param {boolean} [partialMarkup] - Whether treating input as partial markup
|
|
985
|
-
* @returns {Promise<string>}
|
|
1074
|
+
* @returns {Promise<string>}
|
|
986
1075
|
*/
|
|
987
1076
|
async function minifyHTML(value, options, partialMarkup) {
|
|
988
|
-
//
|
|
1077
|
+
// Input length limit, against ReDoS
|
|
989
1078
|
if (options.maxInputLength && value.length > options.maxInputLength) {
|
|
990
1079
|
throw new Error(`Input length (${value.length}) exceeds maximum allowed length (${options.maxInputLength})`);
|
|
991
1080
|
}
|
|
@@ -1000,11 +1089,30 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1000
1089
|
|
|
1001
1090
|
/** @type {string[]} */
|
|
1002
1091
|
const buffer = [];
|
|
1092
|
+
// Parallel to `buffer`: whether the entry is a tag—the only place lines may break
|
|
1093
|
+
const bufferTags = options.maxLineLength ? /** @type {boolean[]} */ ([]) : null;
|
|
1003
1094
|
/** @type {string} */
|
|
1004
1095
|
let charsPrevTag = '';
|
|
1005
1096
|
let currentChars = '';
|
|
1006
1097
|
/** @type {boolean} */
|
|
1007
1098
|
let hasChars = false;
|
|
1099
|
+
// Open elements under `removeEmptyElements`, so an element whose content
|
|
1100
|
+
// went is removed, too: where its start tag sits in `buffer`, and whether
|
|
1101
|
+
// anything kept went in since
|
|
1102
|
+
/** @type {Array<{tag: string, index: number, empty: boolean}>} */
|
|
1103
|
+
const openElements = [];
|
|
1104
|
+
// A start tag the parser implied without writing it, whose end tag, if it comes next, is a stray
|
|
1105
|
+
// one that browsers read as an empty element (as `</p>` is), so it must not be omitted
|
|
1106
|
+
let impliedStartTag = '';
|
|
1107
|
+
// Whether the parser found the document to be in no-quirks mode, where `table` closes a `p`
|
|
1108
|
+
let tableClosesP = false;
|
|
1109
|
+
// Under `collapseWhitespace`, the text whose trailing whitespace sits before or
|
|
1110
|
+
// between elements that don’t render, kept until what follows them shows whether
|
|
1111
|
+
// it separates anything; whether the text being processed is such text; and how
|
|
1112
|
+
// deep inside such elements parsing is
|
|
1113
|
+
let transparentGapIndex = -1;
|
|
1114
|
+
let transparentGapPending = false;
|
|
1115
|
+
let transparentDepth = 0;
|
|
1008
1116
|
let currentTag = '';
|
|
1009
1117
|
/** @type {Array<{name: string, value?: string, quote?: string, customAssign?: string, customOpen?: string, customClose?: string}>} */
|
|
1010
1118
|
let currentAttrs = [];
|
|
@@ -1013,13 +1121,32 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1013
1121
|
/** @type {string[]} */
|
|
1014
1122
|
const stackNoCollapseWhitespace = [];
|
|
1015
1123
|
let preTextareaDepth = 0; // Count of `pre`/`textarea` entries in `stackNoTrimWhitespace`
|
|
1124
|
+
// Where the last element whose whitespace may not be trimmed ended in `buffer`;
|
|
1125
|
+
// what lies up to there stays as written, also where `canTrimWhitespace` decides
|
|
1126
|
+
// by attributes the trim walk lacks
|
|
1127
|
+
let noTrimEndIndex = -1;
|
|
1128
|
+
// The same for the last element whose whitespace may not be collapsed
|
|
1129
|
+
let noCollapseEndIndex = -1;
|
|
1016
1130
|
let optionalStartTag = '';
|
|
1017
1131
|
let optionalEndTag = '';
|
|
1018
1132
|
let optionalEndTagEmitted = false;
|
|
1133
|
+
// Whether a node was removed since the last output
|
|
1134
|
+
let removed = false;
|
|
1135
|
+
// Whether the latest text was kept verbatim, as in `pre` or `script`
|
|
1136
|
+
let textVerbatim = false;
|
|
1019
1137
|
/** @type {string[]} */
|
|
1020
1138
|
const ignoredMarkupChunks = [];
|
|
1021
1139
|
/** @type {Array<RegExpExecArray | null>} */
|
|
1022
1140
|
const ignoredCustomMarkupChunks = [];
|
|
1141
|
+
// Custom fragments whose surrounding whitespace is never trimmed: in tags, where it
|
|
1142
|
+
// separates attributes, and in CSS and JavaScript, where minifiers can’t judge it
|
|
1143
|
+
/** @type {Set<number>} */
|
|
1144
|
+
const customMarkupInTags = new Set();
|
|
1145
|
+
/** @type {Set<number>} */
|
|
1146
|
+
const customMarkupInCode = new Set();
|
|
1147
|
+
// Attributes joined with the custom fragments they run into, to be written as they are
|
|
1148
|
+
/** @type {WeakSet<HTMLAttribute>} */
|
|
1149
|
+
const opaqueAttrs = new WeakSet();
|
|
1023
1150
|
/** @type {string | undefined} */
|
|
1024
1151
|
let uidIgnore;
|
|
1025
1152
|
/** @type {RegExp | undefined} */
|
|
@@ -1030,6 +1157,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1030
1157
|
let uidPattern;
|
|
1031
1158
|
/** @type {RegExp | undefined} */
|
|
1032
1159
|
let uidAttrLeadingPattern;
|
|
1160
|
+
/** @type {RegExp | undefined} */
|
|
1161
|
+
let uidAttrExactPattern;
|
|
1033
1162
|
// Create inline tags/text sets with custom elements
|
|
1034
1163
|
const customElementsInput = options.inlineCustomElements ?? [];
|
|
1035
1164
|
const customElementsArr = Array.isArray(customElementsInput) ? customElementsInput : Array.from(customElementsInput);
|
|
@@ -1041,8 +1170,10 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1041
1170
|
const inlineElements = normalizedCustomElements.length
|
|
1042
1171
|
? new Set([...inlineElementsToKeepWhitespaceAround, ...normalizedCustomElements])
|
|
1043
1172
|
: inlineElementsToKeepWhitespaceAround;
|
|
1173
|
+
const inlineSets = normalizedCustomElements.length
|
|
1174
|
+
? buildInlineSets(inlineElements, inlineTextSet)
|
|
1175
|
+
: defaultInlineSets;
|
|
1044
1176
|
|
|
1045
|
-
// Parse `removeEmptyElementsExcept` option
|
|
1046
1177
|
/** @type {Array<{tag: string, attrs: {[x: string]: string | undefined} | null}>} */
|
|
1047
1178
|
let removeEmptyElementsExcept;
|
|
1048
1179
|
if (options.removeEmptyElementsExcept && !Array.isArray(options.removeEmptyElementsExcept)) {
|
|
@@ -1054,8 +1185,7 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1054
1185
|
removeEmptyElementsExcept = parseRemoveEmptyElementsExcept(options.removeEmptyElementsExcept || [], options) || [];
|
|
1055
1186
|
}
|
|
1056
1187
|
|
|
1057
|
-
// Temporarily replace ignored chunks with comments, so
|
|
1058
|
-
// there might be completely-horribly-broken-alien-non-html-emoji-cthulhu-filled content
|
|
1188
|
+
// Temporarily replace ignored chunks with comments, so whatever they hold needn’t be parsed
|
|
1059
1189
|
if (value.indexOf('<!-- htmlmin:ignore -->') !== -1) {
|
|
1060
1190
|
// Use `indexOf`-based O(n) loop instead of a global regex with [\s\S]*? to avoid O(n²)
|
|
1061
1191
|
// backtracking on adversarial HTML with many `<!--` prefixes but no closing marker
|
|
@@ -1089,8 +1219,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1089
1219
|
value = ignoreResult;
|
|
1090
1220
|
}
|
|
1091
1221
|
|
|
1092
|
-
//
|
|
1093
|
-
//
|
|
1222
|
+
// Sort functions are created after `htmlmin:ignore` processing but before custom fragment UID
|
|
1223
|
+
// markers, so frequency analysis can reach ignored content via UID tokens
|
|
1094
1224
|
if ((options.sortAttributes && typeof options.sortAttributes !== 'function') ||
|
|
1095
1225
|
(options.sortClassNames && typeof options.sortClassNames !== 'function')) {
|
|
1096
1226
|
await createSortFns(value, options, uidIgnore ?? '', uidAttr ?? '', ignoredMarkupChunks);
|
|
@@ -1104,12 +1234,14 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1104
1234
|
uidAttr = uniqueId(value);
|
|
1105
1235
|
uidPattern = new RegExp('(\\s*)' + uidAttr + '([0-9]+)' + uidAttr + '(\\s*)', 'g');
|
|
1106
1236
|
uidAttrLeadingPattern = new RegExp('^\\s*' + uidAttr + '(\\d+)' + uidAttr);
|
|
1237
|
+
uidAttrExactPattern = new RegExp('^' + uidAttr + '(\\d+)' + uidAttr + '$');
|
|
1107
1238
|
|
|
1108
1239
|
if (options.minifyCSS !== identity) {
|
|
1109
1240
|
options.minifyCSS = (function (/** @type {ProcessedOptions['minifyCSS']} */ fn) {
|
|
1110
1241
|
return function (/** @type {string} */ text, /** @type {string | undefined} */ type, /** @type {ProcessedOptions['cssContext']} */ context) {
|
|
1111
1242
|
text = text.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ _match, /** @type {string} */ _prefix, /** @type {string} */ index) {
|
|
1112
1243
|
const chunks = ignoredCustomMarkupChunks[+index];
|
|
1244
|
+
customMarkupInCode.add(+index);
|
|
1113
1245
|
return (chunks?.[1] ?? '') + uidAttr + index + uidAttr + (chunks?.[2] ?? '');
|
|
1114
1246
|
});
|
|
1115
1247
|
|
|
@@ -1123,6 +1255,7 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1123
1255
|
return function (/** @type {string} */ text, /** @type {boolean | undefined} */ inline, /** @type {boolean | undefined} */ isModule) {
|
|
1124
1256
|
return fn(text.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ _match, /** @type {string} */ _prefix, /** @type {string} */ index) {
|
|
1125
1257
|
const chunks = ignoredCustomMarkupChunks[+index];
|
|
1258
|
+
customMarkupInCode.add(+index);
|
|
1126
1259
|
return (chunks?.[1] ?? '') + uidAttr + index + uidAttr + (chunks?.[2] ?? '');
|
|
1127
1260
|
}), inline, isModule);
|
|
1128
1261
|
};
|
|
@@ -1138,28 +1271,216 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1138
1271
|
value = replaceCustomFragments(value, customFragments, replaceFragment);
|
|
1139
1272
|
}
|
|
1140
1273
|
|
|
1141
|
-
|
|
1142
|
-
|
|
1274
|
+
// Custom fragment and `htmlmin:ignore` placeholders hold these
|
|
1275
|
+
const markers = [uidAttr, uidIgnore].filter(marker => marker !== undefined);
|
|
1276
|
+
|
|
1277
|
+
// Record the custom fragments in (part of) a tag
|
|
1278
|
+
function markTagFragments(/** @type {string} */ str) {
|
|
1279
|
+
for (const uidMatch of str.matchAll(/** @type {RegExp} */ (uidPattern))) {
|
|
1280
|
+
customMarkupInTags.add(+(uidMatch[2] ?? 0));
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
// Source text of an attribute, as far as it matters
|
|
1285
|
+
function rawAttr(/** @type {HTMLAttribute} */ attr) {
|
|
1286
|
+
if (opaqueAttrs.has(attr)) {
|
|
1287
|
+
return attr.name;
|
|
1288
|
+
}
|
|
1289
|
+
let raw = attr.name;
|
|
1290
|
+
// Skip values the parser filled in for bare boolean attributes
|
|
1291
|
+
if (attr.value !== undefined && !(attr.quote === '' && attr.value === attr.name)) {
|
|
1292
|
+
raw += (attr.customAssign ?? '=') + (attr.quote ?? '') + attr.value + (attr.quote ?? '');
|
|
1293
|
+
}
|
|
1294
|
+
return (attr.customOpen ?? '') + raw + (attr.customClose ?? '');
|
|
1143
1295
|
}
|
|
1144
1296
|
|
|
1145
|
-
|
|
1146
|
-
|
|
1297
|
+
/**
|
|
1298
|
+
* Join each attribute a custom fragment runs into without whitespace with that fragment,
|
|
1299
|
+
* so that no later step separates, drops, changes, or reorders them
|
|
1300
|
+
* @param {HTMLAttribute[]} attrs - Joined in place
|
|
1301
|
+
* @returns {boolean} Whether the first attribute runs into the tag name
|
|
1302
|
+
*/
|
|
1303
|
+
function joinFragmentAttrs(attrs) {
|
|
1304
|
+
const pattern = /** @type {RegExp} */ (uidAttrExactPattern);
|
|
1305
|
+
let joinsTag = false;
|
|
1306
|
+
let writeIndex = 0;
|
|
1307
|
+
// Padding of the previous attribute if that is a fragment without value
|
|
1308
|
+
/** @type {RegExpExecArray | null | undefined} */
|
|
1309
|
+
let prevChunks = null;
|
|
1310
|
+
for (const attr of attrs) {
|
|
1311
|
+
const uidMatch = pattern.exec(attr.name);
|
|
1312
|
+
const chunks = uidMatch ? ignoredCustomMarkupChunks[+(uidMatch[1] ?? 0)] : null;
|
|
1313
|
+
const joins = prevChunks ? prevChunks[2] === '' : chunks?.[1] === '';
|
|
1314
|
+
prevChunks = attr.value === undefined ? chunks : null;
|
|
1315
|
+
if (!joins) {
|
|
1316
|
+
attrs[writeIndex++] = attr;
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
const prev = writeIndex ? attrs[writeIndex - 1] : undefined;
|
|
1320
|
+
if (!prev) {
|
|
1321
|
+
joinsTag = true;
|
|
1322
|
+
}
|
|
1323
|
+
/** @type {HTMLAttribute} */
|
|
1324
|
+
const joined = { name: (prev ? rawAttr(prev) : '') + rawAttr(attr), customAssign: '=', customOpen: '', customClose: '', quote: '' };
|
|
1325
|
+
opaqueAttrs.add(joined);
|
|
1326
|
+
attrs[prev ? writeIndex - 1 : writeIndex++] = joined;
|
|
1327
|
+
}
|
|
1328
|
+
attrs.length = writeIndex;
|
|
1329
|
+
return joinsTag;
|
|
1147
1330
|
}
|
|
1148
1331
|
|
|
1149
|
-
|
|
1332
|
+
/**
|
|
1333
|
+
* Restore the whitespace on one side of a custom fragment
|
|
1334
|
+
* @param {string} str - Whitespace the minifier left there and the fragment’s own padding
|
|
1335
|
+
* @param {boolean} trim
|
|
1336
|
+
* @param {boolean} leading
|
|
1337
|
+
*/
|
|
1338
|
+
function restoreFragmentSide(str, trim, leading) {
|
|
1339
|
+
if (!str) {
|
|
1340
|
+
return str;
|
|
1341
|
+
}
|
|
1342
|
+
return collapseWhitespace(str, {
|
|
1343
|
+
preserveLineBreaks: options.preserveLineBreaks,
|
|
1344
|
+
conservativeCollapse: !trim
|
|
1345
|
+
}, leading, !leading);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// Under `caseSensitive`, names are read in lowercase all the same, while `buffer` and hooks
|
|
1349
|
+
// get them as written, so the defaults a hook may call take any spelling then
|
|
1350
|
+
const namesAsWritten = Boolean(options.namesAsWritten);
|
|
1351
|
+
const defaultCanCollapse = namesAsWritten
|
|
1352
|
+
? (/** @type {string} */ tag) => defaultCanCollapseWhitespace(tag.toLowerCase())
|
|
1353
|
+
: defaultCanCollapseWhitespace;
|
|
1354
|
+
const defaultCanTrim = namesAsWritten
|
|
1355
|
+
? (/** @type {string} */ tag) => defaultCanTrimWhitespace(tag.toLowerCase())
|
|
1356
|
+
: defaultCanTrimWhitespace;
|
|
1357
|
+
|
|
1358
|
+
// The defaults decide by `tag`, a hook gets `tagOut`; without a hook, the
|
|
1359
|
+
// option holds the default itself
|
|
1360
|
+
function canCollapseWhitespace(/** @type {string} */ tag, /** @type {string} */ tagOut, /** @type {HTMLAttribute[]} */ attrs) {
|
|
1361
|
+
const hook = options.canCollapseWhitespace;
|
|
1362
|
+
return hook === defaultCanCollapseWhitespace ? defaultCanCollapseWhitespace(tag) : hook(tagOut, attrs, defaultCanCollapse);
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
function canTrimWhitespace(/** @type {string} */ tag, /** @type {string} */ tagOut, /** @type {HTMLAttribute[]} */ attrs) {
|
|
1366
|
+
const hook = options.canTrimWhitespace;
|
|
1367
|
+
return hook === defaultCanTrimWhitespace ? defaultCanTrimWhitespace(tag) : hook(tagOut, attrs, defaultCanTrim);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
function bufferPush(/** @type {string} */ entry, /** @type {boolean} */ isTag) {
|
|
1371
|
+
buffer.push(entry);
|
|
1372
|
+
bufferTags?.push(isTag);
|
|
1373
|
+
if (entry) removed = false;
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
function bufferTruncate(/** @type {number} */ length) {
|
|
1377
|
+
buffer.length = Math.max(0, length);
|
|
1378
|
+
if (bufferTags) bufferTags.length = buffer.length;
|
|
1379
|
+
if (transparentGapIndex >= buffer.length) transparentGapIndex = -1;
|
|
1380
|
+
if (noTrimEndIndex >= buffer.length) noTrimEndIndex = -1;
|
|
1381
|
+
if (noCollapseEndIndex >= buffer.length) noCollapseEndIndex = -1;
|
|
1382
|
+
removed = true;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
// The nearest entries before and from `index` that aren’t empty, as removed nodes leave them
|
|
1386
|
+
/** @returns {[number, number]} */
|
|
1387
|
+
function findNeighbors(/** @type {number} */ index) {
|
|
1388
|
+
let before = index - 1;
|
|
1389
|
+
while (before >= 0 && buffer[before] === '') {
|
|
1390
|
+
before--;
|
|
1391
|
+
}
|
|
1392
|
+
let after = index;
|
|
1393
|
+
while (after < buffer.length && buffer[after] === '') {
|
|
1394
|
+
after++;
|
|
1395
|
+
}
|
|
1396
|
+
return [before, after];
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
// With whitespace kept as is, a removed node must not leave a line of nothing but
|
|
1400
|
+
// whitespace behind: The text around the removal (at `index`) drops that line. The start
|
|
1401
|
+
// of the output counts as a line break, and blank lines of the source stay.
|
|
1402
|
+
function removeWhitespaceLine(/** @type {number} */ index) {
|
|
1403
|
+
const [first, after] = findNeighbors(index);
|
|
1404
|
+
// The end of the output is left to `trimOutputWhitespace`
|
|
1405
|
+
if (after === buffer.length) {
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
const next = buffer[after] ?? '';
|
|
1409
|
+
if (!RE_BLANKS_LINE_BREAK_START.test(next)) {
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
// Blanks between nodes removed from the same line belong to that line
|
|
1413
|
+
let before = first;
|
|
1414
|
+
while (before >= 0 && (buffer[before] === '' || RE_BLANKS_ONLY.test(buffer[before] ?? ''))) {
|
|
1415
|
+
before--;
|
|
1416
|
+
}
|
|
1417
|
+
const prev = buffer[before] ?? '';
|
|
1418
|
+
if (before >= 0 && !RE_LINE_BREAK_BLANKS_END.test(prev)) {
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
for (let i = before + 1; i <= first; i++) {
|
|
1422
|
+
buffer[i] = '';
|
|
1423
|
+
}
|
|
1424
|
+
// The line break goes on the side of the text before the removal, so that the text after
|
|
1425
|
+
// it keeps its own for a removal that may follow
|
|
1426
|
+
if (before < 0) {
|
|
1427
|
+
buffer[after] = next.replace(RE_BLANKS_LINE_BREAK_START, '');
|
|
1428
|
+
} else {
|
|
1429
|
+
buffer[before] = prev.replace(RE_LINE_BREAK_BLANKS_END, '');
|
|
1430
|
+
buffer[after] = next.replace(RE_BLANKS_START, '');
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
// Whitespace at either end of the output goes, but not verbatim whitespace, nor whitespace
|
|
1435
|
+
// that `conservativeCollapse` or `preserveLineBreaks` promise to keep, nor that of partial
|
|
1436
|
+
// markup, whose ends join other markup
|
|
1437
|
+
function trimOutputWhitespace() {
|
|
1438
|
+
if (options.partialMarkup || (options.collapseWhitespace && (options.conservativeCollapse || options.preserveLineBreaks))) {
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
// Tags start with `<` and end with `>`, so whitespace at either end belongs to text
|
|
1442
|
+
if (!textVerbatim) {
|
|
1443
|
+
let index = buffer.length - 1;
|
|
1444
|
+
while (index >= 0 && (buffer[index] === '' || RE_WS_ONLY.test(buffer[index] ?? ''))) {
|
|
1445
|
+
buffer[index--] = '';
|
|
1446
|
+
}
|
|
1447
|
+
if (index >= 0) {
|
|
1448
|
+
buffer[index] = (buffer[index] ?? '').replace(RE_WS_END, '');
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
let index = 0;
|
|
1452
|
+
while (index < buffer.length && (buffer[index] === '' || RE_WS_ONLY.test(buffer[index] ?? ''))) {
|
|
1453
|
+
buffer[index++] = '';
|
|
1454
|
+
}
|
|
1455
|
+
if (index < buffer.length) {
|
|
1456
|
+
buffer[index] = (buffer[index] ?? '').replace(RE_WS_START, '');
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function lastStartTagIndex() {
|
|
1150
1461
|
let index = buffer.length - 1;
|
|
1151
1462
|
while (index > 0 && !RE_START_TAG.test(buffer[index] ?? '')) {
|
|
1152
1463
|
index--;
|
|
1153
1464
|
}
|
|
1154
|
-
|
|
1465
|
+
return index;
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
function removeStartTag() {
|
|
1469
|
+
bufferTruncate(lastStartTagIndex());
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
function markOpenElementFilled() {
|
|
1473
|
+
// Guarded, as reading index -1 is a slow property lookup, and this runs for every text node
|
|
1474
|
+
if (openElements.length) {
|
|
1475
|
+
/** @type {{empty: boolean}} */ (openElements[openElements.length - 1]).empty = false;
|
|
1476
|
+
}
|
|
1155
1477
|
}
|
|
1156
1478
|
|
|
1157
1479
|
// Whether the element being parsed holds text rather than markup. The namespace decides
|
|
1158
|
-
// this, not the name alone:
|
|
1159
|
-
//
|
|
1480
|
+
// this, not the name alone: Only HTML elements do—an SVG or MathML `script` or `title`
|
|
1481
|
+
// holds markup like any foreign element
|
|
1160
1482
|
function holdsRawText() {
|
|
1161
|
-
return
|
|
1162
|
-
(rawTextElements.has(currentTag) && !options.insideForeignContent);
|
|
1483
|
+
return rawTextElements.has(currentTag) && !options.insideForeignContent;
|
|
1163
1484
|
}
|
|
1164
1485
|
|
|
1165
1486
|
// Whether whitespace-only text between tags survives minification
|
|
@@ -1171,14 +1492,7 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1171
1492
|
// single character it is due: a line break under `preserveLineBreaks`, a no-break space
|
|
1172
1493
|
// where the run holds one, a space under `conservativeCollapse`
|
|
1173
1494
|
function mergeWhitespaceRuns(/** @type {number} */ index) {
|
|
1174
|
-
|
|
1175
|
-
while (before >= 0 && buffer[before] === '') {
|
|
1176
|
-
before--;
|
|
1177
|
-
}
|
|
1178
|
-
let after = index;
|
|
1179
|
-
while (after < buffer.length && buffer[after] === '') {
|
|
1180
|
-
after++;
|
|
1181
|
-
}
|
|
1495
|
+
const [before, after] = findNeighbors(index);
|
|
1182
1496
|
if (before < 0 || after >= buffer.length) {
|
|
1183
1497
|
return;
|
|
1184
1498
|
}
|
|
@@ -1196,7 +1510,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1196
1510
|
}
|
|
1197
1511
|
}
|
|
1198
1512
|
|
|
1199
|
-
|
|
1513
|
+
// `insideNoTrim` stands in for the stack once the end tag that omits this one has left it
|
|
1514
|
+
function removeEndTag(/** @type {boolean} */ insideNoTrim = false) {
|
|
1200
1515
|
let index = buffer.length - 1;
|
|
1201
1516
|
while (index > 0 && !RE_END_TAG.test(buffer[index] ?? '')) {
|
|
1202
1517
|
index--;
|
|
@@ -1204,50 +1519,159 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1204
1519
|
// Text that follows the end tag is kept as is, so drop the tag alone. Whitespace kept
|
|
1205
1520
|
// verbatim—in `pre`, in `textarea`, or wherever `canTrimWhitespace` says so—counts as
|
|
1206
1521
|
// kept text too, no matter how whitespace is collapsed elsewhere.
|
|
1207
|
-
const noTrim = stackNoTrimWhitespace.length > 0;
|
|
1522
|
+
const noTrim = insideNoTrim || stackNoTrimWhitespace.length > 0;
|
|
1208
1523
|
if (index < buffer.length - 1 && (keepsWhitespace() || noTrim) && RE_END_TAG.test(buffer[index] ?? '')) {
|
|
1209
1524
|
buffer.splice(index, 1);
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1525
|
+
bufferTags?.splice(index, 1);
|
|
1526
|
+
// Collapsed whitespace can merge, kept whitespace can leave a line of only whitespace
|
|
1527
|
+
if (!noTrim) {
|
|
1528
|
+
if (options.collapseWhitespace) {
|
|
1529
|
+
mergeWhitespaceRuns(index);
|
|
1530
|
+
} else {
|
|
1531
|
+
removeWhitespaceLine(index);
|
|
1532
|
+
}
|
|
1213
1533
|
}
|
|
1214
1534
|
return;
|
|
1215
1535
|
}
|
|
1216
|
-
|
|
1536
|
+
bufferTruncate(index);
|
|
1217
1537
|
}
|
|
1218
1538
|
|
|
1219
|
-
// Look for trailing
|
|
1539
|
+
// Look for trailing whitespace, bypassing inline tags
|
|
1220
1540
|
function trimTrailingWhitespace(/** @type {number} */ index, /** @type {string} */ nextTag) {
|
|
1221
|
-
|
|
1541
|
+
// Nothing to the left of the text is in play here, so only its trailing run can
|
|
1542
|
+
// change—unless preserved line breaks bring the leading run into play, too
|
|
1543
|
+
const trailingOnly = !options.preserveLineBreaks;
|
|
1544
|
+
for (let prevTag = ''; index > noTrimEndIndex && canTrimWhitespace(namesAsWritten ? prevTag.toLowerCase() : prevTag, prevTag, emptyAttrs); index--) {
|
|
1222
1545
|
const str = buffer[index] ?? '';
|
|
1223
1546
|
const endTagName = matchPlainEndTag(str);
|
|
1224
1547
|
if (endTagName !== null) {
|
|
1225
1548
|
prevTag = endTagName;
|
|
1226
|
-
|
|
1227
|
-
|
|
1549
|
+
continue;
|
|
1550
|
+
}
|
|
1551
|
+
// A tag ends the search, and so does text that survives collapsing. Text with no
|
|
1552
|
+
// trailing run comes back from the call unchanged, so it can end the search on
|
|
1553
|
+
// the spot; empty text cannot, as the search has to carry on past it
|
|
1554
|
+
if (str.charCodeAt(str.length - 1) === 62 /* > */) {
|
|
1555
|
+
break;
|
|
1556
|
+
}
|
|
1557
|
+
if (trailingOnly && str && !endsWithWhitespace(str)) {
|
|
1558
|
+
break;
|
|
1559
|
+
}
|
|
1560
|
+
buffer[index] = collapseWhitespaceSmart(str, '', nextTag, emptyAttrs, emptyAttrs, options, inlineSets, !stackNoCollapseWhitespace.length && index > noCollapseEndIndex);
|
|
1561
|
+
if (buffer[index]) {
|
|
1228
1562
|
break;
|
|
1229
1563
|
}
|
|
1230
1564
|
}
|
|
1231
1565
|
}
|
|
1232
1566
|
|
|
1233
|
-
// Look for trailing
|
|
1234
|
-
//
|
|
1235
|
-
// element which has now been removed
|
|
1567
|
+
// Look for trailing whitespace in earlier text that a following comment, or an empty element
|
|
1568
|
+
// removed since, kept from being trimmed
|
|
1236
1569
|
function squashTrailingWhitespace(/** @type {string} */ nextTag) {
|
|
1570
|
+
// Fast path: With no transparent gap pending, a start tag or text without trailing
|
|
1571
|
+
// whitespace last in the buffer ends the walk below on that entry. That leaves text
|
|
1572
|
+
// alone as well where `preserveLineBreaks` has the walk collapse it again, as the
|
|
1573
|
+
// text’s own pass collapsed it already.
|
|
1574
|
+
if (transparentGapIndex === -1) {
|
|
1575
|
+
const last = buffer[buffer.length - 1] ?? '';
|
|
1576
|
+
if (last) {
|
|
1577
|
+
if (last.charCodeAt(0) !== 60 /* < */) {
|
|
1578
|
+
if (!endsWithWhitespace(last)) {
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
} else {
|
|
1582
|
+
const second = last.charCodeAt(1);
|
|
1583
|
+
if (second !== 47 /* / */ && second !== 33 /* ! */ && last.charCodeAt(last.length - 1) === 62 /* > */) {
|
|
1584
|
+
return;
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
if (transparentGapIndex !== -1 && !transparentDepth && !inlineElementsTransparentAfter.has(nextTag) && !inlineElementsTransparent.has(nextTag)) {
|
|
1590
|
+
settleTransparentGap(collapseWhitespaceSmart(' ', '', nextTag, emptyAttrs, emptyAttrs, options, inlineSets) !== '');
|
|
1591
|
+
}
|
|
1237
1592
|
let charsIndex = buffer.length - 1;
|
|
1238
1593
|
// Step back over every trailing comment and empty entry, not just one—a single step
|
|
1239
1594
|
// stops the search at the comment itself, leaving whitespace behind that a second
|
|
1240
1595
|
// minification run then removes
|
|
1241
1596
|
while (charsIndex > 0) {
|
|
1242
1597
|
const item = buffer[charsIndex] ?? '';
|
|
1243
|
-
|
|
1598
|
+
// Comments and empty entries only, as `<!…` or nothing at all
|
|
1599
|
+
const skippable = item === '' || (item.charCodeAt(0) === 60 /* < */ && item.charCodeAt(1) === 33 /* ! */);
|
|
1600
|
+
if (!skippable || (uidIgnore && item.indexOf(uidIgnore) !== -1)) {
|
|
1244
1601
|
break;
|
|
1245
1602
|
}
|
|
1246
1603
|
charsIndex--;
|
|
1247
1604
|
}
|
|
1605
|
+
// Right before an element that doesn’t render, the text’s own pass has
|
|
1606
|
+
// weighed both sides already
|
|
1607
|
+
if (charsIndex === buffer.length - 1 && inlineElementsTransparent.has(nextTag)) {
|
|
1608
|
+
return;
|
|
1609
|
+
}
|
|
1248
1610
|
trimTrailingWhitespace(charsIndex, nextTag);
|
|
1249
1611
|
}
|
|
1250
1612
|
|
|
1613
|
+
// Keep or trim the whitespace pending before or between elements that don’t render
|
|
1614
|
+
function settleTransparentGap(/** @type {boolean} */ keep) {
|
|
1615
|
+
if (!keep) {
|
|
1616
|
+
buffer[transparentGapIndex] = collapseWhitespace(buffer[transparentGapIndex] ?? '', options, false, true);
|
|
1617
|
+
}
|
|
1618
|
+
transparentGapIndex = -1;
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
// The index of the start tag whose attributes, which follow it as entries
|
|
1622
|
+
// of their own, end at `index`, or -1 for text
|
|
1623
|
+
function findAttributesStartTag(/** @type {number} */ index) {
|
|
1624
|
+
if ((buffer[index] ?? '').charCodeAt((buffer[index] ?? '').length - 1) !== 62 /* > */) return -1;
|
|
1625
|
+
for (let tagIndex = index - 1; tagIndex >= 0; tagIndex--) {
|
|
1626
|
+
const str = buffer[tagIndex] ?? '';
|
|
1627
|
+
if (str.charCodeAt(0) === 60 /* < */) {
|
|
1628
|
+
return RE_START_TAG.test(str) && str.charCodeAt(str.length - 1) !== 62 /* > */ ? tagIndex : -1;
|
|
1629
|
+
}
|
|
1630
|
+
if (!str || str.charCodeAt(str.length - 1) === 62 /* > */) return -1;
|
|
1631
|
+
}
|
|
1632
|
+
return -1;
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// Whether what comes before the elements that don’t render at the end of `buffer`
|
|
1636
|
+
// would run into what follows them; without `skipAttributes`, the scan stops at
|
|
1637
|
+
// a start tag’s attributes and says yes, as stepping over them on every
|
|
1638
|
+
// call makes the scan quadratic over long runs
|
|
1639
|
+
function precedesTransparentRun(/** @type {boolean} */ skipAttributes = false) {
|
|
1640
|
+
for (let index = buffer.length - 1; index >= 0; index--) {
|
|
1641
|
+
let str = buffer[index] ?? '';
|
|
1642
|
+
if (!str) continue;
|
|
1643
|
+
if (str.charCodeAt(0) !== 60 /* < */) {
|
|
1644
|
+
const tagIndex = skipAttributes ? findAttributesStartTag(index) : -1;
|
|
1645
|
+
if (tagIndex === -1) {
|
|
1646
|
+
return !endsWithWhitespace(str);
|
|
1647
|
+
}
|
|
1648
|
+
index = tagIndex;
|
|
1649
|
+
str = buffer[index] ?? '';
|
|
1650
|
+
}
|
|
1651
|
+
// Comments don’t render, whereas what an `htmlmin:ignore` block
|
|
1652
|
+
// or a processing instruction stands for may
|
|
1653
|
+
if (str.charCodeAt(1) === 33 /* ! */ || str.charCodeAt(1) === 63 /* ? */) {
|
|
1654
|
+
if (str.charCodeAt(1) === 63 || (uidIgnore && str.indexOf(uidIgnore) !== -1)) return true;
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
const endTagName = matchPlainEndTag(str);
|
|
1658
|
+
const tag = (endTagName === null ? (RE_START_TAG_NAME.exec(str)?.[1] ?? '') : '/' + endTagName).toLowerCase();
|
|
1659
|
+
if (!inlineElementsTransparentAfter.has(tag)) {
|
|
1660
|
+
return collapseWhitespaceSmart(' ', tag, '', emptyAttrs, emptyAttrs, options, inlineSets) !== '';
|
|
1661
|
+
}
|
|
1662
|
+
// Skip what an element that doesn’t render holds
|
|
1663
|
+
if (endTagName !== null) {
|
|
1664
|
+
const startTag = '<' + endTagName.toLowerCase();
|
|
1665
|
+
// Only the start of each entry is compared, as what such an element holds can be large
|
|
1666
|
+
while (index > 0 && (buffer[index - 1] ?? '').slice(0, startTag.length).toLowerCase() !== startTag) {
|
|
1667
|
+
index--;
|
|
1668
|
+
}
|
|
1669
|
+
index--;
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
return false;
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1251
1675
|
// Per-text-node context for `charsCollapse`/`charsFinalize`, set by the `chars`
|
|
1252
1676
|
// handler before either phase runs; shared variables (rather than parameters)
|
|
1253
1677
|
// let both phases live at this scope—`charsCollapse` reassigns `textPrevTag`
|
|
@@ -1261,28 +1685,29 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1261
1685
|
let textPrevAttrs = emptyAttrs;
|
|
1262
1686
|
/** @type {HTMLAttribute[]} */
|
|
1263
1687
|
let textNextAttrs = emptyAttrs;
|
|
1688
|
+
// Whether the text is in foreign content, and if so, whether it was read as HTML reads it
|
|
1689
|
+
// and so is to be escaped again
|
|
1690
|
+
let textForeign = false;
|
|
1691
|
+
let textForeignDecoded = false;
|
|
1264
1692
|
|
|
1265
1693
|
// Whitespace collapsing phase (sync)
|
|
1266
1694
|
function charsCollapse(/** @type {string} */ text) {
|
|
1267
|
-
// Trim
|
|
1268
|
-
//
|
|
1269
|
-
// Only trims single trailing newlines (multiple newlines are likely intentional formatting)
|
|
1695
|
+
// Trim a single trailing newline inside `pre`/`textarea`, often a template engine artifact
|
|
1696
|
+
// (several are likely intentional formatting)
|
|
1270
1697
|
if (options.collapseWhitespace && stackNoTrimWhitespace.length) {
|
|
1271
1698
|
const topTag = stackNoTrimWhitespace[stackNoTrimWhitespace.length - 1];
|
|
1272
1699
|
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
1700
|
// Treat CRLF (`\r\n`), CR (`\r`), and LF (`\n`) as single line-ending units
|
|
1276
1701
|
if (textNextTag && textNextTag === '/' + topTag && /[^\r\n](?:\r\n|\r|\n)[ \t]*$/.test(text)) {
|
|
1277
|
-
text = text.replace(
|
|
1702
|
+
text = text.replace(RE_LINE_BREAK_BLANKS_END, '');
|
|
1278
1703
|
}
|
|
1279
1704
|
}
|
|
1280
1705
|
}
|
|
1281
1706
|
if (options.collapseWhitespace) {
|
|
1282
1707
|
if (!stackNoTrimWhitespace.length) {
|
|
1283
|
-
// When the prev item is a UID placeholder, compute its effective tag name for whitespace
|
|
1284
|
-
// this is only used in `collapseWhitespaceSmart`—`textPrevTag` itself is not
|
|
1285
|
-
// to avoid side effects on the `inlineTextSet` branch below
|
|
1708
|
+
// When the prev item is a UID placeholder, compute its effective tag name for whitespace
|
|
1709
|
+
// decisions; this is only used in `collapseWhitespaceSmart`—`textPrevTag` itself is not
|
|
1710
|
+
// modified, to avoid side effects on the `inlineTextSet` branch below
|
|
1286
1711
|
let effectivePrevTag = textPrevTag;
|
|
1287
1712
|
if (textPrevTag === 'comment') {
|
|
1288
1713
|
const prevComment = buffer[buffer.length - 1] ?? '';
|
|
@@ -1301,7 +1726,7 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1301
1726
|
} else if (uidIgnorePlaceholderPattern && textNextTag !== 'comment') {
|
|
1302
1727
|
// UID placeholder followed by a real element—derive the effective `prevTag` from the
|
|
1303
1728
|
// placeholder’s last HTML tag so `collapseWhitespaceSmart` can make the right call;
|
|
1304
|
-
//
|
|
1729
|
+
// `commentFinalize` handles a `textNextTag` of `comment` (another UID placeholder)
|
|
1305
1730
|
const match = prevComment.match(uidIgnorePlaceholderPattern);
|
|
1306
1731
|
if (match) {
|
|
1307
1732
|
const idx = +(match[1] ?? '');
|
|
@@ -1322,17 +1747,48 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1322
1747
|
if (textPrevTag === '/nobr' || textPrevTag === 'wbr') {
|
|
1323
1748
|
if (/^\s/.test(text)) {
|
|
1324
1749
|
let tagIndex = buffer.length - 1;
|
|
1325
|
-
while (tagIndex > 0 && (buffer[tagIndex] ?? '').lastIndexOf('<' + textPrevTag) !== 0) {
|
|
1750
|
+
while (tagIndex > 0 && (namesAsWritten ? (buffer[tagIndex] ?? '').toLowerCase() : buffer[tagIndex] ?? '').lastIndexOf('<' + textPrevTag) !== 0) {
|
|
1326
1751
|
tagIndex--;
|
|
1327
1752
|
}
|
|
1328
1753
|
trimTrailingWhitespace(tagIndex - 1, 'br');
|
|
1329
1754
|
}
|
|
1330
|
-
} else if (
|
|
1331
|
-
text = collapseWhitespace(text, options, /(?:^|\s)$/.test(currentChars), false);
|
|
1755
|
+
} else if (inlineSets.withinEither.has(textPrevTag)) {
|
|
1756
|
+
text = collapseWhitespace(text, options, /(?:^|\s)$/.test(currentChars), false, false, stackNoCollapseWhitespace.length > 0);
|
|
1332
1757
|
}
|
|
1333
1758
|
}
|
|
1334
1759
|
if (textPrevTag || textNextTag) {
|
|
1335
|
-
|
|
1760
|
+
let collapsed = collapseWhitespaceSmart(text, effectivePrevTag, textNextTag, textPrevAttrs, textNextAttrs, options, inlineSets, !stackNoCollapseWhitespace.length);
|
|
1761
|
+
if (!transparentDepth && inlineElementsTransparentAfter.has(textPrevTag)) {
|
|
1762
|
+
// Between elements that don’t render, whitespace stays pending when it may
|
|
1763
|
+
// separate text, and one space does
|
|
1764
|
+
if (!collapsed && text && inlineElementsTransparent.has(textNextTag)) {
|
|
1765
|
+
if (transparentGapIndex === -1 && precedesTransparentRun()) {
|
|
1766
|
+
transparentGapPending = true;
|
|
1767
|
+
text = ' ';
|
|
1768
|
+
} else {
|
|
1769
|
+
text = '';
|
|
1770
|
+
}
|
|
1771
|
+
} else {
|
|
1772
|
+
// Text that follows decides, while a tag that follows does so in
|
|
1773
|
+
// `squashTrailingWhitespace`
|
|
1774
|
+
if (RE_LEADING_WHITESPACE.test(collapsed)) {
|
|
1775
|
+
if (transparentGapIndex !== -1) settleTransparentGap(false);
|
|
1776
|
+
// Where nothing before the elements renders a space, the text’s own goes, too
|
|
1777
|
+
if (!options.conservativeCollapse && !precedesTransparentRun(true)) {
|
|
1778
|
+
collapsed = collapseWhitespace(collapsed, options, true, false);
|
|
1779
|
+
}
|
|
1780
|
+
} else if (transparentGapIndex !== -1 && collapsed) {
|
|
1781
|
+
settleTransparentGap(true);
|
|
1782
|
+
}
|
|
1783
|
+
text = collapsed;
|
|
1784
|
+
}
|
|
1785
|
+
} else {
|
|
1786
|
+
text = collapsed;
|
|
1787
|
+
// Whitespace before an element that doesn’t render waits for what follows it, too
|
|
1788
|
+
if (!transparentDepth && inlineElementsTransparent.has(textNextTag) && endsWithWhitespace(text)) {
|
|
1789
|
+
transparentGapPending = true;
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1336
1792
|
} else {
|
|
1337
1793
|
text = collapseWhitespace(text, options, true, true);
|
|
1338
1794
|
}
|
|
@@ -1340,9 +1796,13 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1340
1796
|
trimTrailingWhitespace(buffer.length - 1, textNextTag);
|
|
1341
1797
|
}
|
|
1342
1798
|
}
|
|
1343
|
-
|
|
1799
|
+
// Whitespace that may not be trimmed stays verbatim, as in `pre`
|
|
1800
|
+
if (!stackNoCollapseWhitespace.length && !stackNoTrimWhitespace.length && textNextTag !== 'html' && !(textPrevTag && textNextTag)) {
|
|
1344
1801
|
text = collapseWhitespace(text, options, false, false, true);
|
|
1345
1802
|
}
|
|
1803
|
+
if (options.collapseNoBreakSpaces && !stackNoCollapseWhitespace.length && !holdsRawText()) {
|
|
1804
|
+
text = collapseNoBreakSpaces(text, options);
|
|
1805
|
+
}
|
|
1346
1806
|
}
|
|
1347
1807
|
return text;
|
|
1348
1808
|
}
|
|
@@ -1364,13 +1824,15 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1364
1824
|
}
|
|
1365
1825
|
}
|
|
1366
1826
|
// `<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>`,
|
|
1827
|
+
// `<body>` may be omitted if first thing inside is not space, comment, `<meta>`, `<link>`,
|
|
1828
|
+
// `<script>`, `<style>`, or `<template>`
|
|
1368
1829
|
if (optionalStartTag === 'html' || (optionalStartTag === 'body' && !/^\s/.test(effectiveText))) {
|
|
1369
1830
|
removeStartTag();
|
|
1370
1831
|
}
|
|
1371
1832
|
optionalStartTag = '';
|
|
1372
1833
|
// `</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
|
|
1834
|
+
// `</head>`, `</colgroup>`, or `</caption>` may be omitted if not followed by space or
|
|
1835
|
+
// comment
|
|
1374
1836
|
if (optionalEndTagEmitted && (compactElements.has(optionalEndTag) || (looseElements.has(optionalEndTag) && !/^\s/.test(effectiveText)))) {
|
|
1375
1837
|
removeEndTag();
|
|
1376
1838
|
// The tag is gone from the buffer, so nothing is left to omit later
|
|
@@ -1387,12 +1849,24 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1387
1849
|
optionalEndTagEmitted = false;
|
|
1388
1850
|
}
|
|
1389
1851
|
}
|
|
1390
|
-
charsPrevTag =
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1852
|
+
charsPrevTag = isAllWhitespace(text) ? textPrevTag : 'comment';
|
|
1853
|
+
const rawText = Boolean(text) && holdsRawText();
|
|
1854
|
+
if (text) {
|
|
1855
|
+
textVerbatim = rawText || stackNoTrimWhitespace.length > 0;
|
|
1856
|
+
}
|
|
1857
|
+
if (text && options.insideSVG && options.minifySVG) {
|
|
1858
|
+
// SVGO reads XML, so text is escaped for it, while raw text, which XML cannot read as
|
|
1859
|
+
// HTML does (as in `foreignObject`), passes SVGO as a placeholder
|
|
1860
|
+
if (!rawText) {
|
|
1861
|
+
text = escapeXML(text);
|
|
1862
|
+
} else if (text.indexOf('&') !== -1 || text.indexOf('<') !== -1 || text.indexOf(']]>') !== -1) {
|
|
1863
|
+
uidSVGRawText ||= uniqueId(value);
|
|
1864
|
+
svgRawTexts.push(text);
|
|
1865
|
+
text = '/*!' + uidSVGRawText + (svgRawTexts.length - 1) + '*/';
|
|
1866
|
+
}
|
|
1867
|
+
} else if (text && (textForeign ? textForeignDecoded : options.decodeEntities && !rawText)) {
|
|
1868
|
+
// Escape every `&` that starts a character reference, legacy-named (without `;`) or not;
|
|
1869
|
+
// `&` needs no semicolon either
|
|
1396
1870
|
// https://mathiasbynens.be/notes/ambiguous-ampersands
|
|
1397
1871
|
if (text.indexOf('&') !== -1) {
|
|
1398
1872
|
text = text.replace(RE_LEGACY_ENTITIES, '&$1');
|
|
@@ -1400,9 +1874,13 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1400
1874
|
if (text.indexOf('<') !== -1) {
|
|
1401
1875
|
// Escapable raw text ends at its own end tag alone, so only that one needs escaping;
|
|
1402
1876
|
// in foreign content the same element holds markup, where every `<` does
|
|
1403
|
-
const escapeLt = (
|
|
1877
|
+
const escapeLt = (textForeign ? undefined : RE_ESCAPE_LT_RAW_TEXT[currentTag]) ?? RE_ESCAPE_LT;
|
|
1404
1878
|
text = text.replace(escapeLt, '<');
|
|
1405
1879
|
}
|
|
1880
|
+
} else if (text && textForeign && text.lastIndexOf('<![CDATA[') > text.lastIndexOf(']]>')) {
|
|
1881
|
+
// A CDATA section left open at the end of the input closes before the
|
|
1882
|
+
// end tags written after it
|
|
1883
|
+
text += ']]>';
|
|
1406
1884
|
}
|
|
1407
1885
|
if (uidPattern && options.collapseWhitespace && stackNoTrimWhitespace.length) {
|
|
1408
1886
|
text = text.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ match, /** @type {string} */ _prefix, /** @type {string} */ index) {
|
|
@@ -1412,11 +1890,20 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1412
1890
|
currentChars += text;
|
|
1413
1891
|
if (text) {
|
|
1414
1892
|
hasChars = true;
|
|
1893
|
+
markOpenElementFilled();
|
|
1894
|
+
}
|
|
1895
|
+
const followsRemoval = removed && Boolean(text) && !options.collapseWhitespace && !stackNoTrimWhitespace.length;
|
|
1896
|
+
if (transparentGapPending) {
|
|
1897
|
+
transparentGapPending = false;
|
|
1898
|
+
if (text) transparentGapIndex = buffer.length;
|
|
1899
|
+
}
|
|
1900
|
+
bufferPush(text, false);
|
|
1901
|
+
if (followsRemoval) {
|
|
1902
|
+
removeWhitespaceLine(buffer.length - 1);
|
|
1415
1903
|
}
|
|
1416
|
-
buffer.push(text);
|
|
1417
1904
|
}
|
|
1418
1905
|
|
|
1419
|
-
// Comment finalization (sync): Optional
|
|
1906
|
+
// Comment finalization (sync): Optional tags, `htmlmin:ignore` whitespace, buffer push
|
|
1420
1907
|
function commentFinalize(/** @type {string} */ comment) {
|
|
1421
1908
|
if (options.removeOptionalTags && comment) {
|
|
1422
1909
|
if (uidIgnorePlaceholderPattern) {
|
|
@@ -1444,6 +1931,24 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1444
1931
|
optionalEndTagEmitted = false;
|
|
1445
1932
|
}
|
|
1446
1933
|
|
|
1934
|
+
// Whitespace between an element that doesn’t render and an `htmlmin:ignore` block
|
|
1935
|
+
// that starts with one depends on what lies before both
|
|
1936
|
+
if (options.collapseWhitespace && comment && uidIgnorePlaceholderPattern && !transparentDepth && !stackNoTrimWhitespace.length && buffer.length >= 2) {
|
|
1937
|
+
const prevText = buffer[buffer.length - 1] ?? '';
|
|
1938
|
+
const match = prevText && RE_WS_ONLY.test(prevText) && uidIgnorePlaceholderPattern.exec(comment);
|
|
1939
|
+
const firstTag = match ? RE_FIRST_HTML_TAG.exec(ignoredMarkupChunks[+(match[1] ?? 0)] ?? '')?.[1] : undefined;
|
|
1940
|
+
if (firstTag && inlineElementsTransparent.has(resolveName(firstTag)) && inlineElementsTransparentAfter.has(charsPrevTag)) {
|
|
1941
|
+
// Emptied first, as `precedesTransparentRun` stops at text
|
|
1942
|
+
buffer[buffer.length - 1] = '';
|
|
1943
|
+
if (transparentGapIndex === buffer.length - 1) transparentGapIndex = -1;
|
|
1944
|
+
buffer[buffer.length - 1] = options.conservativeCollapse || precedesTransparentRun(true) ? ' ' : '';
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
// What an `htmlmin:ignore` block holds is unknown, so whitespace pending before it stays
|
|
1948
|
+
if (transparentGapIndex !== -1 && !transparentDepth && comment && uidIgnorePlaceholderPattern?.test(comment)) {
|
|
1949
|
+
settleTransparentGap(true);
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1447
1952
|
// Optimize whitespace collapsing between consecutive `htmlmin:ignore` placeholder comments
|
|
1448
1953
|
if (options.collapseWhitespace && comment && uidIgnorePlaceholderPattern) {
|
|
1449
1954
|
if (uidIgnorePlaceholderPattern.test(comment)) {
|
|
@@ -1452,9 +1957,7 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1452
1957
|
const prevText = buffer[buffer.length - 1];
|
|
1453
1958
|
const prevComment = buffer[buffer.length - 2];
|
|
1454
1959
|
|
|
1455
|
-
// Check if previous item is whitespace-only and item before that is ignore-placeholder
|
|
1456
1960
|
if (prevText && RE_WHITESPACE_ONLY.test(prevText) && prevComment && uidIgnorePlaceholderPattern.test(prevComment)) {
|
|
1457
|
-
// Extract the index from both placeholders to check their content
|
|
1458
1961
|
const currentMatch = comment.match(uidIgnorePlaceholderPattern);
|
|
1459
1962
|
const prevMatch = prevComment.match(uidIgnorePlaceholderPattern);
|
|
1460
1963
|
|
|
@@ -1462,7 +1965,6 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1462
1965
|
const currentIndex = +(currentMatch[1] ?? 0);
|
|
1463
1966
|
const prevIndex = +(prevMatch[1] ?? 0);
|
|
1464
1967
|
|
|
1465
|
-
// Defensive bounds check to ensure indices are valid
|
|
1466
1968
|
if (currentIndex < ignoredMarkupChunks.length && prevIndex < ignoredMarkupChunks.length) {
|
|
1467
1969
|
const currentContent = ignoredMarkupChunks[currentIndex];
|
|
1468
1970
|
const prevContent = ignoredMarkupChunks[prevIndex];
|
|
@@ -1470,9 +1972,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1470
1972
|
// Only collapse whitespace if both blocks contain HTML (start with `<`)
|
|
1471
1973
|
// Don’t collapse if either contains plain text, as that would change meaning
|
|
1472
1974
|
if (currentContent && prevContent && /^\s*</.test(currentContent) && /^\s*</.test(prevContent)) {
|
|
1473
|
-
|
|
1474
|
-
const
|
|
1475
|
-
const prevTagMatch = prevContent.match(/^\s*<([a-zA-Z][\w:-]*)/);
|
|
1975
|
+
const currentTagMatch = currentContent.match(RE_FIRST_HTML_TAG);
|
|
1976
|
+
const prevTagMatch = prevContent.match(RE_FIRST_HTML_TAG);
|
|
1476
1977
|
// HTML comments are invisible (no block/inline nature), treat as non-inline
|
|
1477
1978
|
const prevIsHtmlComment = !prevTagMatch && RE_HTML_COMMENT_START.test(prevContent);
|
|
1478
1979
|
const currentIsHtmlComment = !currentTagMatch && RE_HTML_COMMENT_START.test(currentContent);
|
|
@@ -1480,7 +1981,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1480
1981
|
const prevClosingTagMatch = !prevTagMatch && RE_CLOSING_TAG_START.exec(prevContent);
|
|
1481
1982
|
const currentClosingTagMatch = !currentTagMatch && RE_CLOSING_TAG_START.exec(currentContent);
|
|
1482
1983
|
|
|
1483
|
-
// Collapse if both sides are element/closing tags or HTML
|
|
1984
|
+
// Collapse if both sides are element/closing tags or HTML
|
|
1985
|
+
// comments, and neither is inline
|
|
1484
1986
|
if ((currentTagMatch || currentIsHtmlComment || currentClosingTagMatch) &&
|
|
1485
1987
|
(prevTagMatch || prevIsHtmlComment || prevClosingTagMatch)) {
|
|
1486
1988
|
const currentTagName = currentTagMatch ? resolveName(currentTagMatch[1] ?? '')
|
|
@@ -1490,10 +1992,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1490
1992
|
|
|
1491
1993
|
// Don’t collapse between inline elements (HTML comments count as non-inline)
|
|
1492
1994
|
if (!inlineElements.has(currentTagName ?? '') && !inlineElements.has(prevTagName ?? '')) {
|
|
1493
|
-
// Collapse whitespace respecting context rules
|
|
1494
1995
|
let collapsedText = prevText;
|
|
1495
1996
|
|
|
1496
|
-
// Apply `collapseWhitespace` with appropriate context
|
|
1497
1997
|
if (!stackNoTrimWhitespace.length && !stackNoCollapseWhitespace.length) {
|
|
1498
1998
|
// Not in pre or other no-collapse context
|
|
1499
1999
|
if (prevText.includes('\xA0')) {
|
|
@@ -1512,7 +2012,6 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1512
2012
|
}
|
|
1513
2013
|
}
|
|
1514
2014
|
|
|
1515
|
-
// Replace the whitespace in buffer
|
|
1516
2015
|
buffer[buffer.length - 1] = collapsedText;
|
|
1517
2016
|
}
|
|
1518
2017
|
}
|
|
@@ -1524,13 +2023,12 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1524
2023
|
}
|
|
1525
2024
|
}
|
|
1526
2025
|
|
|
1527
|
-
|
|
2026
|
+
bufferPush(comment, false);
|
|
1528
2027
|
}
|
|
1529
2028
|
|
|
1530
|
-
// Inline scripts
|
|
1531
|
-
//
|
|
1532
|
-
//
|
|
1533
|
-
// parse asks for in another form simply misses and takes the original path.
|
|
2029
|
+
// Inline scripts minified as the parse reaches them run one at a time; dispatching them all up
|
|
2030
|
+
// front lets the minifier overlap the work. Bodies are matched by exact content, so one the parse
|
|
2031
|
+
// asks for in another form misses and takes the original path.
|
|
1534
2032
|
/** @type {Map<string, Promise<string>> | null} */
|
|
1535
2033
|
let jsPrewarmed = null;
|
|
1536
2034
|
if (options.parallelJS && options.minifyJS !== identity && !options.processScripts?.length) {
|
|
@@ -1556,11 +2054,99 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1556
2054
|
}
|
|
1557
2055
|
}
|
|
1558
2056
|
|
|
2057
|
+
// Writes out a start tag for the `start` handler—right away, or once attribute values
|
|
2058
|
+
// that need asynchronous work (lazy module imports, minified URLs) resolve
|
|
2059
|
+
/**
|
|
2060
|
+
* @param {Array<{name: string, value: string | undefined, attr: HTMLAttribute} | undefined>} normalizedAttrs
|
|
2061
|
+
* @param {string} tag
|
|
2062
|
+
* @param {boolean} unary
|
|
2063
|
+
* @param {boolean} autoGenerated
|
|
2064
|
+
* @param {boolean | undefined} fragmentJoinsTag
|
|
2065
|
+
* @param {string | boolean | undefined} hasUnarySlash
|
|
2066
|
+
* @param {boolean | undefined} optional
|
|
2067
|
+
* @param {ProcessedOptions | null} restoreOptions - Context a unary tag pushed, or null
|
|
2068
|
+
*/
|
|
2069
|
+
function emitStartTag(normalizedAttrs, tag, unary, autoGenerated, fragmentJoinsTag, hasUnarySlash, optional, restoreOptions) {
|
|
2070
|
+
// Find the last kept attribute, then emit in order, with no intermediate array
|
|
2071
|
+
let lastKeptIndex = -1;
|
|
2072
|
+
for (let i = normalizedAttrs.length - 1; i >= 0; i--) {
|
|
2073
|
+
if (normalizedAttrs[i]) {
|
|
2074
|
+
lastKeptIndex = i;
|
|
2075
|
+
break;
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
// Without `maxLineLength`, a start tag is one buffer entry rather than one per attribute,
|
|
2079
|
+
// which keeps the buffer and the final join small (lines only break between entries);
|
|
2080
|
+
// the loop is written out per case, as a check per attribute measurably slows it down
|
|
2081
|
+
let tagText = '';
|
|
2082
|
+
if (lastKeptIndex !== -1) {
|
|
2083
|
+
if (!bufferTags) {
|
|
2084
|
+
tagText = fragmentJoinsTag ? '' : ' ';
|
|
2085
|
+
for (let i = 0; i <= lastKeptIndex; i++) {
|
|
2086
|
+
const normalizedAttr = normalizedAttrs[i];
|
|
2087
|
+
if (normalizedAttr) {
|
|
2088
|
+
if (uidAttr && normalizedAttr.name.includes(uidAttr)) {
|
|
2089
|
+
markTagFragments(normalizedAttr.name);
|
|
2090
|
+
}
|
|
2091
|
+
tagText += buildAttr(normalizedAttr, hasUnarySlash, options, i === lastKeptIndex, uidAttr);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
} else {
|
|
2095
|
+
if (!fragmentJoinsTag) {
|
|
2096
|
+
bufferPush(' ', true);
|
|
2097
|
+
}
|
|
2098
|
+
for (let i = 0; i <= lastKeptIndex; i++) {
|
|
2099
|
+
const normalizedAttr = normalizedAttrs[i];
|
|
2100
|
+
if (normalizedAttr) {
|
|
2101
|
+
if (uidAttr && normalizedAttr.name.includes(uidAttr)) {
|
|
2102
|
+
markTagFragments(normalizedAttr.name);
|
|
2103
|
+
}
|
|
2104
|
+
const builtAttr = buildAttr(normalizedAttr, hasUnarySlash, options, i === lastKeptIndex, uidAttr);
|
|
2105
|
+
// One entry with the tag name, so that no line break can come between them
|
|
2106
|
+
if (i === 0 && fragmentJoinsTag) {
|
|
2107
|
+
buffer[buffer.length - 1] += builtAttr;
|
|
2108
|
+
} else {
|
|
2109
|
+
bufferPush(builtAttr, true);
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
} else if (optional && optionalStartTags.has(tag)) {
|
|
2115
|
+
// Start tag must never be omitted if it has any attributes
|
|
2116
|
+
optionalStartTag = tag;
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
buffer[buffer.length - 1] += tagText + (hasUnarySlash ? '/' : '') + '>';
|
|
2120
|
+
|
|
2121
|
+
impliedStartTag = autoGenerated && !options.includeAutoGeneratedTags ? tag : '';
|
|
2122
|
+
if (impliedStartTag) {
|
|
2123
|
+
removeStartTag();
|
|
2124
|
+
optionalStartTag = '';
|
|
2125
|
+
currentTag = '';
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
// `end` restores what a start tag pushed, and a unary tag never reaches it
|
|
2129
|
+
if (restoreOptions) {
|
|
2130
|
+
options = restoreOptions;
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
// What a unary tag holds ends with the tag, so no text can belong to it
|
|
2134
|
+
if (unary) {
|
|
2135
|
+
currentTag = '';
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
|
|
1559
2139
|
// SVG subtree capture: When SVGO is active, record buffer positions for post-processing
|
|
1560
2140
|
/** @type {Array<{start: number, end: number}>} */
|
|
1561
|
-
const svgBlocks = [];
|
|
2141
|
+
const svgBlocks = [];
|
|
1562
2142
|
let svgBufferStartIndex = -1;
|
|
1563
2143
|
let svgDepth = 0;
|
|
2144
|
+
// HTML raw text in an SVG block, which XML cannot read as HTML does,
|
|
2145
|
+
// passes SVGO as a placeholder—a comment, as SVGO minifies `style` elements
|
|
2146
|
+
// wherever they are
|
|
2147
|
+
/** @type {string[]} */
|
|
2148
|
+
const svgRawTexts = [];
|
|
2149
|
+
let uidSVGRawText = '';
|
|
1564
2150
|
|
|
1565
2151
|
// One-time probe: If the input contains no SVG/MathML elements and the call
|
|
1566
2152
|
// isn’t already inside foreign content (recursive calls inherit options),
|
|
@@ -1569,7 +2155,13 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1569
2155
|
|
|
1570
2156
|
const parser = new HTMLParser(value, {
|
|
1571
2157
|
partialMarkup: partialMarkup ?? options.partialMarkup,
|
|
2158
|
+
// The short doctype makes the output no-quirks, so the input is read as such
|
|
2159
|
+
noQuirksMode: options.useShortDoctype,
|
|
1572
2160
|
continueOnParseError: options.continueOnParseError,
|
|
2161
|
+
// Recovered errors would have aborted without the option, so they are worth knowing about
|
|
2162
|
+
parseError: options.continueOnParseError && options.log !== identity
|
|
2163
|
+
? (/** @type {string} */ message) => options.log('Warning: ' + message)
|
|
2164
|
+
: undefined,
|
|
1573
2165
|
customAttrAssign: options.customAttrAssign,
|
|
1574
2166
|
customAttrSurround: options.customAttrSurround,
|
|
1575
2167
|
// Compute `nextTag` only when whitespace collapse features require it
|
|
@@ -1577,7 +2169,7 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1577
2169
|
// `keepClosingSlash` calls the slash meaningful, which decides how the input is read as well
|
|
1578
2170
|
selfClosingSlash: options.keepClosingSlash,
|
|
1579
2171
|
|
|
1580
|
-
start:
|
|
2172
|
+
start: function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ unary, /** @type {string} */ unarySlash, /** @type {boolean} */ autoGenerated) {
|
|
1581
2173
|
// `lowerTag` stays '' when no foreign content is around—the SVG/MathML
|
|
1582
2174
|
// checks below can then never match, and no per-tag lowercasing is needed
|
|
1583
2175
|
let lowerTag = '';
|
|
@@ -1588,31 +2180,36 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1588
2180
|
if (hasForeignContext) {
|
|
1589
2181
|
lowerTag = tag.toLowerCase();
|
|
1590
2182
|
if (lowerTag === 'svg' || lowerTag === 'math') {
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
2183
|
+
if (lowerTag === 'math' && options.documentState) {
|
|
2184
|
+
options.documentState.hasMathML = true;
|
|
2185
|
+
}
|
|
2186
|
+
// Preserve the surrounding HTML context’s slash handling so
|
|
2187
|
+
// `foreignObject`/`annotation-xml` can restore it
|
|
1595
2188
|
const keepClosingSlashHTML = Boolean(options.keepClosingSlash);
|
|
1596
2189
|
options = Object.create(options);
|
|
1597
|
-
|
|
2190
|
+
// SVGO reads an SVG block whole, nested MathML included, so what the
|
|
2191
|
+
// block is stays true inside it
|
|
2192
|
+
options.insideSVG = lowerTag === 'svg' || Boolean(options.insideSVG);
|
|
2193
|
+
// XML reads names as written, so wherever SVGO reads, they are written the way HTML reads
|
|
2194
|
+
// them (`viewbox` as `viewBox`), and attributes differing only in case are one attribute
|
|
2195
|
+
const readBySVGO = options.insideSVG && Boolean(options.minifySVG);
|
|
2196
|
+
options.caseSensitive = !readBySVGO;
|
|
1598
2197
|
options.keepClosingSlash = true;
|
|
1599
|
-
options.name = identity;
|
|
1600
|
-
options.nameHTML = nameHTML;
|
|
2198
|
+
options.name = readBySVGO ? nameForeign : identity;
|
|
1601
2199
|
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
2200
|
options.insideForeignContent = true;
|
|
1605
2201
|
// Disable HTML-specific options that produce invalid XML:
|
|
1606
2202
|
// SVG with `minifySVG` enabled is passed to SVGO, which requires valid XML input;
|
|
1607
2203
|
// MathML is never processed by SVGO, so these restrictions never apply to it
|
|
1608
2204
|
if (lowerTag === 'svg' && options.minifySVG) {
|
|
1609
2205
|
options.removeAttributeQuotes = false;
|
|
1610
|
-
//
|
|
1611
|
-
//
|
|
1612
|
-
options.decodeEntities =
|
|
2206
|
+
// Text and attribute values are decoded as HTML reads them, for transforms to read
|
|
2207
|
+
// them so, too, and then escaped for XML (see `escapeXML`) rather than for HTML
|
|
2208
|
+
options.decodeEntities = true;
|
|
1613
2209
|
// Omitting a start and end tag both would keep the block well-formed, which this misses
|
|
1614
2210
|
options.removeOptionalTags = false;
|
|
1615
2211
|
options.collapseBooleanAttributes = false;
|
|
2212
|
+
options.collapseEmptyAttributes = false;
|
|
1616
2213
|
options.includeAutoGeneratedTags = true;
|
|
1617
2214
|
}
|
|
1618
2215
|
options.removeTagWhitespace = false;
|
|
@@ -1630,17 +2227,21 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1630
2227
|
// What the parser read the slash as, so that the two agree here as they do in HTML
|
|
1631
2228
|
options.keepClosingSlash = options.keepClosingSlashHTML ?? false;
|
|
1632
2229
|
options.nameParent = nameParent; // Preserve for the element tag itself
|
|
1633
|
-
options.name =
|
|
2230
|
+
options.name = lowercase;
|
|
1634
2231
|
options.insideForeignContent = false;
|
|
1635
|
-
// Note: `removeAttributeQuotes
|
|
1636
|
-
// stay
|
|
1637
|
-
// must be valid XML for SVGO processing
|
|
2232
|
+
// Note: `removeAttributeQuotes` and `removeTagWhitespace` stay disabled,
|
|
2233
|
+
// and values stay escaped for XML (inherited from SVG context), because
|
|
2234
|
+
// the entire SVG block must be valid XML for SVGO processing
|
|
1638
2235
|
useNameParentForTag = true;
|
|
1639
2236
|
pushedContext = true;
|
|
1640
2237
|
}
|
|
1641
2238
|
}
|
|
1642
|
-
// `nameParent` is
|
|
1643
|
-
|
|
2239
|
+
// `nameParent` is set whenever `useNameParentForTag` is; the extra check narrows the type
|
|
2240
|
+
const nameTag = useNameParentForTag && options.nameParent ? options.nameParent : options.name;
|
|
2241
|
+
const tagSource = tag;
|
|
2242
|
+
tag = nameTag(tag);
|
|
2243
|
+
// HTML names are written as in the source under `caseSensitive`, foreign ones as named anyway
|
|
2244
|
+
const tagOut = namesAsWritten && nameTag === lowercase ? tagSource : tag;
|
|
1644
2245
|
currentTag = tag;
|
|
1645
2246
|
charsPrevTag = tag;
|
|
1646
2247
|
if (!inlineTextSet.has(tag)) {
|
|
@@ -1654,7 +2255,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1654
2255
|
const htmlTag = htmlElements.has(tag);
|
|
1655
2256
|
// `<html>` may be omitted if first thing inside is not a comment
|
|
1656
2257
|
// `<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>`,
|
|
2258
|
+
// `<body>` may be omitted if first thing inside is not space, comment, `<meta>`, `<link>`,
|
|
2259
|
+
// `<script>`, `<style>`, or `<template>`
|
|
1658
2260
|
// `<colgroup>` may be omitted if first thing inside is `<col>`
|
|
1659
2261
|
// `<tbody>` may be omitted if first thing inside is `<tr>`
|
|
1660
2262
|
if (htmlTag && canRemoveParentTag(optionalStartTag, tag)) {
|
|
@@ -1662,31 +2264,36 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1662
2264
|
}
|
|
1663
2265
|
optionalStartTag = '';
|
|
1664
2266
|
// End-tag-followed-by-start-tag omission rules
|
|
1665
|
-
|
|
1666
|
-
|
|
2267
|
+
// Outside no-quirks mode, `table` doesn’t (or may not) close a `p`
|
|
2268
|
+
if (htmlTag && canRemovePrecedingTag(optionalEndTag, tag) && (tableClosesP || optionalEndTag !== 'p' || tag !== 'table')) {
|
|
2269
|
+
// Only a start tag that gets written can stand in for the end tag
|
|
2270
|
+
if (optionalEndTagEmitted && (!autoGenerated || options.includeAutoGeneratedTags)) {
|
|
1667
2271
|
removeEndTag();
|
|
1668
2272
|
}
|
|
1669
2273
|
// `<colgroup>` cannot be omitted if preceding `</colgroup>` is omitted
|
|
1670
|
-
// `<tbody>` cannot be omitted if preceding `</tbody>`, `</thead>`, or `</tfoot>` is
|
|
2274
|
+
// `<tbody>` cannot be omitted if preceding `</tbody>`, `</thead>`, or `</tfoot>` is
|
|
2275
|
+
// omitted
|
|
1671
2276
|
optional = !isStartTagMandatory(optionalEndTag, tag);
|
|
1672
2277
|
}
|
|
1673
2278
|
optionalEndTag = '';
|
|
1674
2279
|
optionalEndTagEmitted = false;
|
|
1675
2280
|
}
|
|
1676
2281
|
|
|
1677
|
-
// Set whitespace flags for nested tags (e.g., `<code>` within a `<pre>`)
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
2282
|
+
// Set whitespace flags for nested tags (e.g., `<code>` within a `<pre>`); verbatim
|
|
2283
|
+
// whitespace is tracked without `collapseWhitespace` too, as `removeWhitespaceLine` spares it
|
|
2284
|
+
if (options.collapseWhitespace && !stackNoTrimWhitespace.length) {
|
|
2285
|
+
squashTrailingWhitespace(tag);
|
|
2286
|
+
}
|
|
2287
|
+
if (options.collapseWhitespace && !unary && inlineElementsTransparent.has(tag)) {
|
|
2288
|
+
transparentDepth++;
|
|
2289
|
+
}
|
|
2290
|
+
if (!unary) {
|
|
2291
|
+
if (!canTrimWhitespace(tag, tagOut, attrs) || stackNoTrimWhitespace.length) {
|
|
2292
|
+
stackNoTrimWhitespace.push(tag);
|
|
2293
|
+
if (tag === 'pre' || tag === 'textarea') preTextareaDepth++;
|
|
1681
2294
|
}
|
|
1682
|
-
if (!
|
|
1683
|
-
|
|
1684
|
-
stackNoTrimWhitespace.push(tag);
|
|
1685
|
-
if (tag === 'pre' || tag === 'textarea') preTextareaDepth++;
|
|
1686
|
-
}
|
|
1687
|
-
if (!canCollapseWhitespace(tag, attrs) || stackNoCollapseWhitespace.length) {
|
|
1688
|
-
stackNoCollapseWhitespace.push(tag);
|
|
1689
|
-
}
|
|
2295
|
+
if (options.collapseWhitespace && (!canCollapseWhitespace(tag, tagOut, attrs) || stackNoCollapseWhitespace.length)) {
|
|
2296
|
+
stackNoCollapseWhitespace.push(tag);
|
|
1690
2297
|
}
|
|
1691
2298
|
}
|
|
1692
2299
|
|
|
@@ -1698,78 +2305,69 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1698
2305
|
svgDepth++;
|
|
1699
2306
|
}
|
|
1700
2307
|
|
|
1701
|
-
const openTag = '<' +
|
|
2308
|
+
const openTag = '<' + tagOut;
|
|
1702
2309
|
// SVGO reads the whole SVG block as XML, where an element closes itself or not, so
|
|
1703
2310
|
// every unary element in there is written with a slash
|
|
1704
2311
|
const needsXMLSlash = unary && Boolean(options.insideSVG) && Boolean(options.minifySVG);
|
|
1705
2312
|
const hasUnarySlash = needsXMLSlash || (unarySlash && (useNameParentForTag ? optionsParent : options).keepClosingSlash);
|
|
1706
2313
|
|
|
1707
|
-
|
|
2314
|
+
bufferPush(openTag, true);
|
|
2315
|
+
|
|
2316
|
+
if (options.removeEmptyElements) {
|
|
2317
|
+
if (unary) {
|
|
2318
|
+
markOpenElementFilled();
|
|
2319
|
+
} else {
|
|
2320
|
+
// A start tag not written can’t be removed with its element
|
|
2321
|
+
openElements.push({ tag, index: buffer.length - 1, empty: !autoGenerated || Boolean(options.includeAutoGeneratedTags) });
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
const fragmentJoinsTag = uidAttrExactPattern ? joinFragmentAttrs(attrs) : false;
|
|
2326
|
+
// Whatever runs into the tag name has to stay first
|
|
2327
|
+
const tagFragment = fragmentJoinsTag ? attrs.shift() : undefined;
|
|
1708
2328
|
|
|
1709
|
-
//
|
|
1710
|
-
// Duplicate attributes result in invalid HTML
|
|
2329
|
+
// Duplicate attributes are invalid; per spec, the first one wins
|
|
1711
2330
|
// https://html.spec.whatwg.org/multipage/parsing.html#attribute-name-state
|
|
1712
2331
|
deduplicateAttributes(attrs, Boolean(options.caseSensitive));
|
|
1713
2332
|
|
|
1714
2333
|
if (options.sortAttributes) {
|
|
1715
|
-
// By the time tags are processed, `createSortFns` has replaced any
|
|
1716
|
-
|
|
2334
|
+
// By the time tags are processed, `createSortFns` has replaced any
|
|
2335
|
+
// truthy non-function value
|
|
2336
|
+
/** @type {(tag: string, attrs: HTMLAttribute[]) => void} */ (options.sortAttributes)(tagOut, attrs);
|
|
2337
|
+
}
|
|
2338
|
+
if (tagFragment) {
|
|
2339
|
+
attrs.unshift(tagFragment);
|
|
1717
2340
|
}
|
|
1718
2341
|
|
|
1719
2342
|
const attrResults = new Array(attrs.length);
|
|
1720
2343
|
let anyThenable = false;
|
|
1721
2344
|
for (let i = 0; i < attrs.length; i++) {
|
|
1722
|
-
const
|
|
2345
|
+
const attr = /** @type {HTMLAttribute} */ (attrs[i]);
|
|
2346
|
+
const result = opaqueAttrs.has(attr)
|
|
2347
|
+
? { name: attr.name, value: undefined, attr }
|
|
2348
|
+
: normalizeAttr(attr, attrs, tag, tagOut, options, minifyHTML, markers);
|
|
1723
2349
|
if (!anyThenable && isThenable(result)) {
|
|
1724
2350
|
anyThenable = true;
|
|
1725
2351
|
}
|
|
1726
2352
|
attrResults[i] = result;
|
|
1727
2353
|
}
|
|
1728
|
-
//
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
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 = '';
|
|
2354
|
+
// Only an attribute value that needs asynchronous work defers the write-out;
|
|
2355
|
+
// with none of those, the tag is written before the handler returns
|
|
2356
|
+
const restoreOptions = unary && pushedContext ? optionsParent : null;
|
|
2357
|
+
if (anyThenable) {
|
|
2358
|
+
return Promise.all(attrResults).then(resolved => {
|
|
2359
|
+
emitStartTag(resolved, tag, unary, autoGenerated, fragmentJoinsTag, hasUnarySlash, optional, restoreOptions);
|
|
2360
|
+
});
|
|
1768
2361
|
}
|
|
2362
|
+
emitStartTag(/** @type {Array<{name: string, value: string | undefined, attr: HTMLAttribute} | undefined>} */ (attrResults), tag, unary, autoGenerated, fragmentJoinsTag, hasUnarySlash, optional, restoreOptions);
|
|
2363
|
+
return undefined;
|
|
1769
2364
|
},
|
|
1770
|
-
end: function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ autoGenerated) {
|
|
2365
|
+
end: function (/** @type {string} */ tag, /** @type {HTMLAttribute[]} */ attrs, /** @type {boolean} */ autoGenerated, /** @type {string | undefined} */ rest, /** @type {boolean | undefined} */ holdsTable) {
|
|
1771
2366
|
// As in `start`: `lowerTag` stays '' when no foreign content is around
|
|
1772
2367
|
let lowerTag = '';
|
|
2368
|
+
// Named as the start tag was: an `svg` or `math` element in its own context,
|
|
2369
|
+
// a `foreignObject` or `annotation-xml` element in its parent’s
|
|
2370
|
+
let name = options.name;
|
|
1773
2371
|
if (hasForeignContext) {
|
|
1774
2372
|
lowerTag = tag.toLowerCase();
|
|
1775
2373
|
// Restore parent context when exiting SVG/MathML or HTML-in-foreign-content elements
|
|
@@ -1778,71 +2376,105 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1778
2376
|
} else if ((lowerTag === 'foreignobject' || lowerTag === 'annotation-xml') &&
|
|
1779
2377
|
!options.insideForeignContent && Object.getPrototypeOf(options).insideForeignContent) {
|
|
1780
2378
|
options = Object.getPrototypeOf(options);
|
|
2379
|
+
name = options.name;
|
|
1781
2380
|
}
|
|
1782
2381
|
}
|
|
1783
|
-
|
|
2382
|
+
const tagSource = tag;
|
|
2383
|
+
tag = name(tag);
|
|
2384
|
+
// As in `start`
|
|
2385
|
+
const tagOut = namesAsWritten && name === lowercase ? tagSource : tag;
|
|
2386
|
+
let endTagText = '</' + tagOut + '>';
|
|
2387
|
+
// Custom fragments after the name are kept, next to it if they were in the source
|
|
2388
|
+
if (rest && uidAttr && rest.includes(uidAttr)) {
|
|
2389
|
+
markTagFragments(rest);
|
|
2390
|
+
const uidMatch = /** @type {RegExp} */ (uidAttrLeadingPattern).exec(rest);
|
|
2391
|
+
const joinsTag = uidMatch !== null && rest.startsWith('\t' + uidAttr) &&
|
|
2392
|
+
ignoredCustomMarkupChunks[+(uidMatch[1] ?? 0)]?.[1] === '';
|
|
2393
|
+
// Anything else an end tag holds is dropped, as without fragments
|
|
2394
|
+
const marker = uidAttr;
|
|
2395
|
+
const fragments = Array.from(rest.matchAll(/** @type {RegExp} */ (uidPattern)), uid => marker + (uid[2] ?? '') + marker);
|
|
2396
|
+
endTagText = '</' + tagOut + (joinsTag ? '' : ' ') + fragments.join(' ') + '>';
|
|
2397
|
+
}
|
|
1784
2398
|
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
} else {
|
|
1793
|
-
squashTrailingWhitespace('/' + tag);
|
|
1794
|
-
}
|
|
1795
|
-
if (stackNoCollapseWhitespace.length &&
|
|
1796
|
-
tag === stackNoCollapseWhitespace[stackNoCollapseWhitespace.length - 1]) {
|
|
1797
|
-
stackNoCollapseWhitespace.pop();
|
|
2399
|
+
const insideNoTrim = stackNoTrimWhitespace.length > 0;
|
|
2400
|
+
let closesNoTrim = false;
|
|
2401
|
+
if (stackNoTrimWhitespace.length) {
|
|
2402
|
+
if (tag === stackNoTrimWhitespace[stackNoTrimWhitespace.length - 1]) {
|
|
2403
|
+
if (tag === 'pre' || tag === 'textarea') preTextareaDepth--;
|
|
2404
|
+
stackNoTrimWhitespace.pop();
|
|
2405
|
+
closesNoTrim = !stackNoTrimWhitespace.length;
|
|
1798
2406
|
}
|
|
2407
|
+
} else if (options.collapseWhitespace) {
|
|
2408
|
+
squashTrailingWhitespace('/' + tag);
|
|
2409
|
+
}
|
|
2410
|
+
if (transparentDepth && inlineElementsTransparent.has(tag)) {
|
|
2411
|
+
transparentDepth--;
|
|
1799
2412
|
}
|
|
2413
|
+
let closesNoCollapse = false;
|
|
2414
|
+
if (stackNoCollapseWhitespace.length &&
|
|
2415
|
+
tag === stackNoCollapseWhitespace[stackNoCollapseWhitespace.length - 1]) {
|
|
2416
|
+
stackNoCollapseWhitespace.pop();
|
|
2417
|
+
closesNoCollapse = !stackNoCollapseWhitespace.length;
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
const endsImpliedStart = !autoGenerated && impliedStartTag === tag;
|
|
2421
|
+
// A `p` that holds a `table` while the mode is unknown needs its end tag as written: One
|
|
2422
|
+
// after the `table` that the source lacks would be stray in no-quirks mode, and one that it
|
|
2423
|
+
// has, closing the `p` in quirks mode, would be missed there
|
|
2424
|
+
const skipsEndTag = autoGenerated && (!options.includeAutoGeneratedTags || Boolean(holdsTable));
|
|
2425
|
+
impliedStartTag = '';
|
|
1800
2426
|
|
|
1801
2427
|
let isElementEmpty = false;
|
|
1802
2428
|
if (tag === currentTag) {
|
|
1803
2429
|
currentTag = '';
|
|
1804
2430
|
isElementEmpty = !hasChars;
|
|
1805
2431
|
}
|
|
2432
|
+
// A stray end tag has no open element of its own
|
|
2433
|
+
const openElement = options.removeEmptyElements && openElements[openElements.length - 1]?.tag === tag ? openElements.pop() : undefined;
|
|
2434
|
+
// Emptied by removing what it held, as long as its start tag is still the last one written
|
|
2435
|
+
const isElementEmptied = !isElementEmpty && Boolean(openElement?.empty) && lastStartTagIndex() === openElement?.index;
|
|
1806
2436
|
|
|
1807
2437
|
if (options.removeOptionalTags) {
|
|
1808
|
-
// `<html>`, `<head
|
|
2438
|
+
// `<html>`, `<head>`, or `<body>` may be omitted if the element is empty
|
|
1809
2439
|
if (isElementEmpty && topLevelElements.has(optionalStartTag)) {
|
|
1810
2440
|
removeStartTag();
|
|
1811
2441
|
}
|
|
1812
2442
|
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
|
-
//
|
|
1817
|
-
//
|
|
1818
|
-
//
|
|
1819
|
-
if (tag && optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag) && (optionalEndTag !== 'p' ||
|
|
1820
|
-
removeEndTag();
|
|
2443
|
+
// `</html>` or `</body>` may be omitted if not followed by comment
|
|
2444
|
+
// `</head>` may be omitted if not followed by space or comment
|
|
2445
|
+
// `</p>` may be omitted if no more content in parent, as long as the parent’s end tag
|
|
2446
|
+
// closes the `p` in browsers (`pClosingParents`)
|
|
2447
|
+
// Except for `</dt>` or `</thead>`, end tags may be omitted if no more content in parent
|
|
2448
|
+
// https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
|
|
2449
|
+
if (tag && optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag) && (optionalEndTag !== 'p' || pClosingParents.has(tag))) {
|
|
2450
|
+
removeEndTag(insideNoTrim);
|
|
1821
2451
|
}
|
|
1822
|
-
optionalEndTag = optionalEndTags.has(tag) ? tag : '';
|
|
2452
|
+
optionalEndTag = optionalEndTags.has(tag) && !endsImpliedStart && !holdsTable ? tag : '';
|
|
1823
2453
|
optionalEndTagEmitted = true;
|
|
1824
2454
|
}
|
|
1825
2455
|
|
|
1826
|
-
|
|
2456
|
+
let isElementRemoved = false;
|
|
2457
|
+
// A formatting element closed by a block is reopened after it by browsers, so it has to stay
|
|
2458
|
+
if (options.removeEmptyElements && (isElementEmpty || isElementEmptied) && !options.insideForeignContent && canRemoveElement(tag, attrs) &&
|
|
2459
|
+
!(autoGenerated && formattingElements.has(tag))) {
|
|
1827
2460
|
let preserve = false;
|
|
1828
2461
|
if (removeEmptyElementsExcept.length) {
|
|
1829
|
-
// Normalize attribute names for comparison with specs
|
|
1830
2462
|
const normalizedAttrs = attrs.map((/** @type {HTMLAttribute} */ attr) => ({ ...attr, name: resolveName(attr.name) }));
|
|
1831
2463
|
preserve = shouldPreserveEmptyElement(tag, normalizedAttrs, removeEmptyElementsExcept);
|
|
1832
2464
|
}
|
|
1833
2465
|
|
|
1834
2466
|
if (!preserve) {
|
|
1835
|
-
// Remove last element from buffer
|
|
1836
2467
|
removeStartTag();
|
|
2468
|
+
isElementRemoved = true;
|
|
1837
2469
|
optionalStartTag = '';
|
|
1838
2470
|
optionalEndTag = '';
|
|
1839
2471
|
optionalEndTagEmitted = false;
|
|
1840
2472
|
} else {
|
|
1841
2473
|
// Preserve the element—add closing tag
|
|
1842
|
-
if (
|
|
2474
|
+
if (skipsEndTag) {
|
|
1843
2475
|
optionalEndTagEmitted = false;
|
|
1844
2476
|
} else {
|
|
1845
|
-
|
|
2477
|
+
bufferPush(endTagText, true);
|
|
1846
2478
|
}
|
|
1847
2479
|
charsPrevTag = '/' + tag;
|
|
1848
2480
|
if (!inlineElements.has(tag)) {
|
|
@@ -1852,10 +2484,10 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1852
2484
|
}
|
|
1853
2485
|
}
|
|
1854
2486
|
} else {
|
|
1855
|
-
if (
|
|
2487
|
+
if (skipsEndTag) {
|
|
1856
2488
|
optionalEndTagEmitted = false;
|
|
1857
2489
|
} else {
|
|
1858
|
-
|
|
2490
|
+
bufferPush(endTagText, true);
|
|
1859
2491
|
}
|
|
1860
2492
|
charsPrevTag = '/' + tag;
|
|
1861
2493
|
if (!inlineElements.has(tag)) {
|
|
@@ -1865,6 +2497,18 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1865
2497
|
}
|
|
1866
2498
|
}
|
|
1867
2499
|
|
|
2500
|
+
if (closesNoTrim && !isElementRemoved) {
|
|
2501
|
+
noTrimEndIndex = buffer.length - 1;
|
|
2502
|
+
}
|
|
2503
|
+
if (closesNoCollapse && !isElementRemoved) {
|
|
2504
|
+
noCollapseEndIndex = buffer.length - 1;
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
// A kept element fills the one it sits in
|
|
2508
|
+
if (openElement && !isElementRemoved) {
|
|
2509
|
+
markOpenElementFilled();
|
|
2510
|
+
}
|
|
2511
|
+
|
|
1868
2512
|
// SVG subtree capture: Record end position for post-processing with SVGO
|
|
1869
2513
|
if (lowerTag === 'svg' && options.minifySVG && svgDepth > 0) {
|
|
1870
2514
|
svgDepth--;
|
|
@@ -1874,24 +2518,36 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1874
2518
|
}
|
|
1875
2519
|
}
|
|
1876
2520
|
},
|
|
1877
|
-
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs) {
|
|
2521
|
+
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source) {
|
|
1878
2522
|
// Publish this node’s context for the `charsCollapse`/`charsFinalize` phases
|
|
1879
2523
|
textPrevTag = prevTag === '' ? 'comment' : prevTag;
|
|
1880
2524
|
textNextTag = nextTag === '' ? 'comment' : nextTag;
|
|
1881
2525
|
textPrevAttrs = prevAttrs || [];
|
|
1882
2526
|
textNextAttrs = nextAttrs || [];
|
|
1883
2527
|
|
|
1884
|
-
//
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
const
|
|
2528
|
+
// Whether this text node needs any async work. In foreign content, text reads references
|
|
2529
|
+
// and CDATA sections, and `script` and `style` hold markup, so their text is a source only
|
|
2530
|
+
// where it is all they hold (and in SVG, where they run and apply)
|
|
2531
|
+
const foreign = Boolean(options.insideForeignContent);
|
|
2532
|
+
textForeign = foreign;
|
|
2533
|
+
const holdsSource = !foreign || Boolean(source);
|
|
2534
|
+
const needsProcessScript = holdsSource && specialContentElements.has(currentTag) && (options.processScripts || hasJsonScriptType(currentAttrs));
|
|
2535
|
+
const needsMinifyJS = holdsSource && options.minifyJS !== identity && isExecutableScript(currentTag, currentAttrs);
|
|
1888
2536
|
const isModuleScript = needsMinifyJS && currentAttrs.some(
|
|
1889
2537
|
a => a.name.toLowerCase() === 'type' && (a.value ?? '').trim().toLowerCase() === 'module'
|
|
1890
2538
|
);
|
|
1891
|
-
const needsMinifyCSS = options.minifyCSS !== identity && isStyleElement(currentTag, currentAttrs);
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
2539
|
+
const needsMinifyCSS = holdsSource && options.minifyCSS !== identity && isStyleElement(currentTag, currentAttrs);
|
|
2540
|
+
textForeignDecoded = foreign && Boolean(options.decodeEntities || needsProcessScript || needsMinifyJS || needsMinifyCSS);
|
|
2541
|
+
const needsDecode = Boolean(text) && (foreign
|
|
2542
|
+
? textForeignDecoded && (text.indexOf('&') !== -1 || text.indexOf('<![CDATA[') !== -1)
|
|
2543
|
+
: options.decodeEntities && text.indexOf('&') !== -1 && !holdsRawText());
|
|
2544
|
+
|
|
2545
|
+
// Fast path: All work is sync—skip async machinery (decoding counts
|
|
2546
|
+
// once `entities` has loaded)
|
|
2547
|
+
if ((!needsDecode || decodeHTMLFn) && !needsProcessScript && !needsMinifyJS && !needsMinifyCSS) {
|
|
2548
|
+
if (needsDecode && decodeHTMLFn) {
|
|
2549
|
+
text = foreign ? decodeForeignText(text, decodeHTMLFn) : decodeHTMLFn(text);
|
|
2550
|
+
}
|
|
1895
2551
|
charsFinalize(charsCollapse(text));
|
|
1896
2552
|
return;
|
|
1897
2553
|
}
|
|
@@ -1899,7 +2555,8 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1899
2555
|
// Slow path: At least one async step required
|
|
1900
2556
|
return (async () => {
|
|
1901
2557
|
if (needsDecode) {
|
|
1902
|
-
|
|
2558
|
+
const decode = /** @type {(text: string) => string} */ (await getDecodeHTML());
|
|
2559
|
+
text = foreign ? decodeForeignText(text, decode) : decode(text);
|
|
1903
2560
|
}
|
|
1904
2561
|
text = charsCollapse(text);
|
|
1905
2562
|
if (needsProcessScript) {
|
|
@@ -1915,31 +2572,44 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1915
2572
|
charsFinalize(text);
|
|
1916
2573
|
})();
|
|
1917
2574
|
},
|
|
1918
|
-
|
|
2575
|
+
// `markup` is the comment as written, where it is to stay that way (`<? x>`)
|
|
2576
|
+
comment: function (/** @type {string} */ text, /** @type {boolean} */ nonStandard, /** @type {string | undefined} */ markup) {
|
|
1919
2577
|
const prefix = nonStandard ? '<!' : '<!--';
|
|
1920
2578
|
const suffix = nonStandard ? '>' : '-->';
|
|
1921
2579
|
|
|
1922
|
-
if (options.removeComments) {
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
} else {
|
|
1926
|
-
text = '';
|
|
1927
|
-
}
|
|
2580
|
+
if (options.removeComments && !isIgnoredComment(text, options)) {
|
|
2581
|
+
text = '';
|
|
2582
|
+
removed = true;
|
|
1928
2583
|
} else {
|
|
1929
|
-
text = prefix + text + suffix;
|
|
2584
|
+
text = markup ?? prefix + text + suffix;
|
|
1930
2585
|
}
|
|
1931
2586
|
commentFinalize(text);
|
|
1932
2587
|
},
|
|
1933
|
-
|
|
1934
|
-
|
|
2588
|
+
// Kept as written, as content may be inserted at one (`<template for>`)
|
|
2589
|
+
processingInstruction: function (/** @type {string} */ text) {
|
|
2590
|
+
hasChars = true;
|
|
2591
|
+
markOpenElementFilled();
|
|
2592
|
+
commentFinalize(text);
|
|
2593
|
+
},
|
|
2594
|
+
strayEnd: function () {
|
|
2595
|
+
removed = true;
|
|
2596
|
+
},
|
|
2597
|
+
doctype: function (/** @type {string} */ doctype, /** @type {boolean} */ noQuirksMode) {
|
|
2598
|
+
tableClosesP = noQuirksMode;
|
|
2599
|
+
bufferPush(options.useShortDoctype
|
|
1935
2600
|
? '<!doctype' +
|
|
1936
2601
|
(options.removeTagWhitespace ? '' : ' ') + 'html>'
|
|
1937
|
-
: collapseWhitespaceAll(doctype));
|
|
2602
|
+
: collapseWhitespaceAll(doctype), false);
|
|
1938
2603
|
}
|
|
1939
2604
|
});
|
|
1940
2605
|
|
|
1941
2606
|
await parser.parse();
|
|
1942
2607
|
|
|
2608
|
+
// Nothing follows at the end, so pending whitespace goes (before SVG blocks shift the buffer)
|
|
2609
|
+
if (transparentGapIndex !== -1) {
|
|
2610
|
+
settleTransparentGap(Boolean(options.conservativeCollapse));
|
|
2611
|
+
}
|
|
2612
|
+
|
|
1943
2613
|
// Post-processing: Optimize SVG blocks with SVGO
|
|
1944
2614
|
// Run all SVGO calls in parallel, then splice results in reverse to preserve indices
|
|
1945
2615
|
const minifySVG = options.minifySVG;
|
|
@@ -1951,7 +2621,20 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1951
2621
|
);
|
|
1952
2622
|
for (let i = svgBlocks.length - 1; i >= 0; i--) {
|
|
1953
2623
|
const block = svgBlocks[i];
|
|
1954
|
-
if (block)
|
|
2624
|
+
if (block) {
|
|
2625
|
+
buffer.splice(block.start, block.end - block.start, optimized[i] ?? '');
|
|
2626
|
+
bufferTags?.splice(block.start, block.end - block.start, false);
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
// Also where an SVG left open never reached SVGO
|
|
2631
|
+
if (svgRawTexts.length) {
|
|
2632
|
+
const pattern = new RegExp('/\\*!' + uidSVGRawText + '([0-9]+)\\*/', 'g');
|
|
2633
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
2634
|
+
const segment = /** @type {string} */ (buffer[i]);
|
|
2635
|
+
if (segment.indexOf(uidSVGRawText) !== -1) {
|
|
2636
|
+
buffer[i] = segment.replace(pattern, (/** @type {string} */ match, /** @type {string} */ index) => svgRawTexts[+index] ?? match);
|
|
2637
|
+
}
|
|
1955
2638
|
}
|
|
1956
2639
|
}
|
|
1957
2640
|
|
|
@@ -1961,32 +2644,40 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
1961
2644
|
if (topLevelElements.has(optionalStartTag)) {
|
|
1962
2645
|
removeStartTag();
|
|
1963
2646
|
}
|
|
1964
|
-
//
|
|
2647
|
+
// Except for `</dt>` or `</thead>`, end tags may be omitted if no more content in parent
|
|
1965
2648
|
if (optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag)) {
|
|
1966
2649
|
removeEndTag();
|
|
1967
2650
|
}
|
|
1968
2651
|
}
|
|
2652
|
+
// Collapsing also trims whitespace before trailing inline end tags; trimming the output
|
|
2653
|
+
// catches what it leaves at either end, like a space after a removed leading comment
|
|
1969
2654
|
if (options.collapseWhitespace) {
|
|
1970
2655
|
squashTrailingWhitespace('br');
|
|
1971
2656
|
}
|
|
2657
|
+
trimOutputWhitespace();
|
|
1972
2658
|
|
|
1973
|
-
return joinResultSegments(buffer, options, uidPattern
|
|
2659
|
+
return joinResultSegments(buffer, bufferTags ?? [], markers, options, uidPattern
|
|
1974
2660
|
? 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
|
-
|
|
1977
|
-
if (
|
|
1978
|
-
|
|
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));
|
|
2661
|
+
return str.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ match, /** @type {string} */ prefix, /** @type {string} */ index, /** @type {string} */ suffix, /** @type {number} */ offset, /** @type {string} */ string) {
|
|
2662
|
+
const chunks = ignoredCustomMarkupChunks[+index];
|
|
2663
|
+
if (!chunks) {
|
|
2664
|
+
return match;
|
|
1988
2665
|
}
|
|
1989
|
-
|
|
2666
|
+
if (!options.collapseWhitespace) {
|
|
2667
|
+
return chunks[0];
|
|
2668
|
+
}
|
|
2669
|
+
const leading = chunks[1] ?? '';
|
|
2670
|
+
const trailing = chunks[2] ?? '';
|
|
2671
|
+
const fragment = chunks[0].slice(leading.length, chunks[0].length - trailing.length);
|
|
2672
|
+
const inTag = customMarkupInTags.has(+index);
|
|
2673
|
+
const keep = inTag || customMarkupInCode.has(+index) || !options.trimCustomFragments;
|
|
2674
|
+
// The padding tabs are whitespace to the minifier, so where one is gone, the
|
|
2675
|
+
// minifier removed the whitespace, which makes it safe to trim
|
|
2676
|
+
const trimLeading = !keep && prefix === '';
|
|
2677
|
+
const trimTrailing = inTag ? string.charCodeAt(offset + match.length) === 62 /* > */ : !keep && suffix === '';
|
|
2678
|
+
return restoreFragmentSide(prefix.replace(RE_TABS, '') + leading, trimLeading, true) +
|
|
2679
|
+
fragment +
|
|
2680
|
+
restoreFragmentSide(suffix.replace(RE_TABS, '') + trailing, trimTrailing, false);
|
|
1990
2681
|
});
|
|
1991
2682
|
}
|
|
1992
2683
|
: identity, uidIgnore
|
|
@@ -2000,46 +2691,74 @@ async function minifyHTML(value, options, partialMarkup) {
|
|
|
2000
2691
|
|
|
2001
2692
|
/**
|
|
2002
2693
|
* @param {string[]} results
|
|
2694
|
+
* @param {boolean[]} resultTags Whether each result belongs to a start or end tag
|
|
2695
|
+
* @param {string[]} markers Custom fragment and `htmlmin:ignore` placeholder markers
|
|
2003
2696
|
* @param {ProcessedOptions} options
|
|
2004
2697
|
* @param {Function} restoreCustom
|
|
2005
2698
|
* @param {Function} restoreIgnore
|
|
2006
2699
|
*/
|
|
2007
|
-
function joinResultSegments(results, options, restoreCustom, restoreIgnore) {
|
|
2700
|
+
function joinResultSegments(results, resultTags, markers, options, restoreCustom, restoreIgnore) {
|
|
2008
2701
|
let str;
|
|
2009
2702
|
const maxLineLength = options.maxLineLength;
|
|
2010
|
-
const noNewlinesBeforeTagClose = options.noNewlinesBeforeTagClose;
|
|
2011
2703
|
|
|
2012
2704
|
if (maxLineLength) {
|
|
2013
|
-
|
|
2014
|
-
//
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2705
|
+
// Whitespace in tags is the only whitespace that can’t change the output, so lines break
|
|
2706
|
+
// there alone—in place of the space between attributes, or right before a tag’s `>`
|
|
2707
|
+
const noNewlinesBeforeTagClose = options.noNewlinesBeforeTagClose;
|
|
2708
|
+
/** @type {string[]} */
|
|
2709
|
+
const lines = [];
|
|
2710
|
+
let lineLength = 0;
|
|
2711
|
+
// Output since the last break opportunity, and what that opportunity is when not taken;
|
|
2712
|
+
// fragments are restored by chunk, as whitespace around them decides how they come back
|
|
2713
|
+
let chunk = '';
|
|
2714
|
+
/** @type {string | null} */
|
|
2715
|
+
let separator = null;
|
|
2716
|
+
const flush = (/** @type {string | null} */ nextSeparator) => {
|
|
2717
|
+
chunk = restoreIgnore(restoreCustom(chunk));
|
|
2718
|
+
const newline = chunk.indexOf('\n');
|
|
2719
|
+
const head = newline < 0 ? chunk.length : newline;
|
|
2720
|
+
// A line already too long gains nothing from moving a `>` that ends a line of its own
|
|
2721
|
+
const isUseless = separator === '' && head === 1 && lineLength > maxLineLength;
|
|
2722
|
+
if (separator !== null) {
|
|
2723
|
+
if (lineLength > 0 && lineLength + separator.length + head > maxLineLength && !isUseless) {
|
|
2724
|
+
lines.push('\n');
|
|
2725
|
+
lineLength = 0;
|
|
2726
|
+
} else if (separator) {
|
|
2727
|
+
lines.push(separator);
|
|
2728
|
+
lineLength += separator.length;
|
|
2729
|
+
}
|
|
2030
2730
|
}
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2731
|
+
lines.push(chunk);
|
|
2732
|
+
lineLength = newline < 0 ? lineLength + chunk.length : chunk.length - chunk.lastIndexOf('\n') - 1;
|
|
2733
|
+
chunk = '';
|
|
2734
|
+
separator = nextSeparator;
|
|
2735
|
+
};
|
|
2736
|
+
for (let index = 0; index < results.length; index++) {
|
|
2737
|
+
const result = results[index] ?? '';
|
|
2738
|
+
if (!resultTags[index]) {
|
|
2739
|
+
chunk += result;
|
|
2740
|
+
} else if (markers.length && markers.some(marker => result.includes(marker))) {
|
|
2741
|
+
// Whitespace next to a fragment stays as is, as it may belong to it
|
|
2742
|
+
if (!chunk && separator !== null) {
|
|
2743
|
+
chunk = separator;
|
|
2744
|
+
separator = null;
|
|
2745
|
+
}
|
|
2746
|
+
chunk += result;
|
|
2747
|
+
} else if (result.charCodeAt(result.length - 1) === 32 /* space */) {
|
|
2748
|
+
chunk += result.slice(0, -1);
|
|
2749
|
+
flush(' ');
|
|
2750
|
+
} else if (result.charCodeAt(result.length - 1) === 62 /* > */ &&
|
|
2751
|
+
result.charCodeAt(result.length - 2) !== 47 /* / */ &&
|
|
2752
|
+
!(noNewlinesBeforeTagClose && result.startsWith('</'))) {
|
|
2753
|
+
chunk += result.slice(0, -1);
|
|
2754
|
+
flush('');
|
|
2755
|
+
chunk = '>';
|
|
2756
|
+
} else {
|
|
2757
|
+
chunk += result;
|
|
2037
2758
|
}
|
|
2038
2759
|
}
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
}
|
|
2042
|
-
str = lines.join('\n');
|
|
2760
|
+
flush(null);
|
|
2761
|
+
str = lines.join('');
|
|
2043
2762
|
} else {
|
|
2044
2763
|
str = restoreIgnore(restoreCustom(results.join('')));
|
|
2045
2764
|
}
|
|
@@ -2053,16 +2772,14 @@ function joinResultSegments(results, options, restoreCustom, restoreIgnore) {
|
|
|
2053
2772
|
* - Caches are created on the first `minify()` call and persist for the lifetime of the process
|
|
2054
2773
|
* - Cache sizes are locked after first initialization—subsequent calls use the same caches
|
|
2055
2774
|
* even if different `cacheCSS`/`cacheJS`/`cacheSVG` options are provided
|
|
2056
|
-
* - The first call’s options determine the cache sizes for subsequent calls
|
|
2057
2775
|
* - Invalid values (NaN, Infinity, negative) fall back to the default size (500)
|
|
2058
2776
|
*/
|
|
2059
2777
|
/** @param {MinifierOptions} options */
|
|
2060
2778
|
function initCaches(options) {
|
|
2061
|
-
// Only create caches once (on first call)—sizes are locked after this
|
|
2062
2779
|
if (!cssMinifyCache) {
|
|
2063
2780
|
const defaultSize = 500;
|
|
2064
2781
|
|
|
2065
|
-
//
|
|
2782
|
+
// Parses an env var size (0 allowed); undefined when absent, invalid, or negative
|
|
2066
2783
|
const parseEnvCacheSize = (/** @type {string | undefined} */ envVar) => {
|
|
2067
2784
|
if (envVar === undefined) return undefined;
|
|
2068
2785
|
const parsed = Number(envVar);
|
|
@@ -2076,7 +2793,7 @@ function initCaches(options) {
|
|
|
2076
2793
|
// environment variables above
|
|
2077
2794
|
const sanitizeSize = (/** @type {number} */ size) => Number.isFinite(size) && size >= 0 ? Math.floor(size) : defaultSize;
|
|
2078
2795
|
|
|
2079
|
-
//
|
|
2796
|
+
// Precedence: Options > env > default
|
|
2080
2797
|
const cssSize = options.cacheCSS !== undefined ? options.cacheCSS
|
|
2081
2798
|
: (parseEnvCacheSize(process.env.HMN_CACHE_CSS) ?? defaultSize);
|
|
2082
2799
|
const jsSize = options.cacheJS !== undefined ? options.cacheJS
|
|
@@ -2113,14 +2830,11 @@ export function getCacheStats() {
|
|
|
2113
2830
|
};
|
|
2114
2831
|
}
|
|
2115
2832
|
|
|
2116
|
-
// Memoized options processing: Batch runs
|
|
2117
|
-
//
|
|
2118
|
-
//
|
|
2119
|
-
//
|
|
2120
|
-
//
|
|
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.
|
|
2833
|
+
// Memoized options processing: Batch runs pass one options object to many `minify()` calls, and
|
|
2834
|
+
// processing it (regex parsing, closures, option signatures) is expensive. The cache is keyed on
|
|
2835
|
+
// the object and checked against a deep snapshot, so mutating a reused object, nested values
|
|
2836
|
+
// included, still triggers reprocessing. Each call works on a shallow copy, as `minifyHTML`
|
|
2837
|
+
// reassigns top-level keys (wrapped minifiers, sorters, UID comment patterns) per call.
|
|
2124
2838
|
/** @type {MinifierOptions} */
|
|
2125
2839
|
const EMPTY_OPTIONS = {};
|
|
2126
2840
|
/** @type {WeakMap<object, {snapshot: unknown, processed: ProcessedOptions}>} */
|
|
@@ -2128,8 +2842,7 @@ const processedOptionsCache = new WeakMap();
|
|
|
2128
2842
|
|
|
2129
2843
|
// A “plain” value is an array or plain object, which the snapshot copies and
|
|
2130
2844
|
// compares structurally; anything else (functions, RegExps, class instances)
|
|
2131
|
-
// is kept and compared by identity—a false mismatch merely reprocesses
|
|
2132
|
-
// is the pre-memoization behavior
|
|
2845
|
+
// is kept and compared by identity—a false mismatch merely reprocesses
|
|
2133
2846
|
/** @param {unknown} value */
|
|
2134
2847
|
function isPlainValue(value) {
|
|
2135
2848
|
if (Array.isArray(value)) return true;
|
|
@@ -2212,7 +2925,6 @@ export const minify = async function (value, options) {
|
|
|
2212
2925
|
|
|
2213
2926
|
const inputOptions = options || EMPTY_OPTIONS;
|
|
2214
2927
|
|
|
2215
|
-
// Initialize caches on first use with configurable sizes
|
|
2216
2928
|
const caches = initCaches(inputOptions);
|
|
2217
2929
|
|
|
2218
2930
|
// WeakMap keys must be objects
|
|
@@ -2245,40 +2957,39 @@ export const minify = async function (value, options) {
|
|
|
2245
2957
|
}
|
|
2246
2958
|
}
|
|
2247
2959
|
}
|
|
2248
|
-
// Work on a shallow copy so per-call reassignments don’t reach the cached base
|
|
2249
|
-
const processedOptions = /** @type {ProcessedOptions} */ ({ ...processedBase });
|
|
2250
|
-
|
|
2251
2960
|
// Warnings are deduplicated per document, so the state has to live on the per-call
|
|
2252
2961
|
// copy; the `minifyCSS` closure hangs off the memoized base, shared across calls
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
//
|
|
2256
|
-
|
|
2257
|
-
//
|
|
2258
|
-
//
|
|
2962
|
+
/** @type {NonNullable<ProcessedOptions['cssContext']>} */
|
|
2963
|
+
const cssContext = { warned: new Set() };
|
|
2964
|
+
// What the parse finds out about the document for post-processing, sparing an output scan
|
|
2965
|
+
const documentState = { hasMathML: false };
|
|
2966
|
+
// Work on a shallow copy so per-call reassignments don’t reach the cached base. The
|
|
2967
|
+
// per-document state is part of the copy from the start, as properties added to it
|
|
2968
|
+
// later slow down every option lookup.
|
|
2969
|
+
const processedOptions = /** @type {ProcessedOptions} */ ({ ...processedBase, cssContext, documentState });
|
|
2970
|
+
|
|
2971
|
+
// Unused-CSS removal needs the whole document’s symbols before the first `style` element is
|
|
2972
|
+
// minified, so they are collected upfront from the raw input—where there is a style sheet at all
|
|
2259
2973
|
if (processedOptions.removeUnusedCSS && RE_STYLE_ELEMENT.test(value)) {
|
|
2260
|
-
|
|
2974
|
+
Object.assign(cssContext, collectUsage(
|
|
2261
2975
|
value,
|
|
2262
2976
|
processedOptions.removeUnusedCSS.scripts,
|
|
2263
2977
|
value.indexOf('&') !== -1
|
|
2264
2978
|
? /** @type {(text: string) => string} */ (await getDecodeHTML())
|
|
2265
2979
|
: undefined
|
|
2266
|
-
);
|
|
2980
|
+
));
|
|
2267
2981
|
}
|
|
2268
2982
|
|
|
2269
2983
|
let result = await minifyHTML(value, processedOptions);
|
|
2270
2984
|
|
|
2271
|
-
// Post-processing: Merge consecutive inline scripts if enabled
|
|
2272
2985
|
if (processedOptions.mergeScripts) {
|
|
2273
|
-
result = mergeConsecutiveScripts(result);
|
|
2986
|
+
result = mergeConsecutiveScripts(result, documentState.hasMathML);
|
|
2274
2987
|
}
|
|
2275
2988
|
|
|
2276
2989
|
processedOptions.log('minified in: ' + (Date.now() - start) + 'ms');
|
|
2277
2990
|
return result;
|
|
2278
2991
|
};
|
|
2279
2992
|
|
|
2280
|
-
// Exports
|
|
2281
|
-
|
|
2282
2993
|
export {
|
|
2283
2994
|
presets,
|
|
2284
2995
|
getPreset,
|