Skip to content

Commit 430bd41

Browse files
feat(css, html): extract license comments, and shorten CSS gradients and shadows (#22408)
* feat(css, html): extract license comments, and shorten CSS gradients and shadows minimize.css.extractComments and minimize.html.extractComments take terser's values and a { value, line, col } predicate, moving license comments into [file].LICENSE.txt; HTML writes its banner as <!-- … --> at the end of the document. CSS gradient directions, positions and colors, and shadow colors, are written shorter. * build(deps): bump minimizer-webpack-plugin to 5.13.0 Its formatBanner and getBannerPosition helpers let htmlMinify write the extracted comments' banner as <!-- … --> at the end of the document. * fix(types): keep minimizer-webpack-plugin's types out of the public declarations Its types import webpack's own types.d.ts, so naming them in cssMinify, htmlMinify or util.extractComments made every class appear twice to the generator, which renamed them all. The plugin's extractComments is now typed by what these minifiers read of it. * fix(css): leave an invalid shadow layer as written Dropping currentcolor or trailing zeros from a layer with two colors, too many lengths, or lengths a color parts made a declaration the engine drops valid. SHADOW_PROPERTIES now carries the grammar's length range, and the rewrite runs only over layers already in shape. The equivalence helper's gradient step also leaves strings and url() bodies alone.
1 parent b17fa7d commit 430bd41

128 files changed

Lines changed: 1728 additions & 151 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
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+
Extract CSS and HTML license comments like JS, and shorten CSS gradients.

‎declarations/WebpackOptions.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3148,6 +3148,11 @@ export interface OptimizationMinimizeCss {
31483148
* @since 5.112.0
31493149
*/
31503150
dropOverriddenDeclarations?: boolean;
3151+
/**
3152+
* Move comments out of a `.css` asset into the `[file].LICENSE.txt` the minimizer plugin writes for JavaScript, leaving a one-line banner pointing at it. Takes terser's values: `true` or `"some"` (the default) a `/*!` banner and a comment annotated `@preserve` or `@lic` — terser's `some` bar IE's `@cc_on`, which is left alone, `"all"` every comment, a RegExp or a string read as one the comments it matches, and a function the comments it returns `true` for, asked with the comment's `value` (its text without the delimiters), `line` (from 1) and `col` (from 0). `false` leaves them in the stylesheet, where `comments` decides which survive. A stylesheet webpack minifies inside another document — an inline `<style>`, a `style=""` — keeps them, having no file of its own to point from.
3153+
* @since 5.112.0
3154+
*/
3155+
extractComments?: OptimizationMinimizeExtractComments;
31513156
/**
31523157
* Write a name that matches ASCII case-insensitively in lowercase: an at-rule name, a property name, a pseudo-class or pseudo-element name, a function name, a unit, and a keyword standing in a value whose grammar takes keywords alone. `@MEDIA`, `COLOR`, `:NTH-CHILD`, `URL(`, `1PX` and `currentColor` become `@media`, `color`, `:nth-child`, `url(`, `1px` and `currentcolor`. On by default, and exact: CSS matches every one of these ASCII case-insensitively, so the fold names the same thing. What it never touches is a name the author chose — a custom property, a custom ident such as an animation or grid-area name, an id, a class, a type selector, an attribute's value, or anything inside a substituted value. `@charset` is left as written, being read as bytes rather than matched, and `!important` is always written in lowercase because the printer writes the keyword rather than copying it.
31533158
* @since 5.111.0
@@ -3250,6 +3255,21 @@ export interface OptimizationMinimizeCss {
32503255
vendorPrefixes?: boolean;
32513256
}
32523257

3258+
/**
3259+
* Which comments a minimized asset gives up to its `[file].LICENSE.txt`.
3260+
*/
3261+
export type OptimizationMinimizeExtractComments =
3262+
RegExp | boolean | string | OptimizationMinimizeExtractCommentsCondition;
3263+
3264+
/**
3265+
* Asked about each comment: its text without the delimiters, and its line (from 1) and column (from 0).
3266+
*/
3267+
export type OptimizationMinimizeExtractCommentsCondition = (comment: {
3268+
value: string;
3269+
line: number;
3270+
col: number;
3271+
}) => boolean;
3272+
32533273
/**
32543274
* What the HTML minimizer does. Every transform that keeps the document's DOM is on by default and may be turned off on its own, so a page a rewrite breaks can be minimized without it while the rest still applies; the ones that change what a script or a selector reads back are off until asked for.
32553275
* @since 5.110.0
@@ -3275,6 +3295,11 @@ export interface OptimizationMinimizeHtml {
32753295
| boolean
32763296
| string
32773297
| ((comment: string) => boolean);
3298+
/**
3299+
* Move comments out of an `.html` asset into the `[file].LICENSE.txt` the minimizer plugin writes for JavaScript, leaving a `<!-- … -->` banner at the end of the document pointing at it, so the doctype stays first. Takes the values `minimize.css.extractComments` takes: `true` or `"some"` (the default) a comment opening with `!` or annotated `@preserve` or `@lic` — terser's `some` bar IE's `@cc_on`, which is left alone, `"all"` every comment, a RegExp or a string read as one the comments it matches, and a function the comments it returns `true` for, asked with the comment's `value` (its text without the delimiters), `line` (from 1) and `col` (from 0). `false` leaves them in the document, where `comments` decides which survive. A conditional comment, a server-side include and a `<?…?>` template directive are code and are never taken, and a document nested in another — an `<iframe srcdoc>`, a conditional comment's body — keeps its comments.
3300+
* @since 5.112.0
3301+
*/
3302+
extractComments?: OptimizationMinimizeExtractComments;
32783303
/**
32793304
* Print a run of adjacent `<script>` elements as one, joined by a newline and a `;`. Only bare ones fold — any attribute at all, a `src`, `type`, `nonce`, `async` or `id` among them, says the two are not interchangeable with one — and only where the print writes the bodies itself, so a `<script>` that `output.html.inline` fills in after the print is left alone. A body is left alone too wherever appending it would change what it means: one still inside a string, template or block comment would swallow the next, and a directive prologue, a hashbang or a leading `-->` mean what they do only at a start the appended body no longer has. Off by default: it removes elements, so `document.scripts`, a `script:nth-child()` selector and `querySelectorAll("script").length` all read a different document; a later body's `var` and `function` declarations become visible to the bodies before it; and a body that throws takes the rest of its run with it rather than only itself, while one that does not parse takes the whole run, its own code included.
32803305
* @since 5.111.0

‎lib/css/cssMinify.js‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
* @typedef {(source: string, info: { type: string, hostType: string }) => Promise<string | EmbeddedSourceResult | undefined> | string | EmbeddedSourceResult | undefined} AsyncEmbeddedSourceRenderer
1919
*/
2020
/** @import { SourceMap } from "../util/SourceProcessor" */
21+
/** @typedef {import("../util/extractComments").PluginExtractComments} ExtractCommentsOption */
22+
/** @typedef {import("../../declarations/WebpackOptions").OptimizationMinimizeExtractComments} MinimizeExtractComments */
2123

2224
/**
2325
* A `minify` function for `minimizer-webpack-plugin` (passed as its `minify`
@@ -33,10 +35,16 @@
3335
* re-resolves in the worker — via the installed package, or the dev self-link.
3436
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
3537
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
36-
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, convertLengthUnits?: boolean, convertApproximateColors?: boolean, dropOverriddenDeclarations?: boolean, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer } & CssTransformOptions=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`, and the per-transform switches). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output
37-
* @returns {Promise<{ code: string, map?: SourceMap, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified CSS, its input->output source map (one anchor for the whole of a `block-contents` print, which is emitted as one piece), and what a renderer reported over what this embeds
38+
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, convertLengthUnits?: boolean, convertApproximateColors?: boolean, dropOverriddenDeclarations?: boolean, extractComments?: MinimizeExtractComments, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer } & CssTransformOptions=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`, and the per-transform switches). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output. Its `extractComments` decides which comments move into a separate file, over the plugin's
39+
* @param {ExtractCommentsOption=} extractComments the plugin's `extractComments`, read where `minimize.css.extractComments` is not set
40+
* @returns {Promise<{ code: string, map?: SourceMap, extractedComments?: string[], warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified CSS, its input->output source map (one anchor for the whole of a `block-contents` print, which is emitted as one piece), the comments taken out of it, and what a renderer reported over what this embeds
3841
*/
39-
const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
42+
const cssMinify = async (
43+
input,
44+
sourceMap,
45+
minimizerOptions = {},
46+
extractComments = undefined
47+
) => {
4048
const webpack = /** @type {typeof import("../index")} */ (
4149
// eslint-disable-next-line import/no-extraneous-dependencies -- webpack self-require, re-resolved inside the worker
4250
require(/** @type {string} */ ("webpack"))
@@ -119,6 +127,29 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
119127
// `pickTransforms` is what knows which names those are.
120128
transforms: pickTransforms(minimizerOptions)
121129
};
130+
const extraction = webpack.util.extractComments.extractComments(
131+
minimizerOptions.extractComments === undefined
132+
? extractComments
133+
: minimizerOptions.extractComments,
134+
printOptions.transforms === undefined
135+
? undefined
136+
: printOptions.transforms.comments,
137+
{
138+
open: "/*",
139+
close: "*/",
140+
some: (comment) => /^!|@(?:license|preserve)/i.test(comment),
141+
// Bar the `/*#` pragmas a source map is linked by.
142+
unstated: (comment) => comment.startsWith("#")
143+
}
144+
);
145+
if (extraction !== undefined) {
146+
printOptions.transforms = {
147+
...printOptions.transforms,
148+
comments: /** @type {(comment: string) => boolean} */ (
149+
extraction.comments
150+
)
151+
};
152+
}
122153
/** @type {EmbeddedSourceResult[]} */
123154
const reported = [];
124155
// Handed each body the print offers, with what it reported kept: `processAsync`
@@ -136,9 +167,13 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
136167
renderEmbeddedSource: renderer
137168
});
138169

170+
const answer =
171+
extraction === undefined || extraction.extracted.length === 0
172+
? result
173+
: { ...result, extractedComments: extraction.extracted };
139174
return reported.length === 0
140-
? result
141-
: { ...result, ...collectEmbeddedDiagnostics(reported) };
175+
? answer
176+
: { ...answer, ...collectEmbeddedDiagnostics(reported) };
142177
};
143178

