GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(html): keep escaped text from becoming markup when minifying or r… · webpack/webpack@384dfaa

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .changeset
    • 107-html-markup-escaping.md
  • lib
    • css
      • CssParser.js
    • dependencies/html
      • HtmlInlineHtmlDependency.js
      • HtmlInlineStyleDependency.js
    • html
      • HtmlGenerator.js
      • HtmlParser.js
      • htmlMinify.js
      • syntax-parser.js
      • syntax-printer.js
    • util
      • SourceProcessor.js
  • test
    • configCases/html/generated-markup-escaping
      • bom.html
      • dot.svg
      • import.html
      • nested.html
      • test.config.js
      • test.js
      • theme.css
      • unquoted.html
      • webpack.config.js
    • unitCases/html
      • __snapshots__
        • printer.unittest.js.snap
      • printer.unittest.js
  • tooling
    • compare-html-tools.js
  • types.d.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.changeset/107-html-markup-escaping.md‎

Copy file name to clipboard
+5Lines changed: 5 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Stop the HTML minifier and generator from turning escaped text into markup.
Collapse file

‎lib/css/CssParser.js‎

Copy file name to clipboardExpand all lines: lib/css/CssParser.js
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,9 +1049,8 @@ class CssParser extends Parser {
10491049
} else if (typeof source === "object") {
10501050
throw new Error("webpackAst is unexpected for the CssParser");
10511051
}
1052-
if (source[0] === "\uFEFF") {
1053-
source = source.slice(1);
1054-
}
1052+
// No BOM is stripped here: `processResult` already took the one a file
1053+
// starts with, and the ranges must index the source the generator edits.
10551054

10561055
// Per-parse comment side-array — kept local (like HtmlParser) so nothing is retained on the reused parser instance between modules.
10571056
/** @type {Comment[]} */
Collapse file

‎lib/dependencies/html/HtmlInlineHtmlDependency.js‎

Copy file name to clipboardExpand all lines: lib/dependencies/html/HtmlInlineHtmlDependency.js
+11-2Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ const ModuleDependency = require("../core/ModuleDependency");
1818
// One pass over the source: each char is replaced once and replacements aren't
1919
// re-scanned, so this matches the `&`-first sequential escape chain exactly.
2020
const ATTR_ESCAPE_REGEXP = /[&"']/g;
21+
// A decoded `</noscript>` ends a `<noscript>` read with scripting on.
22+
const NOSCRIPT_CLOSE_REGEXP = /<(\/noscript)/gi;
2123
/** @type {Record<string, string>} */
2224
const ATTR_ESCAPES = { "&": "&amp;", '"': "&quot;", "'": "&#39;" };
2325
/**
@@ -87,9 +89,16 @@ HtmlInlineHtmlDependency.Template = class HtmlInlineHtmlDependencyTemplate exten
8789

8890
// The attribute value was entity-decoded before parsing, so re-escape the
8991
// processed HTML to keep the surrounding `srcdoc="..."` attribute valid.
90-
const htmlText = (
92+
let htmlText = (
9193
htmlSource ? /** @type {string} */ (htmlSource.source()) : ""
92-
).replace(ATTR_ESCAPE_REGEXP, escapeAttrChar);
94+
)
95+
.replace(ATTR_ESCAPE_REGEXP, escapeAttrChar)
96+
.replace(NOSCRIPT_CLOSE_REGEXP, "&lt;$1");
97+
// Whitespace or `>` would end an unquoted value, so that one is quoted.
98+
const quote = /** @type {string} */ (source.original().source()).charCodeAt(
99+
dep.range[0] - 1
100+
);
101+
if (quote !== 0x22 && quote !== 0x27) htmlText = `"${htmlText}"`;
93102

94103
source.replace(dep.range[0], dep.range[1] - 1, htmlText);
95104
}
Collapse file

‎lib/dependencies/html/HtmlInlineStyleDependency.js‎

