Skip to content

Commit a104074

Browse files
feat(html): minify the script an event handler attribute holds (#21968)
* feat(html): minify the script an event handler attribute holds Every event handler content attribute — `onclick` and its 93 siblings — is offered to `renderEmbeddedSource` as JavaScript, with `as: "event-handler"` saying it is a function body rather than a script, the way a `style=""` is offered as a block's contents rather than a whole sheet. The answer is written back escaped for the delimiter it lands in, and only where it spells shorter than the source does. `htmlMinify` spends that production, since a JavaScript minifier takes whole scripts and no `as`: the function the body belongs to goes out and the body of the one answered comes back. So a `return` — what an author writes to cancel an event — is minified in the production it is in, rather than skipped for failing to parse as a script. The handler table is derived from webref's HTML IDL alongside the other reflected-attribute tables, so which names are handlers on which elements is generated rather than listed. * test(html): shorten the handler fixture's comment to two lines
1 parent efd9ff2 commit a104074

15 files changed

Lines changed: 764 additions & 106 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Minify the script an event handler attribute holds when minifying HTML.

‎lib/html/data.js‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"use strict";
77

88
// GENERATED by tooling/generate-html-data.js — do not edit.
9-
// cspell:ignore advasoft altglyph altglyphdef altglyphitem animatecolor animatemotion animatetransform arcrole aswedit attributename attributetype basefrequency baseprofile bgsound calcmode clippathunits contenteditable diffuseconstant enterkeyhint fedropshadow filterunits formenctype formmethod formtarget glyphref gradienttransform gradientunits hotjava hotmetal inputmode jscript kernelmatrix kernelunitlength keypoints keysplines keytimes limitingconeangle livescript markerheight markerwidth maskcontentunits maskunits metrius mtext numoctaves pathlength patterncontentunits patterntransform patternunits pointsatx pointsaty pointsatz preservealpha primitiveunits refx refy repeatcount repeatdur requiredextensions requiredfeatures silmaril softquad specularconstant specularexponent startoffset stddeviation stitchtiles surfacescale systemlanguage tablevalues targetx targety textlength viewbox viewtarget webtechs writingsuggestions xchannelselector ychannelselector
9+
// cspell:ignore advasoft altglyph altglyphdef altglyphitem animatecolor animatemotion animatetransform arcrole aswedit attributename attributetype basefrequency baseprofile bgsound calcmode clippathunits contenteditable diffuseconstant enterkeyhint fedropshadow filterunits formenctype formmethod formtarget glyphref gradienttransform gradientunits hotjava hotmetal inputmode jscript kernelmatrix kernelunitlength keypoints keysplines keytimes limitingconeangle livescript markerheight markerwidth maskcontentunits maskunits metrius mtext numoctaves pathlength patterncontentunits patterntransform patternunits pointsatx pointsaty pointsatz preservealpha primitiveunits refx refy repeatcount repeatdur requiredextensions requiredfeatures silmaril softquad specularconstant specularexponent startoffset stddeviation stitchtiles surfacescale systemlanguage tablevalues targetx targety textlength viewbox viewtarget webtechs writingsuggestions xchannelselector ychannelselector onabort onafterprint onauxclick onbeforeinput onbeforematch onbeforeprint onbeforetoggle onbeforeunload onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncommand oncontextlost oncontextmenu oncontextrestored oncopy oncuechange oncut ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus onformdata onhashchange oninput oninvalid onkeydown onkeypress onkeyup onlanguagechange onload onloadeddata onloadedmetadata onloadstart onmessage onmessageerror onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onoffline ononline onpagehide onpagereveal onpageshow onpageswap onpaste onpause onplay onplaying onpopstate onprogress onratechange onrejectionhandled onreset onresize onscroll onscrollend onsecuritypolicyviolation onseeked onseeking onselect onslotchange onstalled onstorage onsubmit onsuspend ontimeupdate ontoggle onunhandledrejection onunload onvolumechange onwaiting onwebkitanimationend onwebkitanimationiteration onwebkitanimationstart onwebkittransitionend onwheel
1010
// Reflected-attribute tables from webref's extraction of the HTML IDL (see tooling/generate-html-data.js); everything else is the
1111
// generator's SUPPLEMENT, which carries the spec facts no dataset states.
1212

@@ -524,6 +524,110 @@ const SIGNED_INTEGER_ATTRIBUTES = new Set(["start", "tabindex", "value"]);
524524
*/
525525
const COMMA_LIST_ATTRIBUTES = new Set(["accept", "coords", "sizes"]);
526526

527+
/**
528+
* Event handler content attributes, mapped to the elements each is one on
529+
* (`null` = a global attribute). Elsewhere the same name is an ordinary
530+
* attribute holding text — `onunload` is a handler on `<body>` and data on a
531+
* `<div>` — so the value is only read as JavaScript where the table says it is.
532+
* @type {Map<string, Set<string> | null>}
533+
*/
534+
const EVENT_HANDLER_ATTRIBUTES = new Map([
535+
["onabort", null],
536+
["onafterprint", new Set(["body"])],
537+
["onauxclick", null],
538+
["onbeforeinput", null],
539+
["onbeforematch", null],
540+
["onbeforeprint", new Set(["body"])],
541+
["onbeforetoggle", null],
542+
["onbeforeunload", new Set(["body"])],
543+
["onblur", null],
544+
["oncancel", null],
545+
["oncanplay", null],
546+
["oncanplaythrough", null],
547+
["onchange", null],
548+
["onclick", null],
549+
["onclose", null],
550+
["oncommand", null],
551+
["oncontextlost", null],
552+
["oncontextmenu", null],
553+
["oncontextrestored", null],
554+
["oncopy", null],
555+
["oncuechange", null],
556+
["oncut", null],
557+
["ondblclick", null],
558+
["ondrag", null],
559+
["ondragend", null],
560+
["ondragenter", null],
561+
["ondragleave", null],
562+
["ondragover", null],
563+
["ondragstart", null],
564+
["ondrop", null],
565+
["ondurationchange", null],
566+
["onemptied", null],
567+
["onended", null],
568+
["onerror", null],
569+
["onfocus", null],
570+
["onformdata", null],
571+
["onhashchange", new Set(["body"])],
572+
["oninput", null],
573+
["oninvalid", null],
574+
["onkeydown", null],
575+
["onkeypress", null],
576+
["onkeyup", null],
577+
["onlanguagechange", new Set(["body"])],
578+
["onload", null],
579+
["onloadeddata", null],
580+
["onloadedmetadata", null],
581+
["onloadstart", null],
582+
["onmessage", new Set(["body"])],
583+
["onmessageerror", new Set(["body"])],
584+
["onmousedown", null],
585+
["onmouseenter", null],
586+
["onmouseleave", null],
587+
["onmousemove", null],
588+
["onmouseout", null],
589+
["onmouseover", null],
590+
["onmouseup", null],
591+
["onoffline", new Set(["body"])],
592+
["ononline", new Set(["body"])],
593+
["onpagehide", new Set(["body"])],
594+
["onpagereveal", new Set(["body"])],
595+
["onpageshow", new Set(["body"])],
596+
["onpageswap", new Set(["body"])],
597+
["onpaste", null],
598+
["onpause", null],
599+
["onplay", null],
600+
["onplaying", null],
601+
["onpopstate", new Set(["body"])],
602+
["onprogress", null],
603+
["onratechange", null],
604+
["onrejectionhandled", new Set(["body"])],
605+
["onreset", null],
606+
["onresize", null],
607+
["onscroll", null],
608+
["onscrollend", null],
609+
["onsecuritypolicyviolation", null],
610+
["onseeked", null],
611+
["onseeking", null],
612+
["onselect", null],
613+
["onslotchange", null],
614+
["onstalled", null],
615+
["onstorage", new Set(["body"])],
616+
["onsubmit", null],
617+
["onsuspend", null],
618+
["ontimeupdate", null],
619+
["ontoggle", null],
620+
["onunhandledrejection", new Set(["body"])],
621+
["onunload", new Set(["body"])],
622+
["onvolumechange", null],
623+
["onwaiting", null],
624+
["onwebkitanimationend", null],
625+
["onwebkitanimationiteration", null],
626+
["onwebkitanimationstart", null],
627+
["onwebkittransitionend", null],
628+
["onwheel", null]
629+
]);
630+
527631
/**
528632
* §13.1.2 void elements: no end tag, and no children to close one over.
529633
* @type {Set<string>}
@@ -1863,6 +1967,7 @@ module.exports.EMPTY_METADATA_ELEMENTS = EMPTY_METADATA_ELEMENTS;
18631967
module.exports.EMPTY_REMOVABLE_ATTRIBUTES = EMPTY_REMOVABLE_ATTRIBUTES;
18641968
module.exports.ENUMERATED_ATTRIBUTE_NAMES = ENUMERATED_ATTRIBUTE_NAMES;
18651969
module.exports.ENUMERATED_KEYWORDS = ENUMERATED_KEYWORDS;
1970+
module.exports.EVENT_HANDLER_ATTRIBUTES = EVENT_HANDLER_ATTRIBUTES;
18661971
module.exports.FONT_BREAKOUT_ATTRS = FONT_BREAKOUT_ATTRS;
18671972
module.exports.FOREIGN_ATTR_NS = FOREIGN_ATTR_NS;
18681973
module.exports.FOREIGN_BREAKOUT = FOREIGN_BREAKOUT;

‎lib/html/htmlMinify.js‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
4949
askEmbeddedRenderer,
5050
collectEmbeddedDiagnostics,
5151
embeddedText,
52+
EVENT_HANDLER,
5253
SourceProcessor,
5354
NodeType,
5455
pickTransforms
@@ -96,6 +97,40 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
9697
sortTokenLists,
9798
removeImpliedTags
9899
};
100+
/**
101+
* The function an event handler's body belongs to. Named past any run of `_`
102+
* the body holds, so nothing in it resolves to the function instead of what it
103+
* meant; the newline ends a line comment the body may close with.
104+
* @param {string} body the handler's text
105+
* @returns {string} the script it is the body of
106+
*/
107+
const asFunction = (body) => {
108+
let longest = 0;
109+
let run = 0;
110+
111+
for (let i = 0; i < body.length; i++) {
112+
run = body.charCodeAt(i) === 95 ? run + 1 : 0;
113+
if (run > longest) longest = run;
114+
}
115+
116+
return `function ${"_".repeat(longest + 1)}(){${body}\n}`;
117+
};
118+
/**
119+
* The handler body inside the function a renderer answered with. `undefined`
120+
* for an answer that is not that function — one holding anything else, or one
121+
* that dropped it whole as the unused declaration it is.
122+
* @param {string} answered what the renderer answered
123+
* @returns {string | undefined} the body, or undefined
124+
*/
125+
const handlerBody = (answered) => {
126+
const opened = answered.indexOf("{");
127+
128+
return opened !== -1 &&
129+
answered.endsWith("}") &&
130+
/^function\s+[^\s(]+\s*\(\s*\)\s*$/.test(answered.slice(0, opened))
131+
? answered.slice(opened + 1, -1).trim()
132+
: undefined;
133+
};
99134
// Handed each body the print offers, with what it reported kept: how the
100135
// element or attribute around one is written is decided from the answer, and
101136
// a body declined or thrown on is spelled as an untapped run spells it.
@@ -106,11 +141,23 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
106141
/** @type {EXPECTED_ANY} */ hole
107142
) => {
108143
if (renderEmbeddedSource !== undefined) {
144+
// A JavaScript minifier is handed whole scripts and takes no `as`, so
145+
// the function the body belongs to goes out and its body comes back.
146+
const handler =
147+
hole.type === "javascript" && hole.as === EVENT_HANDLER
148+
? { ...hole, source: asFunction(source), as: undefined }
149+
: null;
109150
const answered = embeddedText(
110-
await askEmbeddedRenderer(renderEmbeddedSource, hole, reported)
151+
await askEmbeddedRenderer(
152+
renderEmbeddedSource,
153+
handler === null ? hole : handler,
154+
reported
155+
)
111156
);
112157

113-
if (typeof answered === "string") return answered;
158+
if (typeof answered === "string") {
159+
return handler === null ? answered : handlerBody(answered);
160+
}
114161
}
115162

116163
// A nested document is a document, so it is minified the same way. The
@@ -211,7 +258,8 @@ htmlMinify.getTypes = () => ["html"];
211258

212259
/**
213260
* The languages this can offer a caller through `renderEmbeddedSource` — an
214-
* inline `<style>`, a `<script>`, an `<svg>` subtree and the document an
261+
* inline `<style>`, a `<script>`, every event handler attribute (as the whole
262+
* script its body belongs to), an `<svg>` subtree and the document an
215263
* `<iframe srcdoc>` holds. A `style=""` is not among them: how the attribute is
216264
* written is decided by reading the minified text back, so it stays with the
217265
* built-in CSS minifier, which is webpack's own `cssMinify`.

‎lib/html/syntax.js‎

Lines changed: 110 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ const { deferredWrite, declineDeferredWrites } = GenericSourceProcessor;
2020
/**
2121
* Renders one nested body this document embeds — an inline `<style>`, every
2222
* `style=""` (handed over as a whole stylesheet), a `<script>` holding JSON or
23-
* JavaScript, an `<svg>` subtree, and the document an `<iframe srcdoc>` holds. Returning the input unchanged declines
23+
* JavaScript, every event handler attribute (`as` says it is a function body
24+
* rather than a script), an `<svg>` subtree, and the document an
25+
* `<iframe srcdoc>` holds. Returning the input unchanged declines
2426
* it. Synchronous: it is called from inside the print walk, so a caller with an
2527
* async minifier collects the bodies in a walk-only pass first and looks the
2628
* results up here.
@@ -47,6 +49,9 @@ const SVG_TYPE = "svg";
4749
// it is offered as CSS — with `as` saying which production it is, the same
4850
// vocabulary `module.parser.css.as` uses.
4951
const BLOCK_CONTENTS = "block-contents";
52+
// An `onclick=""` is that shape one language over: JavaScript, but a function
53+
// body — the production the `return` cancelling an event is written in.
54+
const EVENT_HANDLER = "event-handler";
5055

5156
const {
5257
askEmbeddedRenderer,
@@ -87,6 +92,7 @@ const {
8792
EMPTY_REMOVABLE_ATTRIBUTES,
8893
ENUMERATED_ATTRIBUTE_NAMES,
8994
ENUMERATED_KEYWORDS,
95+
EVENT_HANDLER_ATTRIBUTES,
9096
FONT_BREAKOUT_ATTRS,
9197
FOREIGN_ATTR_NS,
9298
FOREIGN_BREAKOUT,
@@ -8946,7 +8952,7 @@ const mirrorSelectedContent = (node, select) => {
89468952
* @property {(boolean | "smart" | "all")=} removeImpliedTags how much of the `<html>` / `<head>` / `<body>` shell §13.1.2.4 lets the parser imply may be left out: `"smart"` leaves out only the `<html>` start tag, `true` (or `"all"`) all six, `false` none (default `"smart"`)
89478953
* @property {boolean=} deferSrcdoc whether an `<iframe srcdoc>` is among what `deferEmbeddedSource` collects (default true); false for a caller that minifies them itself, which keeps the attribute on the normal path and its shorter delimiter
89488954
* @property {DeferredEmbeddedSource[]=} deferEmbeddedSource collects what `renderEmbeddedSource` would be offered instead of offering it, for a caller whose renderer is asynchronous: the print leaves a marker for each and `finish` puts the answers in their place, so one parse serves both. A `style=""` stays with the built-in CSS minifier, whose text this print reads back to decide how the attribute is written. Takes precedence over `renderEmbeddedSource`
8949-
* @property {EmbeddedSourceRenderer=} renderEmbeddedSource renders each nested body this document embeds — an inline `<style>`, every `style=""` (handed over as a whole stylesheet, SVG's and MathML's included), a `<script>` holding JSON or JavaScript, an `<svg>` subtree, and the document an `<iframe srcdoc>` holds (decoded, and written back escaped). Replaces the built-in CSS and JSON minifiers wherever it answers, and returning anything but text falls back to them; it is the only way inline JavaScript, SVG and a nested document are reached at all
8955+
* @property {EmbeddedSourceRenderer=} renderEmbeddedSource renders each nested body this document embeds — an inline `<style>`, every `style=""` (handed over as a whole stylesheet, SVG's and MathML's included), a `<script>` holding JSON or JavaScript, every event handler attribute, with `as: "event-handler"` saying it is a function body rather than a script — the production a `return` at its top level is in, which a renderer taking whole scripts has to wrap before it can read (webpack's own `htmlMinify` does) — an `<svg>` subtree, and the document an `<iframe srcdoc>` holds (decoded, and written back escaped). Replaces the built-in CSS and JSON minifiers wherever it answers, and returning anything but text falls back to them; it is the only way inline JavaScript, SVG and a nested document are reached at all
89508956
*/
89518957

89528958
/**
@@ -10177,6 +10183,20 @@ const _isBooleanAttribute = (tagName, name) => {
1017710183
return elements === null || elements.has(tagName);
1017810184
};
1017910185

10186+
/**
10187+
* Whether an attribute is an event handler on this element, so its value is
10188+
* JavaScript rather than text. `null` in the table means the attribute is a
10189+
* handler on every element.
10190+
* @param {string} tagName lowercased element name
10191+
* @param {string} name lowercased attribute name
10192+
* @returns {boolean} true when the value is a handler body
10193+
*/
10194+
const _isEventHandlerAttribute = (tagName, name) => {
10195+
const elements = EVENT_HANDLER_ATTRIBUTES.get(name);
10196+
if (elements === undefined) return false;
10197+
return elements === null || elements.has(tagName);
10198+
};
10199+
1018010200
/**
1018110201
* Whether a space-separated list names the same token twice, read span by span
1018210202
* so nothing is allocated. The lists are short — `class` is a handful of tokens
@@ -11083,6 +11103,84 @@ const _minifyOpenTag = (path, open) => {
1108311103
const written = isStyle
1108411104
? writeStyle(declarations !== null ? declarations : value)
1108511105
: _writeAttribute(attributeName, value, rawValue, spellable);
11106+
// The JavaScript an event handler holds, offered decoded — `&amp;&amp;`
11107+
// is an operator to JavaScript rather than an entity. No built-in.
11108+
const handler =
11109+
!isStyle &&
11110+
(_renderEmbeddedSource !== undefined ||
11111+
_deferEmbeddedSource !== undefined) &&
11112+
_isEventHandlerAttribute(elementName, attributeName)
11113+
? hasReference
11114+
? spellable
11115+
: rawValue
11116+
: null;
11117+
11118+
if (handler !== null && _asciiTrim(handler) !== "") {
11119+
const delimiter = open[valueStart - tagStart - 1];
11120+
// A foreign `/>` reads back whether this value ends unquoted, which a
11121+
// deferred answer is not there to decide: the source's quoting stands.
11122+
const holdQuoted = tailIsRead && _deferEmbeddedSource !== undefined;
11123+
// Declining leaves the attribute as an untapped run writes it, which is
11124+
// the source spelling wherever nothing shorter was found.
11125+
const asWritten =
11126+
written === null || holdQuoted
11127+
? ` ${attributeName}=${delimiter}${rawValue}${delimiter}`
11128+
: written.text;
11129+
const declinedTail =
11130+
!holdQuoted && written !== null && written.unquotedTail;
11131+
/**
11132+
* The answer is only written where it spells shorter than the source
11133+
* does: a minifier ends a statement it was handed without one, so a
11134+
* handler as short as `onclick="x"` comes back a byte longer.
11135+
* @param {string | null | undefined} rendered what the renderer answered
11136+
* @returns {{ text: string, unquotedTail: boolean } | null} what to emit, or null where nothing it answered is written
11137+
*/
11138+
const writeHandler = (rendered) => {
11139+
if (typeof rendered !== "string") return null;
11140+
11141+
// The answer is source text, so it is escaped for the delimiter it
11142+
// lands in — an `&` in it opens a reference where it is not.
11143+
const answered = holdQuoted
11144+
? {
11145+
text: _writeQuotedAttribute(attributeName, rendered, delimiter),
11146+
unquotedTail: false
11147+
}
11148+
: _writeAttribute(
11149+
attributeName,
11150+
escapeAttribute(rendered, CC_QUOTATION_MARK, true),
11151+
rawValue,
11152+
rendered
11153+
);
11154+
11155+
return answered !== null && answered.text.length < asWritten.length
11156+
? answered
11157+
: null;
11158+
};
11159+
11160+
if (_deferEmbeddedSource !== undefined) {
11161+
out += _deferEmbedded(
11162+
handler,
11163+
JAVASCRIPT_TYPE,
11164+
(rendered) => {
11165+
const answered = writeHandler(rendered);
11166+
11167+
return answered === null ? asWritten : answered.text;
11168+
},
11169+
EVENT_HANDLER
11170+
);
11171+
unquotedTail = declinedTail;
11172+
} else {
11173+
const answered = writeHandler(
11174+
_renderEmbeddedOrNull(handler, JAVASCRIPT_TYPE, EVENT_HANDLER)
11175+
);
11176+
11177+
out += answered === null ? asWritten : answered.text;
11178+
unquotedTail =
11179+
answered === null ? declinedTail : answered.unquotedTail;
11180+
}
11181+
consumedEnd = valueEnd;
11182+
continue;
11183+
}
1108611184

1108711185
// Offered whatever the built-in made of it: a list already at its
1108811186
// shortest is one `_writeAttribute` declines, not one to ask nobody about.
@@ -11806,7 +11904,13 @@ const _digest = (root) => {
1180611904
continue;
1180711905
}
1180811906
const name = a.serializedName || a.name;
11809-
if (REWRITABLE_ATTRIBUTES.has(a.name) || a.name === "srcdoc") {
11907+
// A handler joins the two the printer rewrites wholesale: a renderer's
11908+
// answer is other text for the same behavior, so comparing it says nothing.
11909+
if (
11910+
REWRITABLE_ATTRIBUTES.has(a.name) ||
11911+
a.name === "srcdoc" ||
11912+
_isEventHandlerAttribute(elementName, a.name)
11913+
) {
1181011914
attributes.push(`${name}=${_DIGEST_OPAQUE}`);
1181111915
continue;
1181211916
}
@@ -12097,9 +12201,6 @@ const printer = (path, writer) => {
1209712201
// Literal-text elements (`script` / `style` / …) keep their body raw;
1209812202
// every other text node is escaped (the WHATWG text split).
1209912203
const parent = path.parentOf();
12100-
// TODO minify an inline `<script>` too: terser reaches webpack only
12101-
// through `minimizer-webpack-plugin` and its API is async, so it needs
12102-
// a JS-minify hook on the options rather than a call from here.
1210312204
if (parent !== 0 && LITERAL_TEXT_PARENTS.has(path.tagName(parent))) {
1210412205
if (!minify) return data;
1210512206
const literalName = path.tagName(parent);
@@ -13772,6 +13873,9 @@ const A = {
1377213873

1377313874
module.exports.A = A;
1377413875
module.exports.EMBEDDED_LANGUAGES = EMBEDDED_LANGUAGES;
13876+
// The `as` an event handler attribute is offered under, read by whoever turns
13877+
// that production into the whole script a JavaScript minifier takes.
13878+
module.exports.EVENT_HANDLER = EVENT_HANDLER;
1377513879
module.exports.NS_HTML = NS_HTML;
1377613880
module.exports.NS_MATHML = NS_MATHML;
1377713881
module.exports.NS_SVG = NS_SVG;

0 commit comments

Comments
 (0)