144179
// Worker-safe (see the body's in-worker `require`), so it may run in the shared

‎lib/css/data.js‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2034,11 +2034,11 @@ const DISPLAY_SHORT_FORMS = new Map([
20342034
["run-in flow", "run-in"]
20352035
]);
20362036

2037-
// Each property whose value is a list of shadows -> the count of lengths a
2038-
// shadow cannot go below, past which a trailing zero is already implied.
2037+
// Each property whose value is a list of shadows -> the fewest and most lengths
2038+
// a shadow takes; a trailing zero past the fewest is already implied.
20392039
const SHADOW_PROPERTIES = new Map([
2040-
["box-shadow", 2],
2041-
["text-shadow", 2]
2040+
["box-shadow", [2, 4]],
2041+
["text-shadow", [2, 3]]
20422042
]);
20432043

20442044
// WHY: Each shorthand -> the keywords one of its values may drop, each with every
@@ -2920,6 +2920,25 @@ const AUTO_SECOND_VALUE_PROPERTIES = new Set(["background-size", "mask-size"]);
29202920
// `-webkit-` one measures its angle the other way, so it keeps what it says.
29212921
const DEFAULT_GRADIENT_DIRECTIONS = new Set(["to bottom", "180deg", "0.5turn"]);
29222922

2923+
// The position a radial or conic gradient is centered on when it names none.
2924+
const DEFAULT_GRADIENT_POSITIONS = new Set([
2925+
"center",
2926+
"center center",
2927+
"50%",
2928+
"50% 50%"
2929+
]);
2930+
2931+
// The flow opposite the default one, which reversing the stops turns into it.
2932+
const REVERSED_GRADIENT_DIRECTIONS = new Set(["to top", "0deg"]);
2933+
2934+
// A linear gradient's side keyword -> the shorter angle naming the same flow.
2935+
/** @type {Map<string, string>} */
2936+
const GRADIENT_SIDE_ANGLES = new Map([
2937+
["to top", "0deg"],
2938+
["to right", "90deg"],
2939+
["to left", "270deg"]
2940+
]);
2941+
29232942
// A name CSS matches ASCII case-insensitively but spells with a capital ->
29242943
// that spelling, so lowercasing a name normalizes its case without printing
29252944
// `translatey` or `1q` for what everything else writes `translateY` and `1Q`.
@@ -8180,6 +8199,8 @@ module.exports.CSS_WIDE_KEYWORDS = CSS_WIDE_KEYWORDS;
81808199
module.exports.CUBIC_BEZIER_KEYWORDS = CUBIC_BEZIER_KEYWORDS;
81818200
module.exports.CUSTOM_IDENT_LIST_PROPERTIES = CUSTOM_IDENT_LIST_PROPERTIES;
81828201
module.exports.DEFAULT_GRADIENT_DIRECTIONS = DEFAULT_GRADIENT_DIRECTIONS;
8202+
module.exports.DEFAULT_GRADIENT_POSITIONS = DEFAULT_GRADIENT_POSITIONS;
8203+
module.exports.REVERSED_GRADIENT_DIRECTIONS = REVERSED_GRADIENT_DIRECTIONS;
81838204
module.exports.DISPLAY_SHORT_FORMS = DISPLAY_SHORT_FORMS;
81848205
module.exports.DROPPABLE_WHEN_EMPTY_AT_RULES = DROPPABLE_WHEN_EMPTY_AT_RULES;
81858206
module.exports.EASING_KEYWORDS = EASING_KEYWORDS;
@@ -8201,6 +8222,7 @@ module.exports.FONT_STRETCH_PERCENTAGES = FONT_STRETCH_PERCENTAGES;
82018222
module.exports.FONT_WEIGHT_NUMBERS = FONT_WEIGHT_NUMBERS;
82028223
module.exports.GENERIC_FONT_FAMILIES = GENERIC_FONT_FAMILIES;
82038224
module.exports.GRADIENT_LAST_POSITIONS = GRADIENT_LAST_POSITIONS;
8225+
module.exports.GRADIENT_SIDE_ANGLES = GRADIENT_SIDE_ANGLES;
82048226
module.exports.getInitialValueKeywords = getInitialValueKeywords;
82058227
module.exports.INTEGER_PROPERTIES = INTEGER_PROPERTIES;
82068228
module.exports.getKeywordOnlyProperties = getKeywordOnlyProperties;

