Skip to content

Commit 88c7714

Browse files
fix(css): spell a rebuilt data url so it parses back, and report a redo throw
Two findings from review, both real. A rebuilt `data:` url was spliced into the output unescaped, so a renderer returning a payload with a space or a quote — an SVG minifier's ordinary output — ended the url token or its string early and a browser dropped the whole declaration. One place now decides how a rebuilt url is spelled: a url token where it can be one, quoted with the delimiter escaped where it cannot. A body still carrying a CSS escape is declined rather than read with its backslashes in it, which is what keeps the rewrite idempotent. And the second code-generation pass called `codeGeneration()` with no try/catch, where the first pass wraps it: a generator throwing there escaped through the async chain instead of being reported as a `CodeGenerationError`, so a build could die with nothing to show for it. Also shortens the changeset and the comments the guidelines cap at two lines, and hashes every renderer option the sample plugin varies on rather than `minimizerOptions` alone.
1 parent 71905c3 commit 88c7714

7 files changed

Lines changed: 92 additions & 37 deletions

File tree

‎.changeset/073-minify-embedded-css-html.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": minor
33
---
44

5-
Add `renderEmbeddedSource` to transform source one language embeds in another: a compilation hook for CSS and HTML in JavaScript, and a serializer option for an inline `<style>`, `<script>`, every `style=""` (SVG's included), an `<svg>` subtree, an `<iframe srcdoc>` document, and a `url()` `data:` payload.
5+
Add `renderEmbeddedSource` to transform source one language embeds in another.

‎lib/Compilation.js‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4143,18 +4143,34 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
41434143
/** @type {CodeGenerationResults} */
41444144
(this.codeGenerationResults);
41454145
for (const { module, runtime, runtimes } of redo) {
4146-
this._generatingModule = module;
4147-
const result = module.codeGeneration({
4148-
chunkGraph: this.chunkGraph,
4149-
moduleGraph: this.moduleGraph,
4150-
dependencyTemplates: this.dependencyTemplates,
4151-
runtimeTemplate: this.runtimeTemplate,
4152-
runtime,
4153-
runtimes,
4154-
codeGenerationResults: results,
4155-
compilation: this
4156-
});
4157-
this._generatingModule = undefined;
4146+
/** @type {CodeGenerationResult} */
4147+
let result;
4148+
try {
4149+
this._generatingModule = module;
4150+
result = module.codeGeneration({
4151+
chunkGraph: this.chunkGraph,
4152+
moduleGraph: this.moduleGraph,
4153+
dependencyTemplates: this.dependencyTemplates,
4154+
runtimeTemplate: this.runtimeTemplate,
4155+
runtime,
4156+
runtimes,
4157+
codeGenerationResults: results,
4158+
compilation: this
4159+
});
4160+
} catch (err) {
4161+
// Reported and carried on with, as the first pass does: a throw
4162+
// here would leave the build with no error to show for it.
4163+
this.errors.push(
4164+
new (getCodeGenerationError())(module, /** @type {Error} */ (err))
4165+
);
4166+
result = {
4167+
sources: new Map(),
4168+
runtimeRequirements: null,
4169+
data: undefined
4170+
};
4171+
} finally {
4172+
this._generatingModule = undefined;
4173+
}
41584174
for (const r of runtimes) results.add(module, r, result);
41594175
}
41604176
// A tap that changed the source again is resolved on the next round.

‎lib/css/syntax.js‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ const { makeCacheable } = require("../util/identifier");
1818

1919
/**
2020
* Renders source this stylesheet embeds — a `data:` URL's payload today.
21-
* Returning the input unchanged declines it, and the URL is then emitted
22-
* exactly as it was written.
21+
* Returning it unchanged declines it, and the URL is emitted as written.
2322
* @typedef {(source: string, info: { type: string, hostType: string }) => string} EmbeddedSourceRenderer
2423
*/
2524
const {
@@ -7971,7 +7970,7 @@ const _minifyUrlFunction = (name, fn, inner) => {
79717970
// A `data:` payload the renderer rewrote: quote it as written, since the
79727971
// unquoted form below cannot carry what a document payload contains.
79737972
const rendered = _renderDataUrl(body);
7974-
if (rendered !== null) return `${name}(${mark}${rendered}${mark})`;
7973+
if (rendered !== null) return `${name}(${_serializeUrl(rendered, mark)})`;
79757974
if (!_UNQUOTABLE_URL_RE.test(body)) return `${name}(${body})`;
79767975
// A code point a url-token cannot carry can still be escaped into one, which
79777976
// costs a byte where the two quotes cost two — so one of them is shorter
@@ -11046,7 +11045,7 @@ const printer = (path, writer) => {
1104611045
if (_renderEmbeddedSource !== undefined) {
1104711046
const renderedUrl = _renderDataUrl(path.value());
1104811047
if (renderedUrl !== null) {
11049-
return `${raw.slice(0, open + 1)}${renderedUrl})`;
11048+
return `${raw.slice(0, open + 1)}${_serializeUrl(renderedUrl, '"')})`;
1105011049
}
1105111050
}
1105211051
// Padding only exists when the content is whitespace-bounded; checking
@@ -11966,6 +11965,34 @@ let _unitScale = ABSOLUTE_UNIT_SCALE;
1196611965
/** @type {EmbeddedSourceRenderer | undefined} */
1196711966
let _renderEmbeddedSource;
1196811967

11968+
/**
11969+
* Offer a url's `data:` payload to the renderer, and rebuild the URL around
11970+
* what comes back. `null` when nothing should change — not a data URL, a media
11971+
* type naming no language webpack knows, a payload that would not round-trip,
11972+
* or a renderer that declined.
11973+
* @param {string} url the url body, unquoted and unescaped
11974+
* @returns {string | null} the rebuilt URL, or null to emit the original
11975+
*/
11976+
const _CSS_STRING_ESCAPE_RE = /[\\\n]/g;
11977+
11978+
/**
11979+
* Spell a rebuilt URL so it parses back to itself: as a url-token when it can
11980+
* be one, otherwise quoted with the delimiter and its escapes written out.
11981+
* @param {string} url the URL to spell
11982+
* @param {string} mark the quote to use when it needs one
11983+
* @returns {string} the `url()` argument
11984+
*/
11985+
const _serializeUrl = (url, mark) => {
11986+
if (!_UNQUOTABLE_URL_RE.test(url)) return url;
11987+
const escaped = _escapeUrlBody(url);
11988+
if (escaped !== null) return escaped;
11989+
return (
11990+
mark +
11991+
url.replace(_CSS_STRING_ESCAPE_RE, "\\$&").split(mark).join(`\\${mark}`) +
11992+
mark
11993+
);
11994+
};
11995+
1196911996
/**
1197011997
* Offer a url's `data:` payload to the renderer, and rebuild the URL around
1197111998
* what comes back. `null` when nothing should change — not a data URL, a media
@@ -11978,6 +12005,9 @@ const _renderDataUrl = (url) => {
1197812005
if (_renderEmbeddedSource === undefined) return null;
1197912006
// Char-code gate so the dominant non-`data:` url costs one read.
1198012007
if ((url.charCodeAt(0) | 0x20) !== CC_LOWER_D) return null;
12008+
// A CSS escape is still written here — the quoted form is percent-decoded,
12009+
// not unescaped — so the payload would be read with its backslashes in it.
12010+
if (url.includes("\\")) return null;
1198112011
const parsed = parseDataURI(url);
1198212012
if (parsed === null) return null;
1198312013
const type = languageOfMediaType(parsed.mediaType);

‎test/CssSyntax.unittest.js‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6477,9 +6477,10 @@ describe("SourceProcessor — renderEmbeddedSource over a data: url", () => {
64776477
expect(offered('.a{background:url("./img.png")}')).toEqual([]);
64786478
});
64796479

6480-
it("rebuilds the url in the form it was written in", () => {
6480+
it("rebuilds the url in the shortest form that parses back to it", () => {
6481+
// A rebuilt url keeps its base64-ness, and loses quotes it no longer needs.
64816482
expect(minify(svgUrl, (s) => s.replace(/\s+/g, ""))).toBe(
6482-
'.a{background:url("data:image/svg+xml,<svg><rect/></svg>")}'
6483+
".a{background:url(data:image/svg+xml,<svg><rect/></svg>)}"
64836484
);
64846485
expect(minify(base64Url, (s) => s.replace(/\s+/g, ""))).toBe(
64856486
`.a{background:url(data:image/svg+xml;base64,${Buffer.from(
@@ -6490,7 +6491,15 @@ describe("SourceProcessor — renderEmbeddedSource over a data: url", () => {
64906491

64916492
it("escapes only what would change what the url means", () => {
64926493
expect(minify(svgUrl, () => "<svg>%#</svg>")).toBe(
6493-
'.a{background:url("data:image/svg+xml,<svg>%25%23</svg>")}'
6494+
".a{background:url(data:image/svg+xml,<svg>%25%23</svg>)}"
6495+
);
6496+
});
6497+
6498+
it("quotes and escapes a payload a url token cannot carry", () => {
6499+
// A space or a quote would end the token, so the url takes quotes and the
6500+
// delimiter inside it is escaped — otherwise the declaration is dropped.
6501+
expect(minify(svgUrl, () => '<svg viewBox="0 0 2 2"/>')).toBe(
6502+
'.a{background:url("data:image/svg+xml,<svg viewBox=\\"0 0 2 2\\"/>")}'
64946503
);
64956504
});
64966505

@@ -6516,7 +6525,9 @@ describe("SourceProcessor — renderEmbeddedSource over a data: url", () => {
65166525
);
65176526
// Eight characters left the payload, and the last mapping's generated
65186527
// column is the only thing that moved — by exactly that much.
6519-
expect(plain.code.length - shrunk.code.length).toBe(8);
6528+
// Eight characters of whitespace, and the two quotes the shorter url no
6529+
// longer needs.
6530+
expect(plain.code.length - shrunk.code.length).toBe(10);
65206531
const columns = (/** @type {string} */ mappings) =>
65216532
mappings.split(",").length;
65226533
expect(columns(shrunk.map.mappings)).toBe(columns(plain.map.mappings));

‎test/HtmlSyntax.unittest.js‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5071,9 +5071,8 @@ describe("SourceProcessor — renderEmbeddedSource", () => {
50715071
});
50725072

50735073
it("keeps a map the renderer attached to an inline `<style>` / `<script>`", () => {
5074-
// The only mechanism a browser honours for inline content is a
5075-
// `sourceMappingURL` in the body itself, so a renderer attaches its own —
5076-
// nothing here has to compose one. This is that contract.
5074+
// A `sourceMappingURL` in the body is the only map a browser honours for
5075+
// inline content, so a renderer attaches its own and nothing composes it.
50775076
const out = minify(
50785077
"<div>\n <style> .a { color : red } </style>\n <script> var a = 1 </script>\n</div>",
50795078
(source, info) =>

‎test/configCases/html/minify-inline-embedded/webpack.config.js‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,8 @@
22

33
const SampleEmbeddedMinifyPlugin = require("../../../helpers/SampleEmbeddedMinifyPlugin");
44

5-
// Stands in for a real minifier, tagging each body with the type it arrived as.
6-
// The fixture has no inline `<style>` / `<script>`: the HTML parser lifts those
7-
// into modules of their own, so only what stays in the document reaches this.
8-
// CSS keeps its shape — a `style=""` arrives wrapped in a throwaway rule, and
9-
// the serializer only unwraps what still is one.
5+
// Tags each body with the type it arrived as. CSS keeps its shape: a `style=""`
6+
// arrives wrapped in a throwaway rule the serializer only unwraps if it stays one.
107
/** @type {import("../../../../lib/html/syntax").EmbeddedSourceRenderer} */
118
const renderEmbeddedSource = (source, { type, hostType }) =>
129
type === "css"

‎test/helpers/SampleEmbeddedMinifyPlugin.js‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,7 @@ const PLUGIN_NAME = "SampleEmbeddedMinifyPlugin";
1414

1515
/**
1616
* Stands in for `minimizer-webpack-plugin`, which owns the real taps: webpack
17-
* ships `renderEmbeddedSource` but taps it nowhere, so this is what
18-
* exercises it. Kept in `test/` on purpose — nothing here should grow
19-
* into a second implementation of the minifier.
17+
* ships `renderEmbeddedSource` but taps it nowhere.
2018
*/
2119
/**
2220
* @typedef {object} SampleEmbeddedMinifyPluginOptions
@@ -45,14 +43,18 @@ class SampleEmbeddedMinifyPlugin {
4543
*/
4644
apply(compiler) {
4745
const { css, html, minimizerOptions, renderEmbeddedSource } = this.options;
48-
// Whatever a tap varies on has to reach the codegen cache key: module
46+
// Everything a tap varies on has to reach the codegen cache key: module
4947
// hashes are taken before code generation, so the hook's own output cannot.
50-
const key = JSON.stringify(minimizerOptions);
48+
const key = JSON.stringify([
49+
css,
50+
html,
51+
minimizerOptions,
52+
renderEmbeddedSource === undefined ? null : String(renderEmbeddedSource)
53+
]);
5154

5255
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
53-
// One tap for every language pair — `info.type` says which arrived, the
54-
// way `minimizer-webpack-plugin` already dispatches assets by filename.
55-
// Async on purpose: a real minifier may only be loadable that way.
56+
// One tap per language pair — `info.type` says which arrived. Async on
57+
// purpose: a real minifier may only be loadable that way.
5658
compilation.hooks.renderEmbeddedSource.tapPromise(
5759
PLUGIN_NAME,
5860
async (source, { type, module }) => {

0 commit comments

Comments
 (0)