html-minifier
Version:
Highly effective, super-configurable, well-tested web page minifier
1,359 lines (1,256 loc) • 49.6 kB
JavaScript
/**
* HTML attribute parsing, decoding, and minification
*/
import {
RE_EVENT_ATTR_DEFAULT,
RE_CAN_REMOVE_ATTR_QUOTES,
RE_AMP_REFERENCE_ATTR,
RE_CR,
RE_ATTR_SELECTOR,
RE_BASE_ELEMENT,
RE_ATTR_WS_CHECK,
RE_ATTR_WS_COLLAPSE,
RE_TABS_ONLY,
RE_WS_CHAR,
generalDefaults,
tagDefaults,
metaHttpEquivNoEffect,
metaNamesNoEffect,
targetSelfElements,
tagDefaultsSVG,
svgElementsInheritingByReference,
namespaceHTML,
namespaceSVG,
namespaceMathML,
namespaceXLink,
executableScriptsMimetypes,
keepScriptsMimetypes,
isSimpleBoolean,
isBooleanValue,
collapsibleValues,
srcsetElements,
RE_EMPTY_ATTRIBUTE,
RE_STYLE_ELEMENT,
RE_STYLE_TAG
} from './constants.js';
import { trimWhitespace, collapseWhitespaceAll } from './whitespace.js';
import { shouldMinifyInnerHTML } from './options.js';
import { collectUsage } from './unused-css.js';
import { escapeXML, identity, isThenable, lowercase } from './utils.js';
/** @import { ProcessedOptions } from './options.js' */
/**
* @typedef {{ name: string, value?: string | undefined, quote?: string, customAssign?: string, customOpen?: string, customClose?: string }} HTMLAttribute
* Internal counterpart of the public typedef in htmlminifier.js—keep in sync.
*/
// Lazy-load entities (used for `decodeEntities`, event-handler attribute decoding
// before `minifyJS`, `srcdoc` decoding, and values SVGO reads)
/** @type {Promise<Function> | undefined} */
let decodeHTMLAttributePromise;
/** @type {((text: string) => string) | undefined} The resolved `decodeHTMLAttribute`, once the lazy import above has settled */
let decodeHTMLAttributeFn;
async function getDecodeHTMLAttribute() {
if (!decodeHTMLAttributePromise) {
decodeHTMLAttributePromise = import('entities').then(m => (decodeHTMLAttributeFn = m.decodeHTMLAttribute));
}
return decodeHTMLAttributePromise;
}
const RE_ATTRIBUTE_ESCAPE = /["&\u00A0]/g;
const attributeEscapes = { '"': '"', '&': '&', '\u00A0': ' ' };
/**
* Escapes a quoted attribute value, keeping `<` and `>` (unlike `entities` 9’s `escapeAttribute`)
* @param {string} value
* @returns {string}
*/
function escapeAttribute(value) {
return value.replace(RE_ATTRIBUTE_ESCAPE, char => attributeEscapes[/** @type {'"' | '&' | '\u00A0'} */ (char)]);
}
// Validators
/**
* @param {string} text
* @param {ProcessedOptions} options
*/
function isIgnoredComment(text, options) {
for (const pattern of options.ignoreCustomComments) {
if (pattern.test(text)) {
return true;
}
}
return false;
}
/**
* @param {string} attrName
* @param {{customEventAttributes?: RegExp[]}} options
* @param {string} [attrNameOut] - The name as written, for the patterns
*/
function isEventAttribute(attrName, options, attrNameOut = attrName) {
const patterns = options.customEventAttributes;
if (patterns) {
for (const pattern of patterns) {
if (pattern.test(attrNameOut)) {
return true;
}
}
return false;
}
return RE_EVENT_ATTR_DEFAULT.test(attrName);
}
/** @param {string} value */
function canRemoveAttributeQuotes(value) {
// https://mathiasbynens.be/notes/unquoted-attribute-values
return RE_CAN_REMOVE_ATTR_QUOTES.test(value);
}
/**
* @param {HTMLAttribute[]} attributes
* @param {string} attribute
*/
function attributesInclude(attributes, attribute) {
for (const attr of attributes) {
if (attr.name.toLowerCase() === attribute) {
return true;
}
}
return false;
}
/**
* Remove duplicate attributes from an attribute list.
* Per HTML spec, when an attribute appears multiple times, the first occurrence wins.
* Duplicate attributes result in invalid HTML, so only the first is kept.
* @param {HTMLAttribute[]} attrs - Array of attribute objects with `name` property
* @param {boolean} caseSensitive - Whether to compare names case-sensitively (for XML/SVG)
* @returns {HTMLAttribute[]} Deduplicated attribute array (modifies in place and returns)
*/
function deduplicateAttributes(attrs, caseSensitive) {
if (attrs.length < 2) {
return attrs;
}
// Most tags hold a few attributes, which are faster compared with each other than in a set
const keys = attrs.map(attr => caseSensitive ? attr.name : attr.name.toLowerCase());
let hasDuplicates = false;
if (keys.length <= 8) {
for (let i = 1; i < keys.length && !hasDuplicates; i++) {
hasDuplicates = keys.lastIndexOf(/** @type {string} */ (keys[i]), i - 1) !== -1;
}
} else {
hasDuplicates = new Set(keys).size !== keys.length;
}
if (!hasDuplicates) {
return attrs;
}
const seen = new Set();
let writeIndex = 0;
for (let i = 0; i < attrs.length; i++) {
const key = keys[i];
if (!seen.has(key)) {
seen.add(key);
attrs[writeIndex++] = /** @type {HTMLAttribute} */ (attrs[i]);
}
}
attrs.length = writeIndex;
return attrs;
}
// Names that can have a general or tag-specific default value, for the fast pre-check
// in `isAttributeRedundant` (a Set lookup beats two `Object.hasOwn` plus property reads);
// the legacy rules (`script[language|charset]`, `a[name]`) are named here explicitly
const redundantDefaultNames = new Set([...Object.keys(generalDefaults), 'language', 'charset', 'name']);
for (const defaults of Object.values(tagDefaults)) {
for (const name of Object.keys(defaults)) {
redundantDefaultNames.add(name);
}
}
/**
* Whether `xmlns` or `xmlns:xlink` repeats the namespace HTML puts the element or its
* attributes in anyway
* @param {string} attrName - In lowercase
* @param {string} attrValue
* @param {ProcessedOptions} options
*/
function isNamespaceRedundant(attrName, attrValue, options) {
// XML, which SVGO reads, needs the declarations, which go after it (see `minifySVG`)
if (options.insideSVG && options.minifySVG) {
return false;
}
if (attrName === 'xmlns') {
if (!options.insideForeignContent) {
return attrValue === namespaceHTML;
}
return attrValue === (options.namespaceForeign === 'math' ? namespaceMathML : namespaceSVG);
}
return Boolean(options.insideForeignContent) && attrValue === namespaceXLink;
}
/**
* Whether `target=_self` is redundant, which it is not where a `base` element may set another
* target—as far as the document shows, which partial markup does not
* @param {string} attrValue
* @param {ProcessedOptions} options
*/
function isTargetSelfRedundant(attrValue, options) {
// Matched as is, as padded it names a browsing context of its own
if (options.partialMarkup || attrValue.toLowerCase() !== '_self') {
return false;
}
// Written as markup or within a value
const state = options.baseState;
return !state || !(state.hasBase ??= RE_BASE_ELEMENT.test(state.source));
}
/**
* The attribute names `style` elements in `source` select on, in lowercase
* @param {string} source
* @returns {Set<string>}
*/
function findSelectedAttributes(source) {
/** @type {Set<string>} */
const names = new Set();
if (!RE_STYLE_ELEMENT.test(source)) {
return names;
}
const addSelected = (/** @type {number} */ start, /** @type {number} */ end) => {
for (const selector of source.slice(start, end).toLowerCase().matchAll(RE_ATTR_SELECTOR)) {
names.add(/** @type {string} */ (selector[1]));
}
};
// Scanned rather than matched, as a lazy pattern is quadratic on `style` tags left open
let start = -1;
RE_STYLE_TAG.lastIndex = 0;
for (let match = RE_STYLE_TAG.exec(source); match; match = RE_STYLE_TAG.exec(source)) {
if (match[0][1] !== '/') {
if (start === -1) start = match.index;
} else if (start !== -1) {
addSelected(start, match.index);
start = -1;
}
}
// Browsers apply a `style` element the document ends in, but not one that is script text,
// with a script’s end tag after it (without, `<script` before it is text of some other kind)
if (start !== -1) {
const before = source.slice(0, start).toLowerCase();
if (before.lastIndexOf('<script') <= before.lastIndexOf('</script') || !source.slice(start).toLowerCase().includes('</script')) {
addSelected(start, source.length);
}
}
return names;
}
/**
* Whether a style sheet of the document selects on the attribute, which removing it would break
* @param {string} attrName
* @param {ProcessedOptions} options
*/
function isAttributeSelected(attrName, options) {
const state = options.baseState;
return state !== undefined && (state.selectedAttrs ??= findSelectedAttributes(state.source)).has(attrName.toLowerCase());
}
/**
* @param {string} tag - In lowercase
* @param {string} attrName - In lowercase
* @param {string} attrValue
* @param {HTMLAttribute[]} attrs
*/
function isAttributeRedundantSVG(tag, attrName, attrValue, attrs) {
const defaults = Object.hasOwn(tagDefaultsSVG, tag)
? /** @type {Record<string, string | string[]>} */ (/** @type {Record<string, unknown>} */ (tagDefaultsSVG)[tag])
: undefined;
const value = defaults && Object.hasOwn(defaults, attrName) ? defaults[attrName] : undefined;
if (value === undefined) {
return false;
}
if (svgElementsInheritingByReference.has(tag) && attrs.some(a => {
const name = a.name.toLowerCase();
return name === 'href' || name === 'xlink:href';
})) {
return false;
}
attrValue = trimWhitespace(attrValue.toLowerCase());
return typeof value === 'string' ? attrValue === value : value.includes(attrValue);
}
/**
* @param {string} tag
* @param {string} attrName
* @param {string} attrValue
* @param {HTMLAttribute[]} attrs
* @param {ProcessedOptions} options
*/
function isAttributeRedundant(tag, attrName, attrValue, attrs, options) {
// Foreign names are as written (`viewBox`, `viewbox`), which the HTML parser reads alike
if (options.insideForeignContent) {
const attrNameLower = attrName.toLowerCase();
if (attrNameLower === 'xmlns' || attrNameLower === 'xmlns:xlink') {
return isNamespaceRedundant(attrNameLower, attrValue, options);
}
if (options.namespaceForeign !== 'svg') {
return false;
}
const tagLower = tag.toLowerCase();
if (tagLower === 'a' && attrNameLower === 'target') {
return isTargetSelfRedundant(attrValue, options);
}
return isAttributeRedundantSVG(tagLower, attrNameLower, attrValue, attrs);
}
if (attrName === 'xmlns') {
return isNamespaceRedundant(attrName, attrValue, options);
}
if (attrName === 'target' && targetSelfElements.has(tag)) {
return isTargetSelfRedundant(attrValue, options);
}
// Without effect in HTML (unlike in foreign content, where it’s in the XML namespace)
if (attrName === 'xml:lang') {
return true;
}
// Fast path: Check if this element–attribute combination can possibly be redundant before
// normalizing the value; own properties only, so `constructor` has no default
if (!redundantDefaultNames.has(attrName)) {
return false;
}
const generalDefault = Object.hasOwn(generalDefaults, attrName)
? /** @type {Record<string, string>} */ (generalDefaults)[attrName]
: undefined;
const tagAttrDefaults = Object.hasOwn(tagDefaults, tag)
? /** @type {Record<string, string>} */ (/** @type {Record<string, unknown>} */ (tagDefaults)[tag])
: undefined;
const tagDefault = tagAttrDefaults && Object.hasOwn(tagAttrDefaults, attrName) ? tagAttrDefaults[attrName] : undefined;
// As written, for browsers match fragments case-sensitively and without trimming
if (tag === 'a' && attrName === 'name') {
const id = attrs.find(attr => attr.name.toLowerCase() === 'id');
const idValue = id?.value ?? '';
// With `decodeEntities`, the name is decoded by now, the ID isn’t
if (id === undefined || (options.decodeEntities && idValue.indexOf('&') !== -1)) {
return false;
}
return options.collapseAttributeWhitespace ? collapseAttributeValue(idValue) === collapseAttributeValue(attrValue) : idValue === attrValue;
}
const isLegacyAttr = tag === 'script' && (attrName === 'language' || attrName === 'charset');
// Without a default for this very attribute, nor a legacy rule, the value cannot be redundant
if (generalDefault === undefined && tagDefault === undefined && !isLegacyAttr) {
return false;
}
// Value needs to be checked, so normalize it
attrValue = attrValue ? trimWhitespace(attrValue.toLowerCase()) : '';
if (tag === 'script' && attrName === 'language' && attrValue === 'javascript') {
return true;
}
if (tag === 'script' && attrName === 'charset' && !attributesInclude(attrs, 'src')) {
return true;
}
if (tag === 'ol' && attrName === 'start' && attributesInclude(attrs, 'reversed')) {
return false;
}
return attrValue === generalDefault || attrValue === tagDefault;
}
// Types are matched as written, as browsers do:
// With parameters, a JavaScript type makes a data block
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
function isScriptTypeAttribute(attrValue = '') {
attrValue = trimWhitespace(attrValue).toLowerCase();
return attrValue === '' || executableScriptsMimetypes.has(attrValue);
}
function keepScriptTypeAttribute(attrValue = '') {
return keepScriptsMimetypes.has(trimWhitespace(attrValue).toLowerCase());
}
// Whether a `type` makes a classic script, which it can then be left out for
function isClassicScriptType(attrValue = '') {
return isScriptTypeAttribute(attrValue) && !keepScriptTypeAttribute(attrValue);
}
/**
* @param {string} tag
* @param {HTMLAttribute[]} attrs
*/
function isExecutableScript(tag, attrs) {
if (tag !== 'script') {
return false;
}
for (const attr of attrs) {
if (attr.name.toLowerCase() === 'type') {
return isScriptTypeAttribute(attr.value);
}
}
return true;
}
function isStyleLinkTypeAttribute(attrValue = '') {
attrValue = trimWhitespace(attrValue).toLowerCase();
return attrValue === '' || attrValue === 'text/css';
}
/**
* @param {string} tag
* @param {HTMLAttribute[]} attrs
*/
function isStyleElement(tag, attrs) {
if (tag !== 'style') {
return false;
}
for (const attr of attrs) {
if (attr.name.toLowerCase() === 'type') {
return isStyleLinkTypeAttribute(attr.value);
}
}
return true;
}
/**
* Whether an attribute collapses to its name; lower-cases the value only for the few names
* that depend on it
*
* @param {string} name - In lowercase
* @param {string} attrValue
* @param {string} tag
* @param {string[]} markers - What custom fragment and `htmlmin:ignore` placeholders hold
*/
function collapsesToBooleanName(name, attrValue, tag, markers) {
const simple = isSimpleBoolean.has(name);
if (!simple && name !== 'hidden' && name !== 'draggable' && !collapsibleValues.has(name)) {
return false;
}
// Custom elements define what their attributes mean, and `marquee` counts its loops
if (tag.includes('-') || (name === 'loop' && tag.toLowerCase() === 'marquee')) {
return false;
}
// Template code and ignored markup are not the minifier’s to remove
if (markers.some(marker => attrValue.indexOf(marker) !== -1)) {
return false;
}
if (simple) {
return true;
}
const values = collapsibleValues.get(name);
if (values) {
return values.has(attrValue.toLowerCase());
}
// What a reference decodes to, the value as written doesn’t show
if ((name === 'hidden' || name === 'draggable') && attrValue.indexOf('&') !== -1) {
return false;
}
// Any other value means the hidden state, which the bare attribute does, too
if (name === 'hidden') {
return attrValue.toLowerCase() !== 'until-found';
}
return name === 'draggable' && !isBooleanValue.has(attrValue.toLowerCase());
}
const uriTypeAttributes = new Map([
['a', new Set(['href'])],
['area', new Set(['href'])],
['audio', new Set(['src'])],
['base', new Set(['href'])],
['blockquote', new Set(['cite'])],
['button', new Set(['formaction'])],
['del', new Set(['cite'])],
['embed', new Set(['src'])],
['form', new Set(['action'])],
['frame', new Set(['longdesc', 'src'])],
['head', new Set(['profile'])],
['iframe', new Set(['src'])],
['img', new Set(['longdesc', 'src', 'usemap'])],
['input', new Set(['formaction', 'src', 'usemap'])],
['ins', new Set(['cite'])],
['link', new Set(['href'])],
['object', new Set(['classid', 'codebase', 'data', 'usemap'])],
['q', new Set(['cite'])],
['script', new Set(['src'])],
['source', new Set(['src'])],
['track', new Set(['src'])],
['video', new Set(['poster', 'src'])]
]);
/**
* @param {string} attrName
* @param {string} tag
*/
function isUriTypeAttribute(attrName, tag) {
const set = uriTypeAttributes.get(tag);
return set ? set.has(attrName) : false;
}
const numberTypeAttributes = new Map([
['a', new Set(['tabindex'])],
['area', new Set(['tabindex'])],
['button', new Set(['tabindex'])],
['col', new Set(['span'])],
['colgroup', new Set(['span'])],
['input', new Set(['maxlength', 'tabindex'])],
['object', new Set(['tabindex'])],
['select', new Set(['size', 'tabindex'])],
['td', new Set(['colspan', 'rowspan'])],
['textarea', new Set(['cols', 'rows', 'tabindex'])],
['th', new Set(['colspan', 'rowspan'])]
]);
/**
* @param {string} attrName
* @param {string} tag
*/
function isNumberTypeAttribute(attrName, tag) {
const set = numberTypeAttributes.get(tag);
return set ? set.has(attrName) : false;
}
/**
* @param {string} tag
* @param {HTMLAttribute[]} attrs
* @param {string} value
*/
function isLinkType(tag, attrs, value) {
if (tag !== 'link') return false;
const needle = String(value).toLowerCase();
for (const attr of attrs) {
if (attr.name.toLowerCase() === 'rel') {
const tokens = String(attr.value).toLowerCase().split(/\s+/);
if (tokens.includes(needle)) return true;
}
}
return false;
}
/**
* @param {string} tag
* @param {HTMLAttribute[]} attrs
* @param {string} attrName
*/
function isMediaQuery(tag, attrs, attrName) {
return attrName === 'media' && (isLinkType(tag, attrs, 'stylesheet') || isStyleElement(tag, attrs));
}
/**
* @param {string} attrName
* @param {string} tag
*/
function isSrcset(attrName, tag) {
return (attrName === 'srcset' && srcsetElements.has(tag)) ||
(attrName === 'imagesrcset' && tag === 'link');
}
// Whitespace (as `\s`) and comma for the `srcset` parser, with ASCII checked by code first
/** @param {number} code */
function isWsChar(code) {
return code === 32 || (code >= 9 && code <= 13) ||
(code > 127 && RE_WS_CHAR.test(String.fromCharCode(code)));
}
/** @param {number} code */
function isWsOrComma(code) {
return code === 44 /* , */ || isWsChar(code);
}
/**
* @param {string} tag
* @param {HTMLAttribute[]} attrs
*/
function isMetaViewport(tag, attrs) {
if (tag !== 'meta') {
return false;
}
for (const attr of attrs) {
if (attr.name.toLowerCase() === 'name' && (attr.value || '').toLowerCase() === 'viewport') {
return true;
}
}
return false;
}
/**
* @param {string} tag
* @param {HTMLAttribute[]} attrs
*/
function isContentSecurityPolicy(tag, attrs) {
if (tag !== 'meta') {
return false;
}
for (const attr of attrs) {
if (attr.name.toLowerCase() === 'http-equiv' && (attr.value || '').toLowerCase() === 'content-security-policy') {
return true;
}
}
return false;
}
/**
* Whether a `meta` element has no effect in any current browser, holding no more than the
* `http-equiv` or `name` that says so, and `content`
* @param {HTMLAttribute[]} attrs - Deduplicated
* @param {string[]} markers - What custom fragment and `htmlmin:ignore` placeholders hold
*/
function isMetaWithoutEffect(attrs, markers) {
let hasKey = false;
for (const attr of attrs) {
const name = attr.name.toLowerCase();
const value = attr.value ?? '';
if (attr.customOpen || attr.customClose || markers.some(marker => value.indexOf(marker) !== -1)) {
return false;
}
if (name === 'http-equiv' || name === 'name') {
if (!(name === 'name' ? metaNamesNoEffect : metaHttpEquivNoEffect).has(value.toLowerCase())) {
return false;
}
hasKey = true;
} else if (name !== 'content') {
return false;
}
}
return hasKey;
}
/**
* The charset a `content` value declares, as browsers extract it, if any
* https://html.spec.whatwg.org/multipage/urls-and-fetching.html#algorithm-for-extracting-a-character-encoding-from-a-meta-element
* @param {string} value
* @returns {string | undefined}
*/
function extractCharset(value) {
const re = /charset[\t\n\f\r ]*(=)?[\t\n\f\r ]*/gi;
let match;
while ((match = re.exec(value))) {
if (!match[1]) {
continue;
}
const start = re.lastIndex;
const quote = value.charAt(start);
if (quote === '"' || quote === "'") {
const end = value.indexOf(quote, start + 1);
return end === -1 ? undefined : value.slice(start + 1, end);
}
return value.slice(start).split(/[\t\n\f\r ;]/, 1)[0];
}
return undefined;
}
/**
* Replace a `meta` element’s `http-equiv=Content-Type` and `content` with the `charset` they
* declare, which browsers read the same
* @param {HTMLAttribute[]} attrs - Deduplicated; changed in place
* @param {string[]} markers - What custom fragment and `htmlmin:ignore` placeholders hold
*/
function replaceContentTypePragma(attrs, markers) {
if (attrs.length !== 2 || attrs.some(attr => attr.customOpen || attr.customClose)) {
return;
}
const httpEquiv = attrs.find(attr => attr.name.toLowerCase() === 'http-equiv');
const content = attrs.find(attr => attr.name.toLowerCase() === 'content');
if (!httpEquiv || !content || (httpEquiv.value ?? '').toLowerCase() !== 'content-type') {
return;
}
const value = content.value ?? '';
// Character references are left to the attribute, which browsers decode before extracting
const charset = value.indexOf('&') !== -1 || markers.some(marker => value.indexOf(marker) !== -1) ? undefined : extractCharset(value);
if (charset && trimWhitespace(charset)) {
attrs.splice(0, 2, { ...content, name: 'charset', value: charset });
}
}
/**
* A `rel` value without repeated keywords, nor ones others imply
* @param {string} tag - In lowercase
* @param {string} attrValue
*/
function cleanRelKeywords(tag, attrValue) {
const keywords = trimWhitespace(attrValue).split(RE_ATTR_WS_COLLAPSE);
const seen = new Set();
for (const keyword of keywords) {
seen.add(keyword.toLowerCase());
}
// Only Internet Explorer needed `shortcut`; `noreferrer` implies `noopener` (as does
// `target=_blank`, but only since Chrome 88, Firefox 79, and Safari 12.1 [TBC])
const implied = tag === 'link' && seen.has('icon')
? 'shortcut'
: (tag === 'a' || tag === 'area' || tag === 'form') && seen.has('noreferrer') ? 'noopener' : '';
if (seen.size === keywords.length && !seen.has(implied)) {
return attrValue;
}
seen.clear();
return keywords.filter(keyword => {
const keywordLower = keyword.toLowerCase();
if (keywordLower === implied || seen.has(keywordLower)) {
return false;
}
seen.add(keywordLower);
return true;
}).join(' ');
}
/**
* @param {string} tag
* @param {string} attrName
* @param {string | undefined} attrValue
* @param {{removeEmptyAttributes?: boolean | Function}} options
* @param {string} [tagOut] - The tag name as written, for the hook
* @param {string} [attrNameOut] - The attribute name as written, for the hook
*/
function canDeleteEmptyAttribute(tag, attrName, attrValue, options, tagOut = tag, attrNameOut = attrName) {
const isValueEmpty = !attrValue || attrValue.trim() === '';
if (!isValueEmpty) {
return false;
}
if (typeof options.removeEmptyAttributes === 'function') {
return options.removeEmptyAttributes(attrNameOut, tagOut);
}
return (tag === 'input' && attrName === 'value') || RE_EMPTY_ATTRIBUTE.test(attrName);
}
/**
* The name to write and to hand to hooks: as in the source for HTML names under
* `caseSensitive`, as named otherwise (foreign names are named as written anyway)
* @param {HTMLAttribute} attr
* @param {string} attrName
* @param {ProcessedOptions} options
*/
function nameAttrOut(attr, attrName, options) {
return options.namesAsWritten && options.name === lowercase ? attr.name : attrName;
}
/**
* Whether `removeEmptyAttributes` removes the attribute
* @param {string} tag
* @param {string} attrName
* @param {string | undefined} attrValue
* @param {ProcessedOptions} options
* @param {string} [tagOut]
* @param {string} [attrNameOut]
*/
function removesEmptyAttribute(tag, attrName, attrValue, options, tagOut = tag, attrNameOut = attrName) {
return Boolean(options.removeEmptyAttributes) &&
canDeleteEmptyAttribute(tag, attrName, attrValue, options, tagOut, attrNameOut) &&
!isAttributeSelected(attrName, options);
}
/**
* @param {string} name
* @param {HTMLAttribute[]} attrs
*/
function hasAttrName(name, attrs) {
for (const attr of attrs) {
if (attr.name === name) {
return true;
}
}
return false;
}
// Cleaners
const collapseAttributeWhitespaceExempt = new Set(['pattern', 'placeholder', 'title']);
// `value` whitespace matters only on form-submission and machine-readable elements
const valueWhitespaceExemptElements = new Set(['button', 'data', 'input', 'option', 'param']);
/**
* @param {string} value
* @param {string[]} [markers] - What custom fragment and `htmlmin:ignore` placeholders hold
* @returns {string}
*/
function collapseAttributeValue(value, markers = []) {
// Fast path: Only process if whitespace exists (avoids regex overhead on clean values)
if (!RE_ATTR_WS_CHECK.test(value)) {
return value;
}
value = trimWhitespace(value);
if (!markers.some(marker => value.indexOf(marker) !== -1)) {
return value.replace(RE_ATTR_WS_COLLAPSE, ' ');
}
// Placeholders come padded with a tab on each side, which restoring them drops; as spaces,
// they would stay, while other tabs (e.g., decoded ones) must become a space that stays
return value.replace(RE_ATTR_WS_COLLAPSE, (run, offset) => {
if (!RE_TABS_ONLY.test(run)) {
return ' ';
}
const paddingBefore = markers.some(marker => value.endsWith(marker, offset)) ? '\t' : '';
const paddingAfter = markers.some(marker => value.startsWith(marker, offset + run.length)) ? '\t' : '';
return run.length > paddingBefore.length + paddingAfter.length ? paddingBefore + ' ' + paddingAfter : run;
});
}
/**
* Drop repeated names from a whitespace-separated class list, keeping the first of each.
* @param {string} value
* @returns {string}
*/
function dedupeClassNames(value) {
if (!RE_ATTR_WS_CHECK.test(value)) {
return value;
}
const names = value.split(RE_ATTR_WS_COLLAPSE);
// As with attributes, a short list is faster checked name by name than through a set
if (names.length <= 16) {
for (let i = 1; i < names.length; i++) {
if (names.lastIndexOf(/** @type {string} */ (names[i]), i - 1) !== -1) {
return [...new Set(names)].join(' ');
}
}
return value;
}
const unique = new Set(names);
return unique.size === names.length ? value : [...unique].join(' ');
}
// Returns the cleaned attribute value directly (sync) or as a Promise (async);
// callers must handle both cases—use `isThenable()` to distinguish
/**
* @param {string} tag
* @param {string} attrName
* @param {string} attrValue
* @param {ProcessedOptions} options
* @param {HTMLAttribute[]} attrs
* @param {Function} minifyHTMLSelf
* @param {string[]} [markers] - What custom fragment and `htmlmin:ignore` placeholders hold
* @param {string} [attrNameOut] - The name as written, for the patterns
*/
function cleanAttributeValue(tag, attrName, attrValue, options, attrs, minifyHTMLSelf, markers = [], attrNameOut = attrName) {
const isEventAttr = isEventAttribute(attrName, options, attrNameOut);
// Special spaces (no-break space, hair space, etc.) stay, for consistency
// with `collapseWhitespace`; an `annotation-xml` encoding is matched as written,
// and with spaces taken out could make the element hold HTML
if (options.collapseAttributeWhitespace && !collapseAttributeWhitespaceExempt.has(attrName) && !(attrName === 'value' && valueWhitespaceExemptElements.has(tag)) && !(attrName.toLowerCase() === 'encoding' && tag.toLowerCase() === 'annotation-xml') && !isEventAttr) {
attrValue = collapseAttributeValue(attrValue, markers);
}
if (isEventAttr) {
attrValue = trimWhitespace(attrValue).replace(/^javascript:\s*/i, '');
// Browsers decode attribute values before running event-handler JS—
// decode first so the minifier gets valid JavaScript
if (!options.decodeEntities && options.minifyJS !== identity && attrValue.indexOf('&') !== -1) {
return getDecodeHTMLAttribute().then(decode => {
const decoded = decode(attrValue);
const result = options.minifyJS(decoded, true);
const reEncode = (/** @type {string} */ v) => (v && v.indexOf('&') !== -1) ? v.replace(RE_AMP_REFERENCE_ATTR, '&') : v;
if (isThenable(result)) {
return result.then(reEncode, (/** @type {Error} */ err) => {
if (!options.continueOnMinifyError) throw err;
options.log(err);
return attrValue;
});
}
return reEncode(result);
});
}
const result = options.minifyJS(attrValue, true);
if (isThenable(result)) {
return result.catch((/** @type {Error} */ err) => {
if (!options.continueOnMinifyError) throw err;
options.log(err);
return attrValue;
});
}
return result;
}
if (attrName === 'class') {
attrValue = trimWhitespace(attrValue);
// Names around a fragment placeholder (`ignoreCustomFragments`, `htmlmin:ignore`)
// may not repeat once a template renders
const holdsFragment = markers.some(marker => attrValue.indexOf(marker) !== -1);
if (options.sortClassNames) {
// `createSortFns` has replaced any truthy non-function value by now
attrValue = /** @type {(value: string) => string} */ (options.sortClassNames)(attrValue);
} else {
attrValue = collapseWhitespaceAll(attrValue);
}
return holdsFragment ? attrValue : dedupeClassNames(attrValue);
}
if (isUriTypeAttribute(attrName, tag)) {
attrValue = trimWhitespace(attrValue);
if (isLinkType(tag, attrs, 'canonical')) {
return attrValue;
}
const result = options.minifyURLs(attrValue);
if (isThenable(result)) {
return result
.then((/** @type {unknown} */ out) => typeof out === 'string' ? out : attrValue)
.catch((/** @type {Error} */ err) => {
if (!options.continueOnMinifyError) throw err;
options.log(err);
return attrValue;
});
}
return typeof result === 'string' ? result : attrValue;
}
if (isNumberTypeAttribute(attrName, tag)) {
return trimWhitespace(attrValue);
}
if (attrName === 'style') {
attrValue = trimWhitespace(attrValue);
if (attrValue) {
if (attrValue.endsWith(';') && !/&#?[0-9a-zA-Z]+;$/.test(attrValue)) {
attrValue = attrValue.replace(/\s*;$/, ';');
}
const originalAttrValue = attrValue;
const cssResult = options.minifyCSS(attrValue, 'inline', options.cssContext);
if (isThenable(cssResult)) {
return cssResult
.then((/** @type {string} */ minified) => {
// CSS of nothing but properties without values (`color:`, `margin:;padding:`) is empty
if (minified && /^(?:[a-z-]+:[;\s]*)+$/i.test(minified)) return '';
return minified;
})
.catch((/** @type {Error} */ err) => {
if (!options.continueOnMinifyError) throw err;
options.log(err);
return originalAttrValue;
});
}
// Sync path (`minifyCSS` disabled—identity function)
if (cssResult && /^(?:[a-z-]+:[;\s]*)+$/i.test(cssResult)) return '';
return cssResult ?? attrValue;
}
return attrValue;
}
if (isSrcset(attrName, tag)) {
// Split into image candidate strings following the spec parsing algorithm
// (https://html.spec.whatwg.org/multipage/images.html#parsing-a-srcset-attribute);
// a naive split on commas would corrupt URLs that contain commas
const value = trimWhitespace(attrValue);
/** @type {string[]} */
const candidates = [];
let pos = 0;
while (pos < value.length) {
// Skip whitespace and separator commas
while (pos < value.length && isWsOrComma(value.charCodeAt(pos))) pos++;
if (pos >= value.length) break;
const start = pos;
// URL: a run of non-whitespace characters (which may contain commas)
while (pos < value.length && !isWsChar(value.charCodeAt(pos))) pos++;
if (value.charAt(pos - 1) === ',') {
// Trailing comma(s) end the candidate—a URL without descriptor
candidates.push(value.slice(start, pos).replace(/,+$/, ''));
continue;
}
// Descriptor: everything up to the next comma outside parentheses
let inParens = false;
while (pos < value.length) {
const code = value.charCodeAt(pos);
if (!inParens && code === 44 /* , */) break;
if (code === 40 /* ( */) inParens = true;
else if (code === 41 /* ) */) inParens = false;
pos++;
}
candidates.push(trimWhitespace(value.slice(start, pos)));
}
const processed = candidates.map(candidate => {
let url = candidate;
let descriptor = '';
const match = candidate.match(/\s+([1-9][0-9]*w|[0-9]+(?:\.[0-9]+)?x)$/);
if (match) {
url = url.slice(0, -match[0].length);
const group = match[1] ?? '';
const num = +group.slice(0, -1);
const suffix = group.slice(-1);
if (num !== 1 || suffix !== 'x') {
descriptor = ' ' + num + suffix;
}
}
const out = options.minifyURLs(url);
if (isThenable(out)) {
return out
.then((/** @type {unknown} */ result) => (typeof result === 'string' ? result : url) + descriptor)
.catch((/** @type {Error} */ err) => {
if (!options.continueOnMinifyError) throw err;
options.log(err);
return url + descriptor;
});
}
return (typeof out === 'string' ? out : url) + descriptor;
});
if (processed.some(isThenable)) {
return Promise.all(processed).then(results => results.join(', '));
}
return processed.join(', ');
}
if (attrName === 'rel' && options.removeRedundantAttributes && !options.insideForeignContent) {
// Which keywords a template renders, the value doesn’t show
return markers.some(marker => attrValue.indexOf(marker) !== -1) ? attrValue : cleanRelKeywords(tag, attrValue);
}
if (attrName === 'content' && isMetaViewport(tag, attrs)) {
return attrValue.replace(/\s+/g, '').replace(/[0-9]+\.[0-9]+/g, function (numString) {
// 0.90000 → 0.9
// 1.0 → 1
// 1.0001 → 1.0001 (unchanged)
return (+numString).toString();
});
}
if (attrName.toLowerCase() === 'content' && isContentSecurityPolicy(tag, attrs)) {
return collapseWhitespaceAll(attrValue);
}
if (options.customAttrCollapse && options.customAttrCollapse.test(attrNameOut)) {
return trimWhitespace(attrValue.replace(/ ?[\n\r]+ ?/g, '').replace(/\s{2,}/g, options.conservativeCollapse ? ' ' : ''));
}
if (tag === 'script' && attrName === 'type') {
return trimWhitespace(attrValue.replace(/\s*;\s*/g, ';'));
}
if (isMediaQuery(tag, attrs, attrName)) {
attrValue = trimWhitespace(attrValue);
// Only media queries with features (in parentheses) need minifying; media types like `all`,
// `screen`, or `print` are minimal already
if (!/[()]/.test(attrValue)) {
return attrValue;
}
const originalAttrValue = attrValue;
const cssResult = options.minifyCSS(attrValue, 'media', options.cssContext);
if (isThenable(cssResult)) {
return cssResult.catch((/** @type {Error} */ err) => {
if (!options.continueOnMinifyError) throw err;
options.log(err);
return originalAttrValue;
});
}
return cssResult ?? attrValue;
}
if (tag === 'iframe' && attrName === 'srcdoc') {
// Fast path: Skip if nothing would change
if (!shouldMinifyInnerHTML(options)) {
return attrValue;
}
return minifySrcdoc(attrValue, options, minifyHTMLSelf);
}
return attrValue;
}
/**
* Recursively minify the document an `iframe srcdoc` attribute holds.
*
* Browsers resolve character references before parsing `srcdoc`, so an
* entity-encoded document is decoded first (unless `decodeEntities` already
* did) and re-encoded afterwards—but only then, so a literal value passes
* through byte-identical.
*
* @param {string} attrValue
* @param {ProcessedOptions} options
* @param {Function} minifyHTMLSelf
* @returns {Promise<string>}
*/
async function minifySrcdoc(attrValue, options, minifyHTMLSelf) {
let markup = attrValue;
let wasEncoded = false;
if (!options.decodeEntities && attrValue.indexOf('&') !== -1) {
const decode = await getDecodeHTMLAttribute();
markup = decode(attrValue);
wasEncoded = markup !== attrValue;
}
// The inner document sees none of the parent’s markup, so its `base` element is its own,
// and its style sheets minify against the symbols the `srcdoc` content references itself
const srcdocOptions = { ...options, baseState: { hasBase: undefined, source: markup } };
if (options.removeUnusedCSS && RE_STYLE_ELEMENT.test(markup)) {
const decode = markup.indexOf('&') !== -1 ? await getDecodeHTMLAttribute() : undefined;
srcdocOptions.cssContext = {
warned: options.cssContext ? options.cssContext.warned : new Set(),
...collectUsage(markup, options.removeUnusedCSS.scripts, /** @type {((text: string) => string) | undefined} */ (decode))
};
}
try {
const minified = await minifyHTMLSelf(markup, srcdocOptions, true);
return wasEncoded ? escapeAttribute(minified) : minified;
} catch (err) {
if (!options.continueOnMinifyError) throw err;
options.log(/** @type {Error} */ (err));
return attrValue;
}
}
/**
* Choose appropriate quote character for an attribute value
* @param {string} attrValue - The attribute value
* @param {{quoteCharacter?: string}} options - Minifier options
* @returns {string} The chosen quote character (`"` or `'`)
*/
function chooseAttributeQuote(attrValue, options) {
if (typeof options.quoteCharacter !== 'undefined') {
return options.quoteCharacter === '\'' ? '\'' : '"';
}
// Count quotes in a single pass
let apos = 0, quot = 0;
for (let i = 0; i < attrValue.length; i++) {
if (attrValue[i] === "'") apos++;
else if (attrValue[i] === '"') quot++;
}
return apos < quot ? '\'' : '"';
}
// Returns the normalized attribute object directly (sync) or as a Promise (async);
// callers must handle both cases—use `isThenable()` to distinguish
/**
* @param {HTMLAttribute} attr
* @param {HTMLAttribute[]} attrs
* @param {string} tag
* @param {string} tagOut - The tag name as written, for hooks
* @param {ProcessedOptions} options
* @param {Function} minifyHTML
* @param {string[]} [markers] - What custom fragment and `htmlmin:ignore` placeholders hold
*/
function normalizeAttr(attr, attrs, tag, tagOut, options, minifyHTML, markers) {
const attrName = options.name(attr.name);
const attrNameOut = nameAttrOut(attr, attrName, options);
const attrValue = attr.value;
// Entity decoding requires a lazy import—async only while that import is unresolved
if (options.decodeEntities && attrValue && attrValue.indexOf('&') !== -1) {
if (decodeHTMLAttributeFn) {
return normalizeAttrContinue(attrName, attrNameOut, decodeHTMLAttributeFn(attrValue), attr, attrs, tag, tagOut, options, minifyHTML, markers);
}
return getDecodeHTMLAttribute().then(decode => {
return normalizeAttrContinue(attrName, attrNameOut, decode(attrValue), attr, attrs, tag, tagOut, options, minifyHTML, markers);
});
}
return normalizeAttrContinue(attrName, attrNameOut, attrValue, attr, attrs, tag, tagOut, options, minifyHTML, markers);
}
// Internal: Handles attribute normalization after entity decoding (if any)
/**
* @param {string} attrName
* @param {string} attrNameOut
* @param {string | undefined} attrValue
* @param {HTMLAttribute} attr
* @param {HTMLAttribute[]} attrs
* @param {string} tag
* @param {string} tagOut
* @param {ProcessedOptions} options
* @param {Function} minifyHTML
* @param {string[]} [markers] - What custom fragment and `htmlmin:ignore` placeholders hold
*/
function normalizeAttrContinue(attrName, attrNameOut, attrValue, attr, attrs, tag, tagOut, options, minifyHTML, markers) {
if (((options.removeRedundantAttributes &&
isAttributeRedundant(tag, attrName, attrValue ?? '', attrs, options)) ||
(options.removeDefaultTypeAttributes && attrName === 'type' && (
((tag === 'style' || tag === 'link') && isStyleLinkTypeAttribute(attrValue)) ||
(tag === 'script' && isClassicScriptType(attrValue))
))) && !isAttributeSelected(attrName, options)) {
return;
}
if (attrValue) {
const cleaned = cleanAttributeValue(tag, attrName, attrValue, options, attrs, minifyHTML, markers, attrNameOut);
if (isThenable(cleaned)) {
return cleaned.then((/** @type {string | undefined} */ v) => normalizeAttrFinish(attrName, attrNameOut, v, attr, tag, tagOut, options));
}
return normalizeAttrFinish(attrName, attrNameOut, cleaned, attr, tag, tagOut, options);
}
return normalizeAttrFinish(attrName, attrNameOut, attrValue, attr, tag, tagOut, options);
}
// Internal: Final checks and result assembly after value cleaning
/**
* @param {string} attrName
* @param {string} attrNameOut
* @param {string | undefined} attrValue
* @param {HTMLAttribute} attr
* @param {string} tag
* @param {string} tagOut
* @param {ProcessedOptions} options
*/
function normalizeAttrFinish(attrName, attrNameOut, attrValue, attr, tag, tagOut, options) {
if (removesEmptyAttribute(tag, attrName, attrValue, options, tagOut, attrNameOut)) {
return;
}
if (attrValue && options.insideSVG && options.minifySVG) {
attrValue = escapeXML(attrValue, true);
} else if (options.decodeEntities && attrValue) {
if (attrValue.indexOf('&') !== -1) {
attrValue = attrValue.replace(RE_AMP_REFERENCE_ATTR, '&');
}
if (attrValue.indexOf('\r') !== -1) {
attrValue = attrValue.replace(RE_CR, ' ');
}
}
return {
attr,
name: attrNameOut,
value: attrValue
};
}
/**
* @param {{name: string, value: string | undefined, attr: HTMLAttribute}} normalized
* @param {string} tag
* @param {string | boolean | undefined} hasUnarySlash
* @param {ProcessedOptions} options
* @param {boolean} isLast
* @param {string | undefined} uidAttr
* @param {string[]} markers - What custom fragment and `htmlmin:ignore` placeholders hold
*/
function buildAttr(normalized, tag, hasUnarySlash, options, isLast, uidAttr, markers) {
const attrName = normalized.name;
let attrValue = normalized.value;
const attr = normalized.attr;
let attrQuote = attr.quote;
const readAsXML = Boolean(options.insideSVG) && Boolean(options.minifySVG);
// SVGO reads the whole SVG block as XML, where every attribute carries a value
if (readAsXML && typeof attrValue === 'undefined') {
attrValue = '';
}
// An attribute written as its name alone skips the quoting work below
if (typeof attrValue === 'undefined' ||
(options.collapseBooleanAttributes && !options.insideForeignContent && collapsesToBooleanName(options.namesAsWritten ? attrName.toLowerCase() : attrName, attrValue ?? '', tag, markers)) ||
(options.collapseEmptyAttributes && attrValue === '' && (attr.customAssign ?? '=') === '=')) {
return attr.customOpen + attrName + (isLast ? '' : ' ') + attr.customClose;
}
const shouldAddQuotes = typeof attrValue !== 'undefined' && (
// If `removeAttributeQuotes` is enabled, add quotes only if they can’t be removed
(options.removeAttributeQuotes && ((uidAttr ? attrValue.indexOf(uidAttr) !== -1 : false) || !canRemoveAttributeQuotes(attrValue))) ||
// If `removeAttributeQuotes` is not enabled, preserve original quote style, or add
// quotes if value requires them
(!options.removeAttributeQuotes && (attrQuote !== '' || !canRemoveAttributeQuotes(attrValue) ||
// XML quotes every attribute value
readAsXML ||
// With `removeTagWhitespace`, unquoted values that aren’t last get a space added, which can
// create ambiguous or invalid HTML—add quotes to be safe
(options.removeTagWhitespace && attrQuote === '' && !isLast)))
);
let emittedAttrValue;
if (shouldAddQuotes) {
attrValue = attrValue ?? '';
if (!options.preventAttributesEscaping) {
// Normal mode: Choose the quote type that minimizes escaping, unless the original quotes are
// kept and need no escaping
const needsEscaping = (attrQuote === '"' && attrValue.indexOf('"') !== -1) || (attrQuote === "'" && attrValue.indexOf("'") !== -1);
if (options.removeAttributeQuotes || typeof options.quoteCharacter !== 'undefined' || needsEscaping || attrQuote === '') {
attrQuote = chooseAttributeQuote(attrValue, options);
}
// `indexOf` first, as values rarely hold the quote and as it’s cheaper than `replace`
if (attrQuote === '"') {
if (attrValue.indexOf('"') !== -1) attrValue = attrValue.replace(/"/g, '"');
} else if (attrValue.indexOf("'") !== -1) {
attrValue = attrValue.replace(/'/g, ''');
}
} else {
// `preventAttributesEscaping` mode: Choose safe quotes but don’t escape
// except when both quote types are present—then escape to prevent invalid HTML
const hasDoubleQuote = attrValue.indexOf('"') !== -1;
const hasSingleQuote = attrValue.indexOf("'") !== -1;
// Both quote types present: Escaping is required to guarantee valid HTML delimiter matching
if (hasDoubleQuote && hasSingleQuote) {
attrQuote = chooseAttributeQuote(attrValue, options);
if (attrQuote === '"') {
attrValue = attrValue.replace(/"/g, '"');
} else {
attrValue = attrValue.replace(/'/g, ''');
}
// No `quoteCharacter` set: Prefer the quote type the value doesn’t hold, default to double
} else if (typeof options.quoteCharacter === 'undefined') {
if (attrQuote === '"' && hasDoubleQuote && !hasSingleQuote) {
attrQuote = "'";
} else if (attrQuote === "'" && hasSingleQuote && !hasDoubleQuote) {
attrQuote = '"';
// If no quote character yet (empty string), choose based on content
} else if (attrQuote === '') {
if (hasSingleQuote && !hasDoubleQuote) {
attrQuote = '"';
} else if (hasDoubleQuote && !hasSingleQuote) {
attrQuote = "'";
} else {
attrQuote = '"';
}
// Fallback for invalid/unsupported attrQuote values (not `"`, `'`, or empty string):
// Choose safe default based on value content
} else if (attrQuote !== '"' && attrQuote !== "'") {
if (hasSingleQuote && !hasDoubleQuote) {
attrQuote = '"';
} else if (hasDoubleQuote && !hasSingleQuote) {
attrQuote = "'";
} else {
attrQuote = '"';
}
}
} else {
// `quoteCharacter` is explicitly set
const preferredQuote = options.quoteCharacter === '\'' ? '\'' : '"';
// If the preferred quote conflicts with value content, switch to the opposite one
if ((preferredQuote === '"' && hasDoubleQuote && !hasSingleQuote) || (preferredQuote === "'" && hasSingleQuote && !hasDoubleQuote)) {
attrQuote = preferredQuote === '"' ? "'" : '"';
} else if ((preferredQuote === '"' && hasDoubleQuote && hasSingleQuote) || (preferredQuote === "'" && hasSingleQuote && hasDoubleQuote)) {
// Both quote types present: Fall back to escaping despite `preventAttributesEscaping`
attrQuote = preferredQuote;
if (attrQuote === '"') {
attrValue = attrValue.replace(/"/g, '"');
} else {
attrValue = attrValue.replace(/'/g, ''');
}
} else {
attrQuote = preferredQuote;
}
}
}
emittedAttrValue = attrQuote + attrValue + attrQuote;
if (!isLast && !options.removeTagWhitespace) {
emittedAttrValue += ' ';
}
} else if (isLast && !hasUnarySlash) {
// Last attribute in a non-self-closing tag: No space needed
emittedAttrValue = attrValue;
} else {
// Not last attribute, or a self-closing tag: Unquoted values need a space to delimit them
emittedAttrValue = attrValue + ' ';
}
return attr.customOpen + attrName + attr.customAssign + emittedAttrValue + attr.customClose;
}
export {
// Validators
isIgnoredComment,
isExecutableScript,
isClassicScriptType,
isStyleElement,
isStyleLinkTypeAttribute,
isMetaWithoutEffect,
hasAttrName,
nameAttrOut,
removesEmptyAttribute,
// Cleaners
normalizeAttr,
buildAttr,
deduplicateAttributes,
replaceContentTypePragma
};