‎lib/css/syntax-parser.js‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7115,8 +7115,9 @@ const _isKeptComment = (src, start, end) => {
71157115
}
71167116
// A pattern or a predicate of the author's, over the comment's own text —
71177117
// which stands in for the banner rule rather than beside it, as terser's
7118-
// `format.comments` does.
7119-
return kept(src.slice(start + 2, end - 2)) === true;
7118+
// `format.comments` does. Its line and column follow, for a caller placing it.
7119+
const loc = _locConverter.get(start);
7120+
return kept(src.slice(start + 2, end - 2), loc.line, loc.column) === true;
71207121
};
71217122

71227123
// Every rewrite on, which is what a print with no `transforms` option makes and
@@ -15720,7 +15721,7 @@ let _distantSeq = 0;
1572015721
// Which comments this print keeps, with a pattern already compiled to the
1572115722
// predicate it stands for — `true` every one, `false` none, `"some"` the ones
1572215723
// that carry something (see `_isKeptComment`).
15723-
/** @type {boolean | "some" | ((comment: string) => boolean)} */
15724+
/** @type {boolean | "some" | ((comment: string, line: number, column: number) => boolean)} */
1572415725
let _commentsKept = "some";
1572515726

1572615727
// Where a `block-contents` print holds its top-level nodes instead of emitting

0 commit comments

Comments
 (0)