Copy file name to clipboardExpand all lines: lib/dependencies/html/HtmlInlineStyleDependency.js
+30-7Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ const TRAILING_WHITESPACE_REGEXP = /\s+$/;
2222
// re-scanned, so this matches the `&`-first sequential escape chain exactly
2323
// while avoiding two extra full-string scans + intermediate strings.
2424
const ATTR_ESCAPE_REGEXP = /[&"']/g;
25+
// A decoded `</noscript>` ends a `<noscript>` read with scripting on.
26+
const NOSCRIPT_CLOSE_REGEXP = /<(\/noscript)/gi;
2527
/** @type {Record<string, string>} */
2628
const ATTR_ESCAPES = { "&": "&amp;", '"': "&quot;", "'": "&#39;" };
2729
/**
@@ -42,6 +44,22 @@ const TEXT_ESCAPES = { "&": "&amp;", "<": "&lt;", "\r": "&#13;" };
4244
*/
4345
const escapeTextChar = (c) => TEXT_ESCAPES[c];
4446

47+
/**
48+
* Whether the attribute value starting at `start` sits between quotes.
49+
* @param {ReplaceSource} source the source being written
50+
* @param {number} start where the value starts
51+
* @returns {boolean} true for a quoted value
52+
*/
53+
const isQuotedValue = (source, start) => {
54+
const quote = /** @type {string} */ (source.original().source()).charCodeAt(
55+
start - 1
56+
);
57+
return quote === 0x22 || quote === 0x27;
58+
};
59+
60+
// In CSS `<\/style` reads as `</style`, which a string or comment can hold.
61+
const RAW_TEXT_CLOSE_REGEXP = /<\/(noscript|style)/gi;
62+
4563
/**
4664
* Represents inline CSS in an HTML module — either a `<style>...</style>`
4765
* block (a stylesheet) or an element's `style="..."` attribute (a CSS
@@ -152,18 +170,23 @@ HtmlInlineStyleDependency.Template = class HtmlInlineStyleDependencyTemplate ext
152170
if (dep.inAttribute) {
153171
cssText = cssText
154172
.replace(TRAILING_WHITESPACE_REGEXP, "")
155-
.replace(ATTR_ESCAPE_REGEXP, escapeAttrChar);
173+
.replace(ATTR_ESCAPE_REGEXP, escapeAttrChar)
174+
.replace(NOSCRIPT_CLOSE_REGEXP, "&lt;$1");
175+
// Whitespace or `>` would end an unquoted value, so that one is quoted.
176+
if (!isQuotedValue(source, dep.range[0])) {
177+
cssText = `"${cssText}"`;
178+
}
156179
} else {
157180
// A `<style>` body keeps the whitespace its source ends with: the newline
158181
// the generator appends to hold a stylesheet's modules apart is no fixed
159182
// point here, and a page built from an emitted one would gain one a pass.
160183
if (cssText.endsWith("\n")) cssText = cssText.slice(0, -1);
161-
if (dep.characterData) {
162-
// A foreign `<style>` body was entity-decoded before parsing, so the
163-
// processed CSS is escaped back as text — its newlines stay literal,
164-
// which an attribute value could not afford.
165-
cssText = cssText.replace(TEXT_ESCAPE_REGEXP, escapeTextChar);
166-
}
184+
// A foreign `<style>` body was entity-decoded before parsing, so it is
185+
// escaped back as text. An HTML one is raw text, which an `@import`ed
186+
// `</style` would end, and `</noscript` the `<noscript>` around it.
187+
cssText = dep.characterData
188+
? cssText.replace(TEXT_ESCAPE_REGEXP, escapeTextChar)
189+
: cssText.replace(RAW_TEXT_CLOSE_REGEXP, "<\\/$1");
167190
}
168191

169192
source.replace(dep.range[0], dep.range[1] - 1, cssText);
Collapse file

‎lib/html/HtmlGenerator.js‎

Copy file name to clipboardExpand all lines: lib/html/HtmlGenerator.js
+50-1Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,53 @@ const memoize = require("../util/memoize");
2222
const { PUBLIC_PATH_AUTO } = require("../util/publicPathPlaceholder");
2323
const { VOID } = require("./data");
2424

25+
/**
26+
* The source without the edits that fall inside a range another edit replaces.
27+
* `ReplaceSource` writes such an edit's content after the outer one's, so an
28+
* attribute rewrite inside a dropped or inlined tag would land as loose markup.
29+
* @param {ReplaceSource} source the edited source
30+
* @param {Source} originalSource what it edits
31+
* @returns {ReplaceSource} the source, or a copy holding only the outer edits
32+
*/
33+
const withoutNestedReplacements = (source, originalSource) => {
34+
const replacements = source.getReplacements();
35+
// Widest first among edits starting at one offset, so the outer comes first.
36+
const byReach = [...replacements].sort(
37+
(a, b) => a.start - b.start || b.end - a.end
38+
);
39+
/** @type {Set<(typeof replacements)[number]> | undefined} */
40+
let nested;
41+
let reachStart = -1;
42+
let reachEnd = -1;
43+
for (const replacement of byReach) {
44+
const { start, end } = replacement;
45+
// An insertion (`end < start`) is nested only strictly inside the range.
46+
const inside =
47+
end < start
48+
? start > reachStart && start <= reachEnd
49+
: end <= reachEnd && (start !== reachStart || end !== reachEnd);
50+
if (inside) {
51+
if (nested === undefined) nested = new Set();
52+
nested.add(replacement);
53+
} else if (end > reachEnd) {
54+
reachStart = start;
55+
reachEnd = end;
56+
}
57+
}
58+
if (nested === undefined) return source;
59+
const kept = new ReplaceSource(originalSource);
60+
for (const replacement of replacements) {
61+
if (nested.has(replacement)) continue;
62+
kept.replace(
63+
replacement.start,
64+
replacement.end,
65+
replacement.content,
66+
replacement.name
67+
);
68+
}
69+
return kept;
70+
};
71+
2572
const getCreateNodeHash = memoize(() => require("crypto").createHash);
2673

2774
const getCssParser = memoize(() => require("../css/syntax-parser"));
@@ -1464,7 +1511,9 @@ class HtmlGenerator extends Generator {
14641511
const initFragments = [];
14651512

14661513
this.sourceModule(module, initFragments, source, generateContext);
1467-
rawContent = /** @type {string} */ (source.source());
1514+
rawContent = /** @type {string} */ (
1515+
withoutNestedReplacements(source, originalSource).source()
1516+
);
14681517
this._rawRenderCache.set(cacheKey, rawContent);
14691518
}
14701519

Collapse file

‎lib/html/HtmlParser.js‎

Copy file name to clipboardExpand all lines: lib/html/HtmlParser.js
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -977,9 +977,8 @@ class HtmlParser extends Parser {
977977
} else if (typeof source === "object") {
978978
throw new Error("webpackAst is unexpected for the HtmlParser");
979979
}
980-
if (source[0] === "\uFEFF") {
981-
source = source.slice(1);
982-
}
980+
// No BOM is stripped here: `processResult` already took the one a file
981+
// starts with, and the ranges must index the source the generator edits.
983982

984983
const locConverter = new LocConverter(source);
985984

Collapse file

‎lib/html/htmlMinify.js‎

Copy file name to clipboardExpand all lines: lib/html/htmlMinify.js
+14-7Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,8 @@ const htmlMinify = async (
117117
removeRedundantAttributes,
118118
sortAttributes,
119119
sortTokenLists,
120-
removeImpliedTags
120+
removeImpliedTags,
121+
srcdoc: false
121122
};
122123
// Handed each body the print offers, keeping what it reported: the element or
123124
// attribute around one is written from that answer, and a body declined or
@@ -152,7 +153,12 @@ const htmlMinify = async (
152153
// nested document, which is a document minified the same way.
153154
const own = builtin(source, hole);
154155
if (own !== undefined) return own;
155-
return hole.type === "html" ? minifyDocument(source) : undefined;
156+
if (hole.type !== "html") return undefined;
157+
// A browser never reads an `<iframe srcdoc>` document in quirks mode.
158+
return minifyDocument(
159+
source,
160+
hole.as === "srcdoc" ? { ...printOptions, srcdoc: true } : printOptions
161+
);
156162
};
157163
/**
158164
* @param {string} text a whole document
@@ -189,10 +195,10 @@ const htmlMinify = async (
189195
// so each nested document is finished before it is spliced in.
190196
/**
191197
* @param {string} text a whole document
192-
* @param {typeof printOptions=} options the print's options, the asset's own for the outermost document
198+
* @param {typeof printOptions} options the print's options, the asset's own for the outermost document
193199
* @returns {Promise<string>} the same document, minified
194200
*/
195-
const minifyDocument = async (text, options = printOptions) => {
201+
const minifyDocument = async (text, options) => {
196202
// Put back into the source, not the output: the printer respells an
197203
// attribute value, so the recorded text is not what the output holds.
198204
let source = text;
@@ -231,7 +237,8 @@ const htmlMinify = async (
231237
});
232238
};
233239

234-
new SourceProcessor().use(visitors).process(source, {});
240+
// Read as the browser does: with scripting on, a `<noscript>` holds text.
241+
new SourceProcessor().use(visitors).process(source, { scripting: true });
235242

236243
/**
237244
* @param {string} markup a conditional comment's body
@@ -269,8 +276,8 @@ const htmlMinify = async (
269276

270277
// Read where the comment sits, not as a document: a print that adds,
271278
// drops or moves a tag (a wrapper another comment closes, a table's
272-
// row) decided as one would, so the body stays as written.
273-
if (tagsOf(inner) !== tagsOf(value)) continue;
279+
// row) decided as one would, or spells what ends the comment, stays.
280+
if (/--!?>/.test(inner) || tagsOf(inner) !== tagsOf(value)) continue;
274281

275282
source = `${source.slice(0, start)}${inner}${source.slice(end)}`;
276283
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.