Skip to content

Commit 2e999c1

Browse files
authored
fix(html): minify by what a value decodes to, and close the tags that print (#22110)
* fix(html): rewrite a value the source spelled with character references The rewrites ran on the source text, so a value carrying a reference was skipped whole: `srcset` and `imagesrcset` kept their list whitespace, a viewport `content` its spaces, an enumerated value its case, a URL its padding. The grammars read what the value decodes to, which the printer already had for spelling it back, so the rewrite runs on that. `style` keeps its own decoded path. 91 findings to 59 in the sweep. * fix(html): read a boolean attribute's presence decoded too `checked="checked"` is the bare name; `checked="&#x63;&#x68;&#x65;&#x63;&#x6b;&#x65;&#x64;"` spells the same presence and was kept whole. The decode already ran a few lines below for spelling the value back, so it moves ahead of this check — still guarded on the `&`, so a value without one pays nothing. * fix(html): close a held-back start tag the printer ended up writing An implied `<html>` / `<body>` prints in pieces: its start tag is held back and settled only once the first piece turns out to open with whitespace, but its end tag was decided before that, as the transparent element's. So a page whose body starts with whitespace printed `<body>` with no `</body>`, and a second pass added one. Both closes are worked out up front and the one that matches the tag actually written is emitted. * fix(html): write a rewritten value the quoting switch cannot spell `normalizeAttributeQuotes: false` freezes the quoting, and `_writeAttribute` answers nothing when neither the minimal nor the bare spelling is open to it — so a referenced value the rewrite had changed fell back to the source and kept its entity spelling. It is escaped and quoted instead, since the value it holds is not what the switch froze.
1 parent 2329658 commit 2e999c1

14 files changed

Lines changed: 208 additions & 20 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Rewrite an attribute value the source spelled with character references.

‎.gitattributes‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ test/configCases/html/minimize-transforms/** eol=lf
3232
test/configCases/html/minimize-round-trip/** eol=lf
3333
test/configCases/html/minimize-shell-end-tags/** eol=lf
3434
test/configCases/html/minimize-lookup-decoded-value/** eol=lf
35+
test/configCases/html/minimize-rewrite-referenced-value/** eol=lf
3536
test/configCases/performance/unused-reexports/** eol=lf
3637
test/configCases/performance/unused-reexports-error/** eol=lf
3738
examples/* eol=lf

‎lib/html/syntax.js‎

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11248,8 +11248,8 @@ const _minifyOpenTag = (path, open) => {
1124811248
// `style`, and a bare value is already the shortest spelling of itself.
1124911249
if (quoted || html || attributeName === "style" || rawValue.includes("&")) {
1125011250
const hasReference = rawValue.includes("&");
11251-
// A character reference would decode to something these grammars read
11252-
// differently, so only a reference-free value is rewritten.
11251+
// Rewritten from the source text where it carries no reference; one that
11252+
// does is rewritten from what it decodes to, below.
1125311253
let value = rawValue;
1125411254
if (!hasReference) {
1125511255
if (html) {
@@ -11275,31 +11275,46 @@ const _minifyOpenTag = (path, open) => {
1127511275
// Both spellings are the same empty presence, and writing either as the
1127611276
// bare name is the `=""` going — a quoting decision, so it answers to
1127711277
// the switch that names the rest of them.
11278+
// Guarded on the reference, so the decode stays off the hot path — and
11279+
// tried before unquoting, which keeps every reference it writes bare.
11280+
const decoded = hasReference ? decodeEntities(rawValue, true) : null;
11281+
// A reference spelling whitespace is deliberate: writing it out would
11282+
// let `removeEmptyAttributes` read the attribute as empty on a re-run.
11283+
const spellable =
11284+
decoded !== null &&
11285+
(_asciiTrim(decoded) !== "" || _asciiTrim(rawValue) === "")
11286+
? decoded
11287+
: null;
11288+
// The name the presence is spelled with is what it decodes to, so
11289+
// `checked="&#x63;…"` is the same presence as `checked="checked"`.
11290+
const presence = spellable !== null ? spellable : rawValue;
1127811291
if (
1127911292
_transforms.normalizeAttributeQuotes &&
1128011293
(value === "" ||
1128111294
(html &&
1128211295
_transforms.collapseBooleanAttributes &&
1128311296
(_transforms.collapseBooleanAttributes === "all" ||
11284-
(rawValue.length === attributeName.length &&
11285-
_asciiLowerCase(rawValue) === attributeName)) &&
11297+
(presence.length === attributeName.length &&
11298+
_asciiLowerCase(presence) === attributeName)) &&
1128611299
_isBooleanAttribute(elementName, attributeName)))
1128711300
) {
1128811301
out += ` ${attributeName}`;
1128911302
unquotedTail = false;
1129011303
consumedEnd = valueEnd;
1129111304
continue;
1129211305
}
11293-
// Guarded on the reference, so the decode stays off the hot path — and
11294-
// tried before unquoting, which keeps every reference it writes bare.
11295-
const decoded = hasReference ? decodeEntities(rawValue, true) : null;
11296-
// A reference spelling whitespace is deliberate: writing it out would
11297-
// let `removeEmptyAttributes` read the attribute as empty on a re-run.
11298-
const spellable =
11299-
decoded !== null &&
11300-
(_asciiTrim(decoded) !== "" || _asciiTrim(rawValue) === "")
11301-
? decoded
11302-
: null;
11306+
// The grammars read what the value decodes to, so a referenced one is
11307+
// rewritten from that and spelled back. `style` has its own path below.
11308+
const rewritten =
11309+
spellable !== null && html && attributeName !== "style"
11310+
? _rewriteAttributeValue(
11311+
elementName,
11312+
attributeName,
11313+
spellable,
11314+
isViewportMeta,
11315+
enumeratedOn
11316+
)
11317+
: spellable;
1130311318
const isStyle = attributeName === "style";
1130411319
// A `style=""` carrying a character reference is a declaration list like
1130511320
// any other once decoded — `&quot;` is a quote to CSS, not an entity — so
@@ -11322,7 +11337,7 @@ const _minifyOpenTag = (path, open) => {
1132211337
);
1132311338
const written = isStyle
1132411339
? writeStyle(declarations !== null ? declarations : value)
11325-
: _writeAttribute(attributeName, value, rawValue, spellable, quoted);
11340+
: _writeAttribute(attributeName, value, rawValue, rewritten, quoted);
1132611341
// The JavaScript an event handler holds, offered decoded — `&amp;&amp;`
1132711342
// is an operator to JavaScript rather than an entity. No built-in.
1132811343
const handler =
@@ -11446,6 +11461,14 @@ const _minifyOpenTag = (path, open) => {
1144611461
consumedEnd = valueEnd;
1144711462
continue;
1144811463
}
11464+
// Quoting may be frozen, but a rewrite changed what the value says, so
11465+
// the source's own spelling of it cannot stand.
11466+
if (rewritten !== null && rewritten !== spellable) {
11467+
out += ` ${attributeName}="${escapeAttribute(rewritten, CC_QUOTATION_MARK, true)}"`;
11468+
unquotedTail = false;
11469+
consumedEnd = valueEnd;
11470+
continue;
11471+
}
1144911472
}
1145011473
// A quoted value carries its quotes over; an unquoted one starts at the
1145111474
// value itself.
@@ -11602,6 +11625,13 @@ const _contentOpensOutside = (node) => {
1160211625
// so each streamed element costs no result object.
1160311626
let _streamOpen = "";
1160411627
let _streamClose = "";
11628+
// The close that goes with a held-back start tag once it prints: an element
11629+
// whose tag the parser no longer re-implies answers to `removeImpliedTags`.
11630+
let _streamCloseIfOpened = "";
11631+
// Which held-back opener `_emitPiece` settled into a start tag, `-1` for none.
11632+
let _materializedPendingSlot = -1;
11633+
/** @type {string[]} */
11634+
const _printCloseIfOpened = [];
1160511635
let _streamImplied = "";
1160611636

1160711637
/**
@@ -11673,6 +11703,9 @@ const _streamTags = (path, minify) => {
1167311703
// The parser re-implies the start tag, but not the end tag the source
1167411704
// carried: without it whatever follows moves inside this element.
1167511705
_streamClose = _impliedCloseTag(path, name, path.node);
11706+
_streamCloseIfOpened = _canOmitEndTag(path, name, path.node)
11707+
? ""
11708+
: `</${name}>`;
1167611709
// Leading whitespace is decided on the first piece emitted; what the modes
1167711710
// hand back out is known here, from the node itself.
1167811711
const shell = name === "body" || name === "html";
@@ -12636,6 +12669,7 @@ const _emitPiece = (text) => {
1263612669
const c = text.charCodeAt(0);
1263712670
if (c === 0x09 || c === 0x0a || c === 0x0c || c === 0x0d || c === 0x20) {
1263812671
w.setPending(held - 1, `<${_printPendingNames[held - 1]}>`);
12672+
_materializedPendingSlot = held - 1;
1263912673
}
1264012674
_printPendingNames.length = 0;
1264112675
w.flushPending();
@@ -12673,6 +12707,7 @@ const _openStreamed = (node, depth, descending) => {
1267312707
if (_streamImplied === "") {
1267412708
_emitPiece(_streamOpen);
1267512709
} else {
12710+
_printCloseIfOpened[depth] = _streamCloseIfOpened;
1267612711
_printPendingSlot[depth] = w.pushPending("");
1267712712
_printPendingNames.push(_streamImplied);
1267812713
}
@@ -12725,8 +12760,14 @@ const _exitNode = (node) => {
1272512760
if (_printOpen[depth] === 1) {
1272612761
// Printed in pieces: its opener went out as it opened and its children as
1272712762
// they finished, so only its closer is left.
12728-
_emitPiece(_printClose[depth]);
1272912763
const slot = _printPendingSlot[depth];
12764+
// Its start tag printed after all, so the end tag is no longer the one a
12765+
// transparent element leaves behind.
12766+
_emitPiece(
12767+
slot !== -1 && slot === _materializedPendingSlot
12768+
? _printCloseIfOpened[depth]
12769+
: _printClose[depth]
12770+
);
1273012771
// Nothing inside it printed, so its held-back opener never had to.
1273112772
if (slot !== -1 && _writer.isPending(slot)) {
1273212773
_printPendingNames.pop();
@@ -13192,6 +13233,8 @@ const grammar = (input, visitors, writer, options) => {
1319213233
_printClose.length = 0;
1319313234
_printPendingNames.length = 0;
1319413235
_printPendingSlot.length = 0;
13236+
_printCloseIfOpened.length = 0;
13237+
_materializedPendingSlot = -1;
1319513238
// Hoisting these to module scope outlives the call, so drop the caller's
1319613239
// visitors and print context here — they used to fall away with `grammar`.
1319713240
_visitors = EMPTY_VISITORS;

‎test/HtmlSyntax.unittest.js‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5430,6 +5430,24 @@ describe("SourceProcessor — attribute quote spelling", () => {
54305430
);
54315431
});
54325432

5433+
it("rewrites a referenced value with the quoting switch off", () => {
5434+
// The switch freezes the quoting, not the value: a rewrite that changes
5435+
// what the value says leaves the source spelling of it unusable.
5436+
const frozen = (/** @type {string} */ html) =>
5437+
new SourceProcessor().process(html, {
5438+
mode: "minify",
5439+
transforms: { normalizeAttributeQuotes: false }
5440+
}).code;
5441+
expect(frozen('<a href="&#x20;/a&#x20;">y</a>')).toContain('href="/a"');
5442+
expect(frozen('<input type="&#x54;&#x45;&#x58;&#x54;">')).toContain(
5443+
'type="text"'
5444+
);
5445+
// The `&` a decoded URL holds is escaped back, not written out bare.
5446+
expect(frozen('<a href="&#x20;/a?x=1&amp;y=2&#x20;">y</a>')).toContain(
5447+
'href="/a?x=1&amp;y=2"'
5448+
);
5449+
});
5450+
54335451
it("writes a reference the parser cannot read back as one", () => {
54345452
// `<` and `>` mean nothing inside a quoted value, and an `&` no reference
54355453
// can start after it is data — but one that could start a reference stays.
@@ -8241,9 +8259,9 @@ describe("SourceProcessor — minify serialization edge cases", () => {
82418259
// before `<body>` starts, the insertion modes ignore whitespace.
82428260
// The shell end tag the source spelled stays: `removeImpliedTags`
82438261
// leaves out only the `<html>` start tag outside `"all"`.
8244-
expect(minify("</html> foo")).toBe("<body> foo</html>");
8262+
expect(minify("</html> foo")).toBe("<body> foo</body></html>");
82458263
expect(minify("</body> foo")).toBe("<body> foo</body>");
8246-
expect(minify("<colgroup> foo")).toBe("<body> foo");
8264+
expect(minify("<colgroup> foo")).toBe("<body> foo</body>");
82478265
// Nothing to keep when the run is not in the body to begin with.
82488266
expect(minify(" foo")).toBe("foo");
82498267
expect(minify("<p>x</p>")).toBe("<p>x");

‎test/configCases/html/attribute-tables/__snapshots__/ConfigCacheTest.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ exports[`ConfigCacheTestCases html attribute-tables attribute-tables should comp
55
<form action=/post autocomplete=on>
66
<input type=text autocapitalize=sentences autocomplete=EMAIL enterkeyhint=go inputmode=numeric spellcheck=true maxlength=10 minlength=2 autofocus>
77
<textarea writingsuggestions=false maxlength=100>text</textarea>
8-
<button formaction=\\" /submit?a=1&amp;b=2 \\" formenctype=multipart/form-data formmethod=post formnovalidate>send</button>
8+
<button formaction=\\"/submit?a=1&amp;b=2\\" formenctype=multipart/form-data formmethod=post formnovalidate>send</button>
99
</form>
1010
<img src=data:, alt=a decoding=async ismap>
1111
<p draggable=true accesskey=\\"s s\\" itemref=\\"one two\\">draggable</p>

‎test/configCases/html/attribute-tables/__snapshots__/ConfigTest.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ exports[`ConfigTestCases html attribute-tables attribute-tables should compile 1
55
<form action=/post autocomplete=on>
66
<input type=text autocapitalize=sentences autocomplete=EMAIL enterkeyhint=go inputmode=numeric spellcheck=true maxlength=10 minlength=2 autofocus>
77
<textarea writingsuggestions=false maxlength=100>text</textarea>
8-
<button formaction=\\" /submit?a=1&amp;b=2 \\" formenctype=multipart/form-data formmethod=post formnovalidate>send</button>
8+
<button formaction=\\"/submit?a=1&amp;b=2\\" formenctype=multipart/form-data formmethod=post formnovalidate>send</button>
99
</form>
1010
<img src=data:, alt=a decoding=async ismap>
1111
<p draggable=true accesskey=\\"s s\\" itemref=\\"one two\\">draggable</p>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases html minimize-rewrite-referenced-value minimize-rewrite-referenced-value should compile 1`] = `
4+
"<!doctype html><head><meta name=viewport content=\\"width=device-width,initial-scale=1\\"><link rel=preload as=image imagesrcset=\\"51b834b7c1ef0b59ea50.png 1x,51b834b7c1ef0b59ea50.png 2x\\"></head><body>
5+
<img src=51b834b7c1ef0b59ea50.png alt=x srcset=\\"51b834b7c1ef0b59ea50.png 200w,51b834b7c1ef0b59ea50.png 400w\\">
6+
<input type=text>
7+
<input type=checkbox checked>
8+
<option selected>o</option>
9+
<a href=./a.png>padded url</a>
10+
11+
12+
</body></html>"
13+
`;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigTestCases html minimize-rewrite-referenced-value minimize-rewrite-referenced-value should compile 1`] = `
4+
"<!doctype html><head><meta name=viewport content=\\"width=device-width,initial-scale=1\\"><link rel=preload as=image imagesrcset=\\"51b834b7c1ef0b59ea50.png 1x,51b834b7c1ef0b59ea50.png 2x\\"></head><body>
5+
<img src=51b834b7c1ef0b59ea50.png alt=x srcset=\\"51b834b7c1ef0b59ea50.png 200w,51b834b7c1ef0b59ea50.png 400w\\">
6+
<input type=text>
7+
<input type=checkbox checked>
8+
<option selected>o</option>
9+
<a href=./a.png>padded url</a>
10+
11+
12+
</body></html>"
13+
`;
Lines changed: 1 addition & 0 deletions
Loading
Lines changed: 1 addition & 0 deletions
Loading

0 commit comments

Comments
 (0)