Skip to content

Commit 1acff82

Browse files
fix(html): read a <script type> decoded, and trim an inline script
An attribute value is stored raw, so `type="text&#47;javascript"` was read as a data block while the parser and every browser read it as JavaScript: its body never reached the JS renderer, and an entity-spelled `application&#47;ld&#43;json` was left unminified beside an attribute the printer had already decoded. `removeRedundantAttributes` read the same value raw, so the two disagreed about one `<script>`. An inline script whose type names JavaScript now also loses the whitespace at its edges, which sits between tokens rather than in the program. A body that is only whitespace keeps it: emptying the element would hand it to `removeEmptyElements`. A data block's body is left alone — its whitespace can be its own syntax, as an indented YAML or Markdown payload shows. Co-authored-by: aryanraj45 <[email protected]>
1 parent f6b470a commit 1acff82

19 files changed

Lines changed: 380 additions & 18 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+
Read a `<script type>` decoded and trim an inline script's own whitespace.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2500,7 +2500,7 @@ export interface OptimizationMinimizeHtml {
25002500
*/
25012501
collapseBooleanAttributes?: boolean;
25022502
/**
2503-
* Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace renders verbatim. `true` (or `"conservative"`) never removes whitespace entirely — dropping it would join two inline elements that render apart. `"smart"` also drops the whitespace that sits against a block element's edge, where no line box reaches it. `"all"` drops the whitespace at every text node's edges, which does change how adjacent inline elements render.
2503+
* Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace renders verbatim. `true` (or `"conservative"`) never removes whitespace entirely — dropping it would join two inline elements that render apart. `"smart"` also drops the whitespace that sits against a block element's edge, where no line box reaches it. `"all"` drops the whitespace at every text node's edges, which does change how adjacent inline elements render. An inline `<script>` holding JavaScript or JSON is trimmed at its edges in every tier, that whitespace sitting outside the program text; a data block's body is left alone, its own whitespace being part of its syntax.
25042504
* @since 5.110.0
25052505
*/
25062506
collapseWhitespace?: ("conservative" | "smart" | "all") | boolean;

‎lib/html/syntax.js‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8934,7 +8934,7 @@ const mirrorSelectedContent = (node, select) => {
89348934
* @property {boolean=} rewriteCustomProperties CSS's too, handed over with `environment` (see `HtmlPrintOptions`)
89358935
* @property {CssTransformOptions=} cssTransforms CSS's per-transform switches too, handed over with `environment` (see `HtmlPrintOptions`)
89368936
* @property {HtmlTransformOptions=} transforms which of the meaning-preserving rewrites the minifying print makes; each is on unless it is `false`
8937-
* @property {(boolean | "conservative" | "smart" | "all")=} collapseWhitespace collapse each run of whitespace in text to a single space, except where an ancestor renders it verbatim; `"smart"` also drops what sits against a block edge and `"all"` drops every edge (default false)
8937+
* @property {(boolean | "conservative" | "smart" | "all")=} collapseWhitespace collapse each run of whitespace in text to a single space, except where an ancestor renders it verbatim; `"smart"` also drops what sits against a block edge and `"all"` drops every edge; an inline `<script>` holding JavaScript or JSON is trimmed at its edges, a data block's body never (default false)
89388938
* @property {boolean=} removeEmptyAttributes drop an attribute whose empty value leaves it in the state its absence gives (default false)
89398939
* @property {boolean=} removeEmptyElements drop an element with no children and no attributes, unless its bare form is meaningful (default false)
89408940
* @property {boolean=} mergeStyles print a run of adjacent `<style>` elements as one sheet, which removes elements (default false)
@@ -10049,10 +10049,11 @@ const _isRedundantAttribute = (markers, defaults, tagName, name, value) => {
1004910049
// `<script type>`: only a spelling that names JavaScript, which is what the
1005010050
// element already runs. `module` and the empty spelling say something.
1005110051
if (tagName === "script" && name === "type") {
10052+
const type = value.includes("&")
10053+
? _asciiLowerCase(_asciiTrim(decodeEntities(value, true)))
10054+
: lowered;
1005210055
return (
10053-
lowered !== "" &&
10054-
lowered !== "module" &&
10055-
JAVASCRIPT_SCRIPT_TYPES.has(lowered)
10056+
type !== "" && type !== "module" && JAVASCRIPT_SCRIPT_TYPES.has(type)
1005610057
);
1005710058
}
1005810059
if (markers !== undefined && markers[name] === lowered) return true;
@@ -10430,7 +10431,13 @@ const _rewriteAttributeValue = (element, name, raw, viewport, enumeratedOn) => {
1043010431
const _scriptType = (path, element) => {
1043110432
for (const attribute of path.attributes(element)) {
1043210433
if (attribute.name === "type") {
10433-
return _asciiLowerCase(_asciiTrim(attribute.value));
10434+
const raw = attribute.value;
10435+
// The value the spec matches is the one the parser read, so a reference
10436+
// is decoded first: `text&#47;javascript` runs, it is not a data block.
10437+
// Guarded on the reference, so the decode stays off the hot path.
10438+
return _asciiLowerCase(
10439+
_asciiTrim(raw.includes("&") ? decodeEntities(raw, true) : raw)
10440+
);
1043410441
}
1043510442
}
1043610443
return "";
@@ -12075,16 +12082,27 @@ const printer = (path, writer) => {
1207512082
if (JSON_SCRIPT_TYPES.has(type) || _JSON_SUBTYPE_REGEXP.test(type)) {
1207612083
return _minifyInlineJson(data);
1207712084
}
12085+
// A data block — a template, a payload in a language nothing here
12086+
// names. Its whitespace can be its own syntax, so it is left alone.
12087+
if (!JAVASCRIPT_SCRIPT_TYPES.has(type)) return data;
12088+
// Program text: its edges sit between tokens, and the parser is
12089+
// where the body ends. Trimmed before the offer, so a renderer that
12090+
// declines still leaves them behind. A body that is only whitespace
12091+
// keeps it: emptying the element hands it to `removeEmptyElements`,
12092+
// and the DOM would lose a `<script>` the source wrote.
12093+
const trimmed =
12094+
_collapseWhitespace === "none" ? data : _asciiTrim(data);
12095+
const body = trimmed === "" ? data : trimmed;
1207812096
// No built-in: webpack ships no JS minifier, so an inline script is
1207912097
// touched only by a caller's renderer.
1208012098
if (
1208112099
(_renderEmbeddedSource !== undefined ||
1208212100
_deferEmbeddedSource !== undefined) &&
12083-
JAVASCRIPT_SCRIPT_TYPES.has(type) &&
12084-
data.trim() !== ""
12101+
body !== ""
1208512102
) {
12086-
return _renderEmbedded(data, JAVASCRIPT_TYPE);
12103+
return _renderEmbedded(body, JAVASCRIPT_TYPE);
1208712104
}
12105+
return body;
1208812106
}
1208912107
return data;
1209012108
}

‎schemas/WebpackOptions.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3833,7 +3833,7 @@
38333833
"added": "5.110.0"
38343834
},
38353835
"collapseWhitespace": {
3836-
"description": "Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace renders verbatim. `true` (or `\"conservative\"`) never removes whitespace entirely — dropping it would join two inline elements that render apart. `\"smart\"` also drops the whitespace that sits against a block element's edge, where no line box reaches it. `\"all\"` drops the whitespace at every text node's edges, which does change how adjacent inline elements render.",
3836+
"description": "Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace renders verbatim. `true` (or `\"conservative\"`) never removes whitespace entirely — dropping it would join two inline elements that render apart. `\"smart\"` also drops the whitespace that sits against a block element's edge, where no line box reaches it. `\"all\"` drops the whitespace at every text node's edges, which does change how adjacent inline elements render. An inline `<script>` holding JavaScript or JSON is trimmed at its edges in every tier, that whitespace sitting outside the program text; a data block's body is left alone, its own whitespace being part of its syntax.",
38373837
"anyOf": [
38383838
{
38393839
"enum": ["conservative", "smart", "all"]

‎test/HtmlSyntax.unittest.js‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4193,6 +4193,131 @@ describe("SourceProcessor — JSON <script> bodies", () => {
41934193
});
41944194
});
41954195

4196+
describe("SourceProcessor — inline <script> whitespace", () => {
4197+
const { SourceProcessor } = require("../lib/html/syntax");
4198+
4199+
/**
4200+
* @param {string} type the `<script type>` value
4201+
* @param {string} body the raw body
4202+
* @param {"conservative" | "smart" | "all"=} collapseWhitespace the tier
4203+
* @returns {string} the body, minified
4204+
*/
4205+
const minifyBody = (type, body, collapseWhitespace = "all") => {
4206+
const out = new SourceProcessor().process(
4207+
`<script type="${type}">${body}</script>`,
4208+
{ mode: "minify", collapseWhitespace }
4209+
).code;
4210+
return out.slice(out.indexOf(">") + 1, out.lastIndexOf("</script>"));
4211+
};
4212+
4213+
it.each(["", "module", "text/javascript", "application/javascript"])(
4214+
"trims the edges of the program text (%s)",
4215+
(type) => {
4216+
expect(minifyBody(type, " var a = 1 ")).toBe("var a = 1");
4217+
}
4218+
);
4219+
4220+
it.each(
4221+
/** @type {("conservative" | "smart" | "all")[]} */ ([
4222+
"conservative",
4223+
"smart",
4224+
"all"
4225+
])
4226+
)("trims where collapsing is %s", (tier) => {
4227+
// Whitespace outside the program renders nothing, so no tier keeps it.
4228+
expect(minifyBody("", " var a = 1 ", tier)).toBe("var a = 1");
4229+
});
4230+
4231+
it("takes every character HTML counts as whitespace", () => {
4232+
expect(minifyBody("", "\t\n\f\r var a = 1 \r\f\n\t")).toBe("var a = 1");
4233+
});
4234+
4235+
it("keeps a body that is only whitespace", () => {
4236+
// Emptying the element hands it to `removeEmptyElements`, and a `<script>`
4237+
// the source wrote would go missing from the DOM.
4238+
expect(minifyBody("", " ")).toBe(" ");
4239+
});
4240+
4241+
it("keeps a NBSP, which is a character and not whitespace", () => {
4242+
// It sits next to a JavaScript identifier, it does not separate one.
4243+
expect(minifyBody("", "\u00A0var a = 1\u00A0")).toBe(
4244+
"\u00A0var a = 1\u00A0"
4245+
);
4246+
});
4247+
4248+
it.each([
4249+
"text/x-template",
4250+
"text/template",
4251+
"text/ng-template",
4252+
"text/html",
4253+
"text/plain",
4254+
"unknown/thing"
4255+
])("leaves the body of the data block %s alone", (type) => {
4256+
// Its own syntax is not ours to read, and its whitespace can be part of it.
4257+
expect(minifyBody(type, " <div> x </div> ")).toBe(" <div> x </div> ");
4258+
});
4259+
4260+
it("keeps the indentation a payload's own language may count", () => {
4261+
// Trimming the edges alone would leave the first line of this at column 0
4262+
// and every other one indented — which is no longer the same document.
4263+
const yaml = "\n a: 1\n b: 2\n ";
4264+
expect(minifyBody("text/yaml", yaml)).toBe(yaml);
4265+
});
4266+
4267+
it.each([
4268+
"text&#47;javascript",
4269+
"text&#x2F;javascript",
4270+
"&#116;ext/javascript"
4271+
])("reads %s as executable, since the parser decodes it", (type) => {
4272+
// Chrome runs each of these, so each is program text and not a data block.
4273+
expect(minifyBody(type, " var a = 1 ")).toBe("var a = 1");
4274+
});
4275+
4276+
it("reads an entity-encoded JSON type as JSON", () => {
4277+
expect(minifyBody("application&#47;ld&#43;json", ' { "a" : 1 } ')).toBe(
4278+
'{"a":1}'
4279+
);
4280+
});
4281+
4282+
it("reads the type case- and whitespace-insensitively", () => {
4283+
expect(minifyBody(" TEXT/JAVASCRIPT ", " var a = 1 ")).toBe("var a = 1");
4284+
expect(minifyBody(" TEXT/X-TEMPLATE ", " x ")).toBe(" x ");
4285+
});
4286+
4287+
it("leaves every body alone where whitespace is kept", () => {
4288+
const out = new SourceProcessor().process(
4289+
"<script> var a = 1 </script>",
4290+
{ mode: "minify" }
4291+
).code;
4292+
expect(out).toBe("<script> var a = 1 </script>");
4293+
});
4294+
4295+
it("trims an inline script in foreign content too", () => {
4296+
const out = new SourceProcessor().process(
4297+
"<svg><script> var a = 1 </script></svg>",
4298+
{ mode: "minify", collapseWhitespace: "all" }
4299+
).code;
4300+
expect(out).toBe("<svg><script>var a = 1</script></svg>");
4301+
});
4302+
4303+
it("drops a redundant type spelled with a reference", () => {
4304+
// The same reading as the body: what the parser sees is `text/javascript`,
4305+
// which is what the element runs anyway.
4306+
const minify = (/** @type {string} */ html) =>
4307+
new SourceProcessor().process(html, {
4308+
mode: /** @type {"minify"} */ ("minify"),
4309+
removeRedundantAttributes: /** @type {"smart"} */ ("smart")
4310+
}).code;
4311+
expect(
4312+
minify('<script type="text&#47;javascript">var a = 1</script>')
4313+
).toBe("<script>var a = 1</script>");
4314+
// A data block's type is what tells it apart from a script, so it stays.
4315+
expect(minify('<script type="text&#47;x-template">x</script>')).toBe(
4316+
"<script type=text/x-template>x</script>"
4317+
);
4318+
});
4319+
});
4320+
41964321
describe("SourceProcessor — collapseWhitespace modes", () => {
41974322
const { SourceProcessor } = require("../lib/html/syntax");
41984323

0 commit comments

Comments
 (0)