@ohos-ports/html-minifier-next 8.4.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,928 @@
1
+ /**
2
+ * HTML attribute parsing, decoding, and minification
3
+ */
4
+
5
+ import {
6
+ RE_EVENT_ATTR_DEFAULT,
7
+ RE_CAN_REMOVE_ATTR_QUOTES,
8
+ RE_AMP_ENTITY,
9
+ RE_ATTR_WS_CHECK,
10
+ RE_ATTR_WS_COLLAPSE,
11
+ RE_ATTR_WS_TRIM,
12
+ generalDefaults,
13
+ tagDefaults,
14
+ executableScriptsMimetypes,
15
+ keepScriptsMimetypes,
16
+ isSimpleBoolean,
17
+ isBooleanValue,
18
+ collapsibleValues,
19
+ srcsetElements,
20
+ RE_EMPTY_ATTRIBUTE,
21
+ RE_STYLE_ELEMENT
22
+ } from './constants.js';
23
+ import { trimWhitespace, collapseWhitespaceAll } from './whitespace.js';
24
+ import { shouldMinifyInnerHTML } from './options.js';
25
+ import { collectUsedSymbols } from './unused-css.js';
26
+ import { identity, isThenable } from './utils.js';
27
+
28
+ /** @import { ProcessedOptions } from './options.js' */
29
+
30
+ // Type definitions
31
+
32
+ /**
33
+ * @typedef {{ name: string, value?: string | undefined, quote?: string, customAssign?: string, customOpen?: string, customClose?: string }} HTMLAttribute
34
+ * Internal counterpart of the public typedef in htmlminifier.js—keep in sync.
35
+ */
36
+
37
+ // Lazy-load entities (used for `decodeEntities`, event-handler attribute
38
+ // decoding before `minifyJS`, and `srcdoc` decoding/re-encoding)
39
+
40
+ /** @type {Promise<Function> | undefined} */
41
+ let decodeHTMLStrictPromise;
42
+ async function getDecodeHTMLStrict() {
43
+ if (!decodeHTMLStrictPromise) {
44
+ decodeHTMLStrictPromise = import('entities').then(m => m.decodeHTMLStrict);
45
+ }
46
+ return decodeHTMLStrictPromise;
47
+ }
48
+
49
+ /** @type {Promise<Function> | undefined} */
50
+ let escapeAttributePromise;
51
+ async function getEscapeAttribute() {
52
+ if (!escapeAttributePromise) {
53
+ escapeAttributePromise = import('entities').then(m => m.escapeAttribute);
54
+ }
55
+ return escapeAttributePromise;
56
+ }
57
+
58
+ // Validators
59
+
60
+ /**
61
+ * @param {string} text
62
+ * @param {ProcessedOptions} options
63
+ */
64
+ function isIgnoredComment(text, options) {
65
+ for (const pattern of options.ignoreCustomComments) {
66
+ if (pattern.test(text)) {
67
+ return true;
68
+ }
69
+ }
70
+ return false;
71
+ }
72
+
73
+ /**
74
+ * @param {string} attrName
75
+ * @param {{customEventAttributes?: RegExp[]}} options
76
+ */
77
+ function isEventAttribute(attrName, options) {
78
+ const patterns = options.customEventAttributes;
79
+ if (patterns) {
80
+ for (const pattern of patterns) {
81
+ if (pattern.test(attrName)) {
82
+ return true;
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+ return RE_EVENT_ATTR_DEFAULT.test(attrName);
88
+ }
89
+
90
+ /** @param {string} value */
91
+ function canRemoveAttributeQuotes(value) {
92
+ // https://mathiasbynens.be/notes/unquoted-attribute-values
93
+ return RE_CAN_REMOVE_ATTR_QUOTES.test(value);
94
+ }
95
+
96
+ /**
97
+ * @param {HTMLAttribute[]} attributes
98
+ * @param {string} attribute
99
+ */
100
+ function attributesInclude(attributes, attribute) {
101
+ for (const attr of attributes) {
102
+ if (attr.name.toLowerCase() === attribute) {
103
+ return true;
104
+ }
105
+ }
106
+ return false;
107
+ }
108
+
109
+ /**
110
+ * Remove duplicate attributes from an attribute list.
111
+ * Per HTML spec, when an attribute appears multiple times, the first occurrence wins.
112
+ * Duplicate attributes result in invalid HTML, so only the first is kept.
113
+ * @param {HTMLAttribute[]} attrs - Array of attribute objects with `name` property
114
+ * @param {boolean} caseSensitive - Whether to compare names case-sensitively (for XML/SVG)
115
+ * @returns {HTMLAttribute[]} Deduplicated attribute array (modifies in place and returns)
116
+ */
117
+ function deduplicateAttributes(attrs, caseSensitive) {
118
+ if (attrs.length < 2) {
119
+ return attrs;
120
+ }
121
+
122
+ const seen = new Set();
123
+ let writeIndex = 0;
124
+
125
+ for (const attr of attrs) {
126
+ const key = caseSensitive ? attr.name : attr.name.toLowerCase();
127
+
128
+ if (!seen.has(key)) {
129
+ seen.add(key);
130
+ attrs[writeIndex++] = attr;
131
+ }
132
+ }
133
+
134
+ attrs.length = writeIndex;
135
+ return attrs;
136
+ }
137
+
138
+ /**
139
+ * @param {string} tag
140
+ * @param {string} attrName
141
+ * @param {string} attrValue
142
+ * @param {HTMLAttribute[]} attrs
143
+ */
144
+ function isAttributeRedundant(tag, attrName, attrValue, attrs) {
145
+ // Fast-path: Check if this element–attribute combination can possibly be redundant
146
+ // before doing expensive string operations
147
+
148
+ // Check if attribute name is in general defaults
149
+ const hasGeneralDefault = attrName in generalDefaults;
150
+
151
+ // Check if element has any default attributes
152
+ const tagHasDefaults = tag in tagDefaults;
153
+
154
+ // Check for legacy attribute rules (element- and attribute-specific)
155
+ const isLegacyAttr = (tag === 'script' && (attrName === 'language' || attrName === 'charset')) || (tag === 'a' && attrName === 'name');
156
+
157
+ // If none of these conditions apply, attribute cannot be redundant
158
+ if (!hasGeneralDefault && !tagHasDefaults && !isLegacyAttr) {
159
+ return false;
160
+ }
161
+
162
+ // Value needs to be checked, so normalize it
163
+ attrValue = attrValue ? trimWhitespace(attrValue.toLowerCase()) : '';
164
+
165
+ // Legacy attribute checks
166
+ if (tag === 'script' && attrName === 'language' && attrValue === 'javascript') {
167
+ return true;
168
+ }
169
+ if (tag === 'script' && attrName === 'charset' && !attributesInclude(attrs, 'src')) {
170
+ return true;
171
+ }
172
+ if (tag === 'a' && attrName === 'name' && attributesInclude(attrs, 'id')) {
173
+ return true;
174
+ }
175
+
176
+ // Check general defaults
177
+ if (hasGeneralDefault && /** @type {Record<string, string>} */ (generalDefaults)[attrName] === attrValue) {
178
+ return true;
179
+ }
180
+
181
+ // Check tag-specific defaults
182
+ return tagHasDefaults && /** @type {Record<string, string>} */ (/** @type {Record<string, unknown>} */ (tagDefaults)[tag])[attrName] === attrValue;
183
+ }
184
+
185
+ function isScriptTypeAttribute(attrValue = '') {
186
+ attrValue = trimWhitespace(attrValue.split(/;/, 2)[0] ?? '').toLowerCase();
187
+ return attrValue === '' || executableScriptsMimetypes.has(attrValue);
188
+ }
189
+
190
+ function keepScriptTypeAttribute(attrValue = '') {
191
+ attrValue = trimWhitespace(attrValue.split(/;/, 2)[0] ?? '').toLowerCase();
192
+ return keepScriptsMimetypes.has(attrValue);
193
+ }
194
+
195
+ /**
196
+ * @param {string} tag
197
+ * @param {HTMLAttribute[]} attrs
198
+ */
199
+ function isExecutableScript(tag, attrs) {
200
+ if (tag !== 'script') {
201
+ return false;
202
+ }
203
+ for (const attr of attrs) {
204
+ if (attr.name.toLowerCase() === 'type') {
205
+ return isScriptTypeAttribute(attr.value);
206
+ }
207
+ }
208
+ return true;
209
+ }
210
+
211
+ function isStyleLinkTypeAttribute(attrValue = '') {
212
+ attrValue = trimWhitespace(attrValue).toLowerCase();
213
+ return attrValue === '' || attrValue === 'text/css';
214
+ }
215
+
216
+ /**
217
+ * @param {string} tag
218
+ * @param {HTMLAttribute[]} attrs
219
+ */
220
+ function isStyleElement(tag, attrs) {
221
+ if (tag !== 'style') {
222
+ return false;
223
+ }
224
+ for (const attr of attrs) {
225
+ if (attr.name.toLowerCase() === 'type') {
226
+ return isStyleLinkTypeAttribute(attr.value);
227
+ }
228
+ }
229
+ return true;
230
+ }
231
+
232
+ /**
233
+ * @param {string} attrName
234
+ * @param {string} attrValue
235
+ */
236
+ function isBooleanAttribute(attrName, attrValue) {
237
+ return isSimpleBoolean.has(attrName) ||
238
+ (attrName === 'draggable' && !isBooleanValue.has(attrValue)) ||
239
+ (collapsibleValues.has(attrName) && collapsibleValues.get(attrName)?.has(attrValue));
240
+ }
241
+
242
+ const uriTypeAttributes = new Map([
243
+ ['a', new Set(['href'])],
244
+ ['area', new Set(['href'])],
245
+ ['link', new Set(['href'])],
246
+ ['base', new Set(['href'])],
247
+ ['img', new Set(['src', 'longdesc', 'usemap'])],
248
+ ['object', new Set(['classid', 'codebase', 'data', 'usemap'])],
249
+ ['q', new Set(['cite'])],
250
+ ['blockquote', new Set(['cite'])],
251
+ ['ins', new Set(['cite'])],
252
+ ['del', new Set(['cite'])],
253
+ ['form', new Set(['action'])],
254
+ ['input', new Set(['src', 'usemap'])],
255
+ ['head', new Set(['profile'])],
256
+ ['script', new Set(['src', 'for'])]
257
+ ]);
258
+
259
+ /**
260
+ * @param {string} attrName
261
+ * @param {string} tag
262
+ */
263
+ function isUriTypeAttribute(attrName, tag) {
264
+ const set = uriTypeAttributes.get(tag);
265
+ return set ? set.has(attrName) : false;
266
+ }
267
+
268
+ const numberTypeAttributes = new Map([
269
+ ['a', new Set(['tabindex'])],
270
+ ['area', new Set(['tabindex'])],
271
+ ['object', new Set(['tabindex'])],
272
+ ['button', new Set(['tabindex'])],
273
+ ['input', new Set(['maxlength', 'tabindex'])],
274
+ ['select', new Set(['size', 'tabindex'])],
275
+ ['textarea', new Set(['rows', 'cols', 'tabindex'])],
276
+ ['colgroup', new Set(['span'])],
277
+ ['col', new Set(['span'])],
278
+ ['th', new Set(['rowspan', 'colspan'])],
279
+ ['td', new Set(['rowspan', 'colspan'])]
280
+ ]);
281
+
282
+ /**
283
+ * @param {string} attrName
284
+ * @param {string} tag
285
+ */
286
+ function isNumberTypeAttribute(attrName, tag) {
287
+ const set = numberTypeAttributes.get(tag);
288
+ return set ? set.has(attrName) : false;
289
+ }
290
+
291
+ /**
292
+ * @param {string} tag
293
+ * @param {HTMLAttribute[]} attrs
294
+ * @param {string} value
295
+ */
296
+ function isLinkType(tag, attrs, value) {
297
+ if (tag !== 'link') return false;
298
+ const needle = String(value).toLowerCase();
299
+ for (const attr of attrs) {
300
+ if (attr.name.toLowerCase() === 'rel') {
301
+ const tokens = String(attr.value).toLowerCase().split(/\s+/);
302
+ if (tokens.includes(needle)) return true;
303
+ }
304
+ }
305
+ return false;
306
+ }
307
+
308
+ /**
309
+ * @param {string} tag
310
+ * @param {HTMLAttribute[]} attrs
311
+ * @param {string} attrName
312
+ */
313
+ function isMediaQuery(tag, attrs, attrName) {
314
+ return attrName === 'media' && (isLinkType(tag, attrs, 'stylesheet') || isStyleElement(tag, attrs));
315
+ }
316
+
317
+ /**
318
+ * @param {string} attrName
319
+ * @param {string} tag
320
+ */
321
+ function isSrcset(attrName, tag) {
322
+ return (attrName === 'srcset' && srcsetElements.has(tag)) ||
323
+ (attrName === 'imagesrcset' && tag === 'link');
324
+ }
325
+
326
+ /**
327
+ * @param {string} tag
328
+ * @param {HTMLAttribute[]} attrs
329
+ */
330
+ function isMetaViewport(tag, attrs) {
331
+ if (tag !== 'meta') {
332
+ return false;
333
+ }
334
+ for (const attr of attrs) {
335
+ if (attr.name.toLowerCase() === 'name' && (attr.value || '').toLowerCase() === 'viewport') {
336
+ return true;
337
+ }
338
+ }
339
+ return false;
340
+ }
341
+
342
+ /**
343
+ * @param {string} tag
344
+ * @param {HTMLAttribute[]} attrs
345
+ */
346
+ function isContentSecurityPolicy(tag, attrs) {
347
+ if (tag !== 'meta') {
348
+ return false;
349
+ }
350
+ for (const attr of attrs) {
351
+ if (attr.name.toLowerCase() === 'http-equiv' && (attr.value || '').toLowerCase() === 'content-security-policy') {
352
+ return true;
353
+ }
354
+ }
355
+ return false;
356
+ }
357
+
358
+ /**
359
+ * @param {string} tag
360
+ * @param {string} attrName
361
+ * @param {string | undefined} attrValue
362
+ * @param {{removeEmptyAttributes?: boolean | Function}} options
363
+ */
364
+ function canDeleteEmptyAttribute(tag, attrName, attrValue, options) {
365
+ const isValueEmpty = !attrValue || attrValue.trim() === '';
366
+ if (!isValueEmpty) {
367
+ return false;
368
+ }
369
+ if (typeof options.removeEmptyAttributes === 'function') {
370
+ return options.removeEmptyAttributes(attrName, tag);
371
+ }
372
+ return (tag === 'input' && attrName === 'value') || RE_EMPTY_ATTRIBUTE.test(attrName);
373
+ }
374
+
375
+ /**
376
+ * @param {string} name
377
+ * @param {HTMLAttribute[]} attrs
378
+ */
379
+ function hasAttrName(name, attrs) {
380
+ for (const attr of attrs) {
381
+ if (attr.name === name) {
382
+ return true;
383
+ }
384
+ }
385
+ return false;
386
+ }
387
+
388
+ // Cleaners
389
+
390
+ const collapseAttributeWhitespaceExempt = new Set(['pattern', 'placeholder', 'title']);
391
+ // `value` whitespace matters only on form-submission and machine-readable elements
392
+ const valueWhitespaceExemptElements = new Set(['button', 'data', 'input', 'option', 'param']);
393
+
394
+ // Returns the cleaned attribute value directly (sync) or as a Promise (async);
395
+ // callers must handle both cases—use `isThenable()` to distinguish
396
+ /**
397
+ * @param {string} tag
398
+ * @param {string} attrName
399
+ * @param {string} attrValue
400
+ * @param {ProcessedOptions} options
401
+ * @param {HTMLAttribute[]} attrs
402
+ * @param {Function} minifyHTMLSelf
403
+ */
404
+ function cleanAttributeValue(tag, attrName, attrValue, options, attrs, minifyHTMLSelf) {
405
+ const isEventAttr = isEventAttribute(attrName, options);
406
+
407
+ // Apply early whitespace normalization if enabled
408
+ // Preserves special spaces (no-break space, hair space, etc.) for consistency with `collapseWhitespace`
409
+ if (options.collapseAttributeWhitespace && !collapseAttributeWhitespaceExempt.has(attrName) && !(attrName === 'value' && valueWhitespaceExemptElements.has(tag)) && !isEventAttr) {
410
+ // Fast path: Only process if whitespace exists (avoids regex overhead on clean values)
411
+ if (RE_ATTR_WS_CHECK.test(attrValue)) {
412
+ // Two-pass approach (faster than single-pass with callback)
413
+ // First: Collapse internal whitespace sequences to single space
414
+ // Second: Trim leading/trailing whitespace
415
+ attrValue = attrValue.replace(RE_ATTR_WS_COLLAPSE, ' ').replace(RE_ATTR_WS_TRIM, '');
416
+ }
417
+ }
418
+
419
+ if (isEventAttr) {
420
+ attrValue = trimWhitespace(attrValue).replace(/^javascript:\s*/i, '');
421
+ // Browsers decode attribute values before running event-handler JS—
422
+ // decode first so the minifier gets valid JavaScript
423
+ if (!options.decodeEntities && options.minifyJS !== identity && attrValue.indexOf('&') !== -1) {
424
+ return getDecodeHTMLStrict().then(decode => {
425
+ const decoded = decode(attrValue);
426
+ const result = options.minifyJS(decoded, true);
427
+ const reEncode = (/** @type {string} */ v) => (v && v.indexOf('&') !== -1) ? v.replace(RE_AMP_ENTITY, '&amp;$1') : v;
428
+ if (isThenable(result)) {
429
+ return result.then(reEncode, (/** @type {Error} */ err) => {
430
+ if (!options.continueOnMinifyError) throw err;
431
+ options.log && options.log(err);
432
+ return attrValue;
433
+ });
434
+ }
435
+ return reEncode(result);
436
+ });
437
+ }
438
+ const result = options.minifyJS(attrValue, true);
439
+ if (isThenable(result)) {
440
+ return result.catch((/** @type {Error} */ err) => {
441
+ if (!options.continueOnMinifyError) throw err;
442
+ options.log && options.log(err);
443
+ return attrValue;
444
+ });
445
+ }
446
+ return result;
447
+ }
448
+
449
+ if (attrName === 'class') {
450
+ attrValue = trimWhitespace(attrValue);
451
+ if (options.sortClassNames) {
452
+ // By the time attributes are processed, `createSortFns` has replaced any truthy non-function value
453
+ attrValue = /** @type {(value: string) => string} */ (options.sortClassNames)(attrValue);
454
+ } else {
455
+ attrValue = collapseWhitespaceAll(attrValue);
456
+ }
457
+ return attrValue;
458
+ }
459
+
460
+ if (isUriTypeAttribute(attrName, tag)) {
461
+ attrValue = trimWhitespace(attrValue);
462
+ if (isLinkType(tag, attrs, 'canonical')) {
463
+ return attrValue;
464
+ }
465
+ const result = options.minifyURLs(attrValue);
466
+ if (isThenable(result)) {
467
+ return result
468
+ .then((/** @type {unknown} */ out) => typeof out === 'string' ? out : attrValue)
469
+ .catch((/** @type {Error} */ err) => {
470
+ if (!options.continueOnMinifyError) throw err;
471
+ options.log && options.log(err);
472
+ return attrValue;
473
+ });
474
+ }
475
+ return typeof result === 'string' ? result : attrValue;
476
+ }
477
+
478
+ if (isNumberTypeAttribute(attrName, tag)) {
479
+ return trimWhitespace(attrValue);
480
+ }
481
+
482
+ if (attrName === 'style') {
483
+ attrValue = trimWhitespace(attrValue);
484
+ if (attrValue) {
485
+ if (attrValue.endsWith(';') && !/&#?[0-9a-zA-Z]+;$/.test(attrValue)) {
486
+ attrValue = attrValue.replace(/\s*;$/, ';');
487
+ }
488
+ const originalAttrValue = attrValue;
489
+ const cssResult = options.minifyCSS(attrValue, 'inline', options.cssContext);
490
+ if (isThenable(cssResult)) {
491
+ return cssResult
492
+ .then((/** @type {string} */ minified) => {
493
+ // After minification, check if CSS consists entirely of invalid properties (no values)
494
+ // I.e., `color:` or `margin:;padding:` should be treated as empty
495
+ if (minified && /^(?:[a-z-]+:[;\s]*)+$/i.test(minified)) return '';
496
+ return minified;
497
+ })
498
+ .catch((/** @type {Error} */ err) => {
499
+ if (!options.continueOnMinifyError) throw err;
500
+ options.log && options.log(err);
501
+ return originalAttrValue;
502
+ });
503
+ }
504
+ // Sync path (`minifyCSS` disabled—identity function)
505
+ if (cssResult && /^(?:[a-z-]+:[;\s]*)+$/i.test(cssResult)) return '';
506
+ return cssResult ?? attrValue;
507
+ }
508
+ return attrValue;
509
+ }
510
+
511
+ if (isSrcset(attrName, tag)) {
512
+ // Split into image candidate strings following the spec parsing algorithm
513
+ // (https://html.spec.whatwg.org/multipage/images.html#parsing-a-srcset-attribute);
514
+ // a naive split on commas would corrupt URLs that contain commas
515
+ const value = trimWhitespace(attrValue);
516
+ /** @type {string[]} */
517
+ const candidates = [];
518
+ let pos = 0;
519
+ while (pos < value.length) {
520
+ // Skip whitespace and separator commas
521
+ while (pos < value.length && /[\s,]/.test(value.charAt(pos))) pos++;
522
+ if (pos >= value.length) break;
523
+ const start = pos;
524
+ // URL: a run of non-whitespace characters (which may contain commas)
525
+ while (pos < value.length && !/\s/.test(value.charAt(pos))) pos++;
526
+ if (value.charAt(pos - 1) === ',') {
527
+ // Trailing comma(s) end the candidate—a URL without descriptor
528
+ candidates.push(value.slice(start, pos).replace(/,+$/, ''));
529
+ continue;
530
+ }
531
+ // Descriptor: everything up to the next comma outside parentheses
532
+ let inParens = false;
533
+ while (pos < value.length && (inParens || value.charAt(pos) !== ',')) {
534
+ if (value.charAt(pos) === '(') inParens = true;
535
+ else if (value.charAt(pos) === ')') inParens = false;
536
+ pos++;
537
+ }
538
+ candidates.push(trimWhitespace(value.slice(start, pos)));
539
+ }
540
+ const processed = candidates.map(candidate => {
541
+ let url = candidate;
542
+ let descriptor = '';
543
+ const match = candidate.match(/\s+([1-9][0-9]*w|[0-9]+(?:\.[0-9]+)?x)$/);
544
+ if (match) {
545
+ url = url.slice(0, -match[0].length);
546
+ const group = match[1] ?? '';
547
+ const num = +group.slice(0, -1);
548
+ const suffix = group.slice(-1);
549
+ if (num !== 1 || suffix !== 'x') {
550
+ descriptor = ' ' + num + suffix;
551
+ }
552
+ }
553
+ const out = options.minifyURLs(url);
554
+ if (isThenable(out)) {
555
+ return out
556
+ .then((/** @type {unknown} */ result) => (typeof result === 'string' ? result : url) + descriptor)
557
+ .catch((/** @type {Error} */ err) => {
558
+ if (!options.continueOnMinifyError) throw err;
559
+ options.log && options.log(err);
560
+ return url + descriptor;
561
+ });
562
+ }
563
+ return (typeof out === 'string' ? out : url) + descriptor;
564
+ });
565
+ if (processed.some(isThenable)) {
566
+ return Promise.all(processed).then(results => results.join(', '));
567
+ }
568
+ return processed.join(', ');
569
+ }
570
+
571
+ if (attrName === 'content' && isMetaViewport(tag, attrs)) {
572
+ return attrValue.replace(/\s+/g, '').replace(/[0-9]+\.[0-9]+/g, function (numString) {
573
+ // 0.90000 → 0.9
574
+ // 1.0 → 1
575
+ // 1.0001 → 1.0001 (unchanged)
576
+ return (+numString).toString();
577
+ });
578
+ }
579
+
580
+ if (attrName.toLowerCase() === 'content' && isContentSecurityPolicy(tag, attrs)) {
581
+ return collapseWhitespaceAll(attrValue);
582
+ }
583
+
584
+ if (options.customAttrCollapse && options.customAttrCollapse.test(attrName)) {
585
+ return trimWhitespace(attrValue.replace(/ ?[\n\r]+ ?/g, '').replace(/\s{2,}/g, options.conservativeCollapse ? ' ' : ''));
586
+ }
587
+
588
+ if (tag === 'script' && attrName === 'type') {
589
+ return trimWhitespace(attrValue.replace(/\s*;\s*/g, ';'));
590
+ }
591
+
592
+ if (isMediaQuery(tag, attrs, attrName)) {
593
+ attrValue = trimWhitespace(attrValue);
594
+ // Only minify actual media queries (those with features in parentheses)
595
+ // Skip simple media types like `all`, `screen`, `print` which are already minimal
596
+ if (!/[()]/.test(attrValue)) {
597
+ return attrValue;
598
+ }
599
+ const originalAttrValue = attrValue;
600
+ const cssResult = options.minifyCSS(attrValue, 'media', options.cssContext);
601
+ if (isThenable(cssResult)) {
602
+ return cssResult.catch((/** @type {Error} */ err) => {
603
+ if (!options.continueOnMinifyError) throw err;
604
+ options.log && options.log(err);
605
+ return originalAttrValue;
606
+ });
607
+ }
608
+ return cssResult ?? attrValue;
609
+ }
610
+
611
+ if (tag === 'iframe' && attrName === 'srcdoc') {
612
+ // Fast-path: Skip if nothing would change
613
+ if (!shouldMinifyInnerHTML(options)) {
614
+ return attrValue;
615
+ }
616
+ return minifySrcdoc(attrValue, options, minifyHTMLSelf);
617
+ }
618
+
619
+ return attrValue;
620
+ }
621
+
622
+ /**
623
+ * Recursively minify the document an `iframe srcdoc` attribute holds.
624
+ *
625
+ * Browsers resolve character references before parsing `srcdoc`, so an
626
+ * entity-encoded document is decoded first (unless `decodeEntities` already
627
+ * did) and re-encoded afterwards—but only then, so a literal value passes
628
+ * through byte-identical.
629
+ *
630
+ * @param {string} attrValue
631
+ * @param {ProcessedOptions} options
632
+ * @param {Function} minifyHTMLSelf
633
+ * @returns {Promise<string>}
634
+ */
635
+ async function minifySrcdoc(attrValue, options, minifyHTMLSelf) {
636
+ let markup = attrValue;
637
+ let wasEncoded = false;
638
+ if (!options.decodeEntities && attrValue.indexOf('&') !== -1) {
639
+ const decode = await getDecodeHTMLStrict();
640
+ markup = decode(attrValue);
641
+ wasEncoded = markup !== attrValue;
642
+ }
643
+
644
+ let srcdocOptions = options;
645
+ // The inner document sees none of the parent’s markup, so its style sheets
646
+ // minify against the symbols the `srcdoc` content references itself
647
+ if (options.removeUnusedCSS && RE_STYLE_ELEMENT.test(markup)) {
648
+ const decode = markup.indexOf('&') !== -1 ? await getDecodeHTMLStrict() : undefined;
649
+ srcdocOptions = {
650
+ ...options,
651
+ cssContext: {
652
+ warned: options.cssContext ? options.cssContext.warned : new Set(),
653
+ usedSymbols: collectUsedSymbols(markup, options.removeUnusedCSS.scripts, /** @type {((text: string) => string) | undefined} */ (decode))
654
+ }
655
+ };
656
+ }
657
+
658
+ try {
659
+ const minified = await minifyHTMLSelf(markup, srcdocOptions, true);
660
+ return wasEncoded ? (await getEscapeAttribute())(minified) : minified;
661
+ } catch (err) {
662
+ if (!options.continueOnMinifyError) throw err;
663
+ options.log && options.log(/** @type {Error} */ (err));
664
+ return attrValue;
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Choose appropriate quote character for an attribute value
670
+ * @param {string} attrValue - The attribute value
671
+ * @param {{quoteCharacter?: string}} options - Minifier options
672
+ * @returns {string} The chosen quote character (`"` or `'`)
673
+ */
674
+ function chooseAttributeQuote(attrValue, options) {
675
+ if (typeof options.quoteCharacter !== 'undefined') {
676
+ return options.quoteCharacter === '\'' ? '\'' : '"';
677
+ }
678
+
679
+ // Count quotes in a single pass
680
+ let apos = 0, quot = 0;
681
+ for (let i = 0; i < attrValue.length; i++) {
682
+ if (attrValue[i] === "'") apos++;
683
+ else if (attrValue[i] === '"') quot++;
684
+ }
685
+ return apos < quot ? '\'' : '"';
686
+ }
687
+
688
+ // Returns the normalized attribute object directly (sync) or as a Promise (async);
689
+ // callers must handle both cases—use `isThenable()` to distinguish
690
+ /**
691
+ * @param {HTMLAttribute} attr
692
+ * @param {HTMLAttribute[]} attrs
693
+ * @param {string} tag
694
+ * @param {ProcessedOptions} options
695
+ * @param {Function} minifyHTML
696
+ */
697
+ function normalizeAttr(attr, attrs, tag, options, minifyHTML) {
698
+ const attrName = options.name(attr.name);
699
+ const attrValue = attr.value;
700
+
701
+ // Entity decoding requires a lazy import—async only when `&` is present
702
+ if (options.decodeEntities && attrValue && attrValue.indexOf('&') !== -1) {
703
+ return getDecodeHTMLStrict().then(decode => {
704
+ return normalizeAttrContinue(attrName, decode(attrValue), attr, attrs, tag, options, minifyHTML);
705
+ });
706
+ }
707
+
708
+ return normalizeAttrContinue(attrName, attrValue, attr, attrs, tag, options, minifyHTML);
709
+ }
710
+
711
+ // Internal: Handles attribute normalization after entity decoding (if any)
712
+ /**
713
+ * @param {string} attrName
714
+ * @param {string | undefined} attrValue
715
+ * @param {HTMLAttribute} attr
716
+ * @param {HTMLAttribute[]} attrs
717
+ * @param {string} tag
718
+ * @param {ProcessedOptions} options
719
+ * @param {Function} minifyHTML
720
+ */
721
+ function normalizeAttrContinue(attrName, attrValue, attr, attrs, tag, options, minifyHTML) {
722
+ if ((options.removeRedundantAttributes &&
723
+ isAttributeRedundant(tag, attrName, attrValue ?? '', attrs)) ||
724
+ (options.removeDefaultTypeAttributes && attrName === 'type' && (
725
+ ((tag === 'style' || tag === 'link') && isStyleLinkTypeAttribute(attrValue)) ||
726
+ (tag === 'script' && isScriptTypeAttribute(attrValue) && !keepScriptTypeAttribute(attrValue))
727
+ ))) {
728
+ return;
729
+ }
730
+
731
+ if (attrValue) {
732
+ const cleaned = cleanAttributeValue(tag, attrName, attrValue, options, attrs, minifyHTML);
733
+ if (isThenable(cleaned)) {
734
+ return cleaned.then((/** @type {string | undefined} */ v) => normalizeAttrFinish(attrName, v, attr, tag, options));
735
+ }
736
+ return normalizeAttrFinish(attrName, cleaned, attr, tag, options);
737
+ }
738
+
739
+ return normalizeAttrFinish(attrName, attrValue, attr, tag, options);
740
+ }
741
+
742
+ // Internal: Final checks and result assembly after value cleaning
743
+ /**
744
+ * @param {string} attrName
745
+ * @param {string | undefined} attrValue
746
+ * @param {HTMLAttribute} attr
747
+ * @param {string} tag
748
+ * @param {ProcessedOptions} options
749
+ */
750
+ function normalizeAttrFinish(attrName, attrValue, attr, tag, options) {
751
+ if (options.removeEmptyAttributes &&
752
+ canDeleteEmptyAttribute(tag, attrName, attrValue, options)) {
753
+ return;
754
+ }
755
+
756
+ if (options.decodeEntities && attrValue && attrValue.indexOf('&') !== -1) {
757
+ attrValue = attrValue.replace(RE_AMP_ENTITY, '&amp;$1');
758
+ }
759
+
760
+ return {
761
+ attr,
762
+ name: attrName,
763
+ value: attrValue
764
+ };
765
+ }
766
+
767
+ /**
768
+ * @param {{name: string, value: string | undefined, attr: HTMLAttribute}} normalized
769
+ * @param {string | boolean | undefined} hasUnarySlash
770
+ * @param {ProcessedOptions} options
771
+ * @param {boolean} isLast
772
+ * @param {string | undefined} uidAttr
773
+ */
774
+ function buildAttr(normalized, hasUnarySlash, options, isLast, uidAttr) {
775
+ const attrName = normalized.name;
776
+ let attrValue = normalized.value;
777
+ const attr = normalized.attr;
778
+ let attrQuote = attr.quote;
779
+ let attrFragment;
780
+ let emittedAttrValue;
781
+
782
+ // Determine if need to add/keep quotes
783
+ const shouldAddQuotes = typeof attrValue !== 'undefined' && (
784
+ // If `removeAttributeQuotes` is enabled, add quotes only if they can’t be removed
785
+ (options.removeAttributeQuotes && ((uidAttr ? attrValue.indexOf(uidAttr) !== -1 : false) || !canRemoveAttributeQuotes(attrValue))) ||
786
+ // If `removeAttributeQuotes` is not enabled, preserve original quote style or add quotes if value requires them
787
+ (!options.removeAttributeQuotes && (attrQuote !== '' || !canRemoveAttributeQuotes(attrValue) ||
788
+ // SVGO reads the whole SVG block as XML, where every attribute value carries quotes
789
+ (Boolean(options.insideSVG) && Boolean(options.minifySVG)) ||
790
+ // Special case: With `removeTagWhitespace`, unquoted values that aren’t last will have space added,
791
+ // which can create ambiguous/invalid HTML—add quotes to be safe
792
+ (options.removeTagWhitespace && attrQuote === '' && !isLast)))
793
+ );
794
+
795
+ if (shouldAddQuotes) {
796
+ attrValue = attrValue ?? '';
797
+ // Determine the appropriate quote character
798
+ if (!options.preventAttributesEscaping) {
799
+ // Normal mode: Choose optimal quote type to minimize escaping
800
+ // unless preserving original quotes and they don’t need escaping
801
+ const needsEscaping = (attrQuote === '"' && attrValue.indexOf('"') !== -1) || (attrQuote === "'" && attrValue.indexOf("'") !== -1);
802
+
803
+ if (options.removeAttributeQuotes || typeof options.quoteCharacter !== 'undefined' || needsEscaping || attrQuote === '') {
804
+ attrQuote = chooseAttributeQuote(attrValue, options);
805
+ }
806
+
807
+ if (attrQuote === '"') {
808
+ attrValue = attrValue.replace(/"/g, '&#34;');
809
+ } else {
810
+ attrValue = attrValue.replace(/'/g, '&#39;');
811
+ }
812
+ } else {
813
+ // `preventAttributesEscaping` mode: Choose safe quotes but don’t escape
814
+ // except when both quote types are present—then escape to prevent invalid HTML
815
+ const hasDoubleQuote = attrValue.indexOf('"') !== -1;
816
+ const hasSingleQuote = attrValue.indexOf("'") !== -1;
817
+
818
+ // Both quote types present: Escaping is required to guarantee valid HTML delimiter matching
819
+ if (hasDoubleQuote && hasSingleQuote) {
820
+ attrQuote = chooseAttributeQuote(attrValue, options);
821
+ if (attrQuote === '"') {
822
+ attrValue = attrValue.replace(/"/g, '&#34;');
823
+ } else {
824
+ attrValue = attrValue.replace(/'/g, '&#39;');
825
+ }
826
+ // Auto quote selection: Prefer the opposite quote type when value contains one quote type, default to double quotes when none present
827
+ } else if (typeof options.quoteCharacter === 'undefined') {
828
+ if (attrQuote === '"' && hasDoubleQuote && !hasSingleQuote) {
829
+ attrQuote = "'";
830
+ } else if (attrQuote === "'" && hasSingleQuote && !hasDoubleQuote) {
831
+ attrQuote = '"';
832
+ // If no quote character yet (empty string), choose based on content
833
+ } else if (attrQuote === '') {
834
+ if (hasSingleQuote && !hasDoubleQuote) {
835
+ attrQuote = '"';
836
+ } else if (hasDoubleQuote && !hasSingleQuote) {
837
+ attrQuote = "'";
838
+ } else {
839
+ attrQuote = '"';
840
+ }
841
+ // Fallback for invalid/unsupported attrQuote values (not `"`, `'`, or empty string):
842
+ // Choose safe default based on value content
843
+ } else if (attrQuote !== '"' && attrQuote !== "'") {
844
+ if (hasSingleQuote && !hasDoubleQuote) {
845
+ attrQuote = '"';
846
+ } else if (hasDoubleQuote && !hasSingleQuote) {
847
+ attrQuote = "'";
848
+ } else {
849
+ attrQuote = '"';
850
+ }
851
+ }
852
+ } else {
853
+ // `quoteCharacter` is explicitly set
854
+ const preferredQuote = options.quoteCharacter === '\'' ? '\'' : '"';
855
+ // Safety check: If the preferred quote conflicts with value content, switch to the opposite quote
856
+ if ((preferredQuote === '"' && hasDoubleQuote && !hasSingleQuote) || (preferredQuote === "'" && hasSingleQuote && !hasDoubleQuote)) {
857
+ attrQuote = preferredQuote === '"' ? "'" : '"';
858
+ } else if ((preferredQuote === '"' && hasDoubleQuote && hasSingleQuote) || (preferredQuote === "'" && hasSingleQuote && hasDoubleQuote)) {
859
+ // Both quote types present: Fall back to escaping despite `preventAttributesEscaping`
860
+ attrQuote = preferredQuote;
861
+ if (attrQuote === '"') {
862
+ attrValue = attrValue.replace(/"/g, '&#34;');
863
+ } else {
864
+ attrValue = attrValue.replace(/'/g, '&#39;');
865
+ }
866
+ } else {
867
+ attrQuote = preferredQuote;
868
+ }
869
+ }
870
+ }
871
+ emittedAttrValue = attrQuote + attrValue + attrQuote;
872
+ if (!isLast && !options.removeTagWhitespace) {
873
+ emittedAttrValue += ' ';
874
+ }
875
+ } else if (isLast && !hasUnarySlash) {
876
+ // Last attribute in a non-self-closing tag:
877
+ // No space needed
878
+ emittedAttrValue = attrValue;
879
+ } else {
880
+ // Not last attribute, or is a self-closing tag:
881
+ // Unquoted values must have space after them to delimit from next attribute
882
+ emittedAttrValue = attrValue + ' ';
883
+ }
884
+
885
+ if (typeof attrValue === 'undefined' || (options.collapseBooleanAttributes &&
886
+ isBooleanAttribute(attrName.toLowerCase(), (attrValue || '').toLowerCase()))) {
887
+ attrFragment = attrName;
888
+ if (!isLast) {
889
+ attrFragment += ' ';
890
+ }
891
+ } else {
892
+ attrFragment = attrName + attr.customAssign + emittedAttrValue;
893
+ }
894
+
895
+ return attr.customOpen + attrFragment + attr.customClose;
896
+ }
897
+
898
+ // Exports
899
+
900
+ export {
901
+ // Validators
902
+ isIgnoredComment,
903
+ isEventAttribute,
904
+ canRemoveAttributeQuotes,
905
+ attributesInclude,
906
+ isAttributeRedundant,
907
+ isScriptTypeAttribute,
908
+ keepScriptTypeAttribute,
909
+ isExecutableScript,
910
+ isStyleLinkTypeAttribute,
911
+ isStyleElement,
912
+ isBooleanAttribute,
913
+ isUriTypeAttribute,
914
+ isNumberTypeAttribute,
915
+ isLinkType,
916
+ isMediaQuery,
917
+ isSrcset,
918
+ isMetaViewport,
919
+ isContentSecurityPolicy,
920
+ canDeleteEmptyAttribute,
921
+ hasAttrName,
922
+
923
+ // Cleaners
924
+ cleanAttributeValue,
925
+ normalizeAttr,
926
+ buildAttr,
927
+ deduplicateAttributes
928
